I've coded up a program that can read rgb values off of a jpg file, but when i test it with a solid color i'm getting rgb results that are slightly inaccurate. Does anyone know if its my code or if its java that is inaccurate?
RGB
red=64 green=0 blue=128
RESULT
red=65 green=0 blue=128
CODE
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.util.ArrayList;
import javax.imageio.*;
public class Program {
public int[][] rgbValues;
public File imagePath = new File("src/image3.jpg");
public BufferedImage image;
public Program() throws IOException{
image = ImageIO.read(imagePath);
rgbValues = new int[image.getWidth()][image.getHeight()];
}
public void run() throws IOException{
getData();
analyzeData();
}
private void getData() throws IOException{
for (int y = 0; y < image.getHeight(); y++){
for (int x = 0; x < image.getWidth(); x++){
rgbValues[y][x] = image.getRGB(x, y);
}
}
}
private void analyzeData() throws IOException{
boolean f = image.getAlphaRaster() != null;
Color color = new Color(rgbValues[10][10], f);
System.out.println(color.getRed());
System.out.println(color.getGreen());
System.out.println(color.getBlue());
}
}
Code seems correct and results as well, Paint says the image is also (65,0,128)
Related
This question already has answers here:
Getting error with ImageIO.read(getClass().getResourceAsStream (input==NULL)?
(2 answers)
Closed 4 years ago.
So I am trying to make a simple graphical interface for a game, So I made a sprite sheet to go along with it. But in my class <SpriteSheet.java> I am coming accross this error:
Exception in thread "main" java.lang.IllegalArgumentException: input == null! at javax.imageio.ImageIO.read(Unknown Source)
at matrix.game.gfx.SpriteSheet.<init>(SpriteSheet.java:18)
Here is <SpriteSheet.java>
package matrix.game.gfx;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
public class SpriteSheet {
public String path;
public int width;
public int height;
public int[] pixels;
public SpriteSheet(String path) {
BufferedImage image = null;
try {
image = ImageIO.read(SpriteSheet.class.getResourceAsStream(path));
} catch (IOException e) {
e.printStackTrace();
}
if(image == null) {
return;
}
this.path = path;
this.width = image.getWidth();
this.height = image.getHeight();
pixels = image.getRGB(0,0, width, height, null, 0, width);
for (int i = 0; i < pixels.length; i++) {
pixels[i] = (pixels[i] & 0xff)/64;
}
for (int i = 0; i < 8; i++) {
System.out.println(pixels[i]);
}
}
}
You are trying to execute function not declared in your class:
image = ImageIO.read(SpriteSheet.class.getResourceAsStream(path));
Because of that it fails try { and throws the exception it cannot handle.
As you can see in the code below, the method read of ImageIO class will throw an IllegalArgumentException when the parameter input is null.
public static BufferedImage read(InputStream input) throws IOException {
if (input == null) {
throw new IllegalArgumentException("input == null!");
}
ImageInputStream stream = createImageInputStream(input);
BufferedImage bi = read(stream);
if (bi == null) {
stream.close();
}
return bi;
}
This following line is trying to find the resource inside the package matrix.game.gfx.
SpriteSheet.class.getResourceAsStream(path)
If you are trying to access a file from a directory other than the class package, you should change the code as follows:
SpriteSheet.class.getClassLoader().getResourceAsStream(fullPath);
In the code above the classloader will starts the search in the root of the classpath.
This worked for me.
Hope it does for you too.
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class SpriteSheet {
public String path;
public int width;
public int height;
public int[] pixels;
public SpriteSheet(String path) {
BufferedImage image = null;
//Adding a directory(FILE) object for the path specified
File dir = new File(path);
try {
//Reading from the specifies directory
image = ImageIO.read(dir);
} catch (IOException e) {
e.printStackTrace();
}
if(image == null) {
return;
}
this.path = path;
this.width = image.getWidth();
this.height = image.getHeight();
pixels = image.getRGB(0,0, width, height, null, 0, width);
for (int i = 0; i < pixels.length; i++) {
pixels[i] = (pixels[i] & 0xff)/64;
}
for (int i = 0; i < 8; i++) {
System.out.println(pixels[i]);
}
}
public static void main(String[] args) {
new SpriteSheet(path/to/file);
}
}
I am trying to write a simple code to write a red 100x100 jpg
For some reason the colors are not right,
I am only setting the color RED :
renderdImg.setRGB(x, y, Color.RED.getRGB());
but the fnal image comes out purplish, what am I doing wrong?
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageWriter {
public static void main(String[] args) throws IOException {
String fileName = "red_100.jpg";
String filePath = "c:\\temp\\";
int width = 100;
int height = 100;
BufferedImage renderdImg = new BufferedImage(width,height, BufferedImage.TYPE_INT_ARGB);
for(int x=0;x< width; x++) {
for(int y=0;y<height; y++) {
renderdImg.setRGB(x, y, Color.RED.getRGB());
}}
File fileToWrite = new File(filePath + fileName);
ImageIO.write(renderdImg, "jpg", fileToWrite);
}
}
Set the image type to BufferedImage.TYPE_INT_RGB and it should become reddish:
BufferedImage renderdImg = new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB);
What is the shortest code one can write in java to break an image (say 200x1000) into 10 images of a tenth height but same width (200x 100)?
Mine is a pretty long code; the main part , I am just giving:
for (int i_=0;i_<10;i_++)
{
for(int k=i_*100;k<i_*100+h/10;k++)
{
for(int j_=0;j_<w;j_++)
{
int pixv=img.getRGB(j_,k);
r=(pixv>>16)&0xff;
g=(pixv>>8)&0xff;
b=(pixv)&0xff;
int rgb=new Color(r,g,b).getRGB();
img.setRGB(j_,k-i_*200,rgb);
}
}
// Here I am writing the img to a new .bmp file thus creating 10 seperate files
}
Here img is a BufferedImage
w,h the width and height of large image
you can get a sub image from BufferedImage using getSubimage(int x,int y,int w,int h). Try this:
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class NewClass9 {
public static void main(String[] args) throws IOException{
BufferedImage img = null;
img = ImageIO.read(new File("C:\\users\\uzochi\\desktop\\Penguins.jpg"));
for(int i = 0;i<10;i++){
BufferedImage sub = img.getSubimage(0, i*(img.getHeight()/10), img.getWidth(), img.getHeight()/10);
File f = new File("C:\\users\\uzochi\\desktop\\SubImage"+i+".png");
ImageIO.write(sub, "png", f);
}
}
}
Okay, so my friend and I are making are a game that requires some pixel analysis for the rectangles, and I wrote the code to analyze the rectangles, and It works swimmingly, However, when I try to draw the bufferedImage it doesn't show up. The main issue is that my java class has never taught us how to use Jframes, and I don't want to change my code to accommodate:
// Threaded Applet Template that works with Macs
// Import section
// Use this section to add additional libaries for use in your program.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.awt.image.BufferedImage;
import java.awt.Toolkit;
import javax.imageio.*;
import javax.swing.*;
import java.awt.image.*;
import java.io.*;
// This begins the class definition.
// Notice that this is a "world". You can tell since it extends Applet.
// It also implement Runnable which allows it to be and use threads.
public class PixelAnalyzetest extends Applet implements Runnable
{
//variable declaration section
// public datatype variablename
public int xTitle;
public int yTitle;
public Analyzer analyzer;
public BufferedImage test;
public Image itest;
public boolean analyzeonce=true;
//declare your Hero object here
//Sets up a Thread called thread
Thread thread;
// Method definition section
// init() is the first method an Applet runs when started
public void init()
{
//Initialize variables
xTitle=10;
yTitle=10;
BufferedImage test = new BufferedImage(1200,1200, BufferedImage.TYPE_INT_ARGB);
//test = getImage(getDocumentBase(),"test.png");
System.out.println("the width of the image is: "+test.getWidth(this));
try{
test = ImageIO.read(new File("test.png"));
} catch(IOException e) {};
//itest=test.getAsBufferedImage();
analyzer = new Analyzer(test, 5);
//construct objects
//construct your hero here!
//Set up the thread
//These should be the LAST lines in your init( ) method.
thread = new Thread(this); //constructs a new thread
thread.start(); //starts the thread
}//init()
// paint() is used to display things on the screen
public void paint(Graphics g)
{
setSize(1200,1200);
//Put the title on the screen.
/*for(int x=0;x<test.getWidth();x++)
{
for(int y=0;y<test.getHeight();y++)
{
BufferedImage.setRGB(x,y,analyzer.pictureRGB[x][y]);
}
}*/
g.drawImage(test,0,0,1200,1200,this);
//draw your hero's name here using g.drawString( )
}// paint()
// every thread needs a run method
// this is what the thread will do
public void run() {
// this thread loop forever and runs the paint method and then sleeps.
while(true)
{
//put what you want your program to do here.
//move your hero here by calling its move() method.
if(analyzeonce==true)
{
analyzer.analyzelines();
analyzeonce=false;
}
repaint(); // run the paint method.
//sleep
try {
thread.sleep(100);
}
catch (Exception e){ }
}//while
}// run()
}
Now my analyzer class:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.awt.image.BufferedImage;
import java.awt.Toolkit;
public class Analyzer
{
public int[][] pictureRGB;
//VARIABLE DECLARATION SECTION
//Here's where you state which variables you are going to use.
public String name; //use this format public datatype variablename;
public boolean isAlive;
public int health;
public int strength;
public String theGlove;
public int dx, dy;
public BufferedImage analyzing, bgrab;
public int imagewidth, imageheight;
public int linecounter = 0;
public int boxcounter = 0;
public boolean endline = false;
public Line lines[];
public Box boxes[];
public int totalboxes;
public boolean donean = false;
// METHOD DEFINITION SECTION
// Constructor Definition
// A constructor "builds" the object when called and give the variable initial values.
// This constructor build Heroes with all the same initial values.
public Analyzer(BufferedImage grab, int xtotalboxes)
{
//BufferedImage bgrab = (BufferedImage) grab;
//bgrab = new BufferedImage(1200,1200, BufferedImage.TYPE_INT_ARGB);
//bgrab.getGraphics().drawImage(grab,0,0,bgrab.getWidth(),bgrab.getHeight(),null);
analyzing = grab;
totalboxes = xtotalboxes;
imagewidth=analyzing.getWidth();
System.out.println(imagewidth+" Is the image's Width");
imageheight=analyzing.getHeight();
System.out.println(imagewidth+" Is the image's Height");
pictureRGB= new int[imagewidth] [imageheight];
lines = new Line[10];
boxes = new Box[20];
isAlive = true;
health = 200;
strength = 20;
for(int xpos = 1; xpos<imagewidth-1;xpos++)
{
for(int ypos = 1; ypos<imageheight-1; ypos++)
{
pictureRGB[xpos][ypos]=analyzing.getRGB(xpos,ypos);
//System.out.println(pictureRGB[xpos][ypos]);
}
}
}
public void analyzelines()
{
for(boxcounter=0; boxcounter<boxes.length; boxcounter++)
{
int tempx = 0;
int tempy = 0;
int tempw = 0;
int temph = 0;
//int pxpos = 0;
//int pypos = 0;
boolean startline=false;
boolean foundw = false;
boolean foundh = false;
if(donean==false)
{
for(int ypos = 1; ypos<imageheight-1; ypos++)
{
for(int xpos = 1; xpos<imagewidth-1;xpos++)
{
if(boxcounter>0)
{
if(pictureRGB[xpos][ypos]==-3584 && startline==false && boxes[boxcounter-1].rect.contains(new Point(xpos,ypos))==false && boxes[boxcounter-1].rect.intersects(new Rectangle(xpos-2,ypos-2,4,4))==false && isEqual(new Rectangle(xpos-2,ypos-2,4,4))==false)
{
System.out.println("--------------------------------START BOX --------------");
System.out.println("The top left corner of the box is: ("+xpos+","+ypos+")");
startline=true;
tempx=xpos;
tempy=ypos;
//System.out.println(tempx+"<<TEMPX TEMPY>>"+tempy);
}
if(startline==true && pictureRGB[xpos+1][ypos]!=pictureRGB[xpos][ypos] && foundw==false && foundh==false && boxes[boxcounter-1].rect.contains(new Point(xpos,ypos))==false && isEqual(new Rectangle(xpos-2,ypos-2,4,4))==false)
{
tempw=xpos-tempx;
System.out.println("XPOS EQ = "+xpos+" - "+tempx+" = "+ tempw);
foundw = true;
//System.out.println(tempw+"<<TEMPw TEMPx>>"+tempx+"<<<<XPOS>>>>>>>>>>>>>"+xpos);
}
if(startline==true && pictureRGB[xpos][ypos+1]!=pictureRGB[xpos][ypos] && foundh==false && foundw==true && boxes[boxcounter-1].rect.contains(new Point(xpos,ypos))==false && pictureRGB[xpos-1][ypos]==pictureRGB[xpos][ypos] && pictureRGB[xpos+1][ypos]!=pictureRGB[xpos][ypos] && isEqual(new Rectangle(xpos-2,ypos-2,4,4))==false)
{
temph=ypos-tempy;
System.out.println("YPOS EQ = "+ypos+" - "+tempy+" = "+ temph);
foundh=true;
System.out.println("The Width is: "+tempw+" The height is: "+temph+" boxcounter="+boxcounter);
boxes[boxcounter]= new Box(tempx, tempy, tempw, temph);
System.out.println("--------------------------------NEXT BOX ---------------");
//System.out.println("BOX WIDTH"+boxes[boxcounter].width + "BOX COUNTER=="+boxcounter);
}
}
if(boxcounter==0)
{
if(pictureRGB[xpos][ypos]==-3584 && startline==false)
{
System.out.println("The top left corner of the box is: ("+xpos+","+ypos+")");
startline=true;
tempx=xpos;
tempy=ypos;
}
if(startline==true && pictureRGB[xpos+1][ypos]!=pictureRGB[xpos][ypos] && foundw==false && foundh==false)
{
tempw=xpos-tempx;
foundw = true;
}
if(startline==true && pictureRGB[xpos][ypos+1]!=pictureRGB[xpos][ypos] && foundh==false && foundw==true)
{
temph=ypos-tempy;
foundh=true;
System.out.println("The Width is: "+tempw+" The height is: "+temph+" boxcounter="+boxcounter);
boxes[boxcounter]= new Box(tempx, tempy, tempw, temph);
//System.out.println("BOX WIDTH"+boxes[boxcounter].width);
}
}
}
}
if(boxcounter>=(totalboxes))
{
donean=true;
}
}
//System.out.println("The black lines width is: "+(lines[linecounter].endx-lines[linecounter].startx));
}
}
public boolean isEqual(Rectangle c1)
{
boolean returned = false;
for(int i = 0; i<boxcounter; i++)
{
if(c1.intersects(boxes[i].rect) || boxes[i].rect.contains(new Point(c1.x, c1.y)))
{
returned=true;
}
}
return(returned);
}
/*
public static BufferedImage toBufferedImage(Image img)
{
if (img instanceof BufferedImage)
{
return (BufferedImage) img;
}
// Create a buffered image with transparency
BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
// Draw the image on to the buffered image
Graphics2D bGr = bimage.createGraphics();
bGr.drawImage(img, 0, 0, null);
bGr.dispose();
// Return the buffered image
return bimage;
}
*/
public void move()
{
}
//Other methods
//You can define what this type of object can do here.
}
my line and box classes are very straight forward just some classes i made with xposes and yposes, width's and heights
i'm working with image processing, and i have a question.
I want read an image from project, and convert the image to gray.
I'm currently trying to do conversion with the function rgb2gray, but still not working.
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class ImageTesting extends Component {
private static int[] pixel;
private static BufferedImage b;
BufferedImage image;
public void paint(Graphics g) {
g.drawImage(image, 0, 0, null);
}
public ImageTesting() {
try {
image = ImageIO.read(new File("teste.jpg"));
} catch (IOException e) {
}
}
public Dimension getPreferredSize() {
if (image == null) {
return new Dimension(400, 400);
} else {
return new Dimension(image.getWidth(null), image.getHeight(null));
}
}
public static BufferedImage rgb2gray(BufferedImage bi) {
int heightLimit = bi.getHeight();
int widthLimit = bi.getTileWidth();
BufferedImage converted = new BufferedImage(widthLimit, heightLimit, BufferedImage.TYPE_BYTE_GRAY);
for (int height = 0; height < heightLimit; height++) {
for (int width = 0; width < widthLimit; width++) {
Color c = new Color(bi.getRGB(width, height) & 0x00fffff);
int newRed = (int) ((0.2989f * c.getRed()) * 2);// 0.2989f//multiplicr po 2
int newGreen = (int) ((0.5870f * c.getGreen()) * 2);// 0.5870f
int newBlue = (int) ((0.1140f * c.getBlue()) * 2);
int roOffset = newRed + newGreen + newBlue;
converted.setRGB(width, height, roOffset);
}
}
return converted;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
// TODO code application logic here
JFrame f = new JFrame("Load Image Sample");
JFrame g = new JFrame("Image RGB");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
g.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.add(new ImageTesting());
f.pack();
f.setVisible(true);
g.add(new ImageTesting());
rgb2gray(b);
}
}
When I run the program,these are the errors that appear.
If anyone could help me, i apreciate.
Thanks
Edit:
I managed to solve this problem,but now another question came up. To continue my work, i want to find the most 10 brilhants points in the resultant image, and return another image with black color in the index's that have the value 0, and white color in the index's that have value 1,but at this point i don't understand the best way to work out the steps.
It seems like there's something wrong with the main() method, isn't it? You create two completely identical JFrame instances, then add Imagetesting components that display the original image. And when running rgb2gray at the end, the result is sent nowhere.
I suggest using image filters, see related documentation here: http://www.jhlabs.com/ip/filters/
It's performant and simple to use.