I am writing a code to get pixels value of the entire image and store it into a array.
But i am facing the problems, as outlined below.
I would be grateful if someone could help me in sorting this out..

Cheers :)

File inputFile = new File("one.jpg");
BufferedImage bufferedImage = ImageIO.read(inputFile);
int w = bufferedImage.getWidth();
int h = bufferedImage.getHeight(null);

//Get Pixels
int [] rgbs = new int[w*h];
bufferedImage.getRGB(0, 0, w, h, rgbs, 0, w); //Get all pixels
for(int i=0;i<w*h;i++)
	 System.out.println("rgbs["+i+"]= "+rgbs[i]);
 //when i printed this, I was expecting pixel values 
//but I got negative values... :| 

//Set Pixels
 int rgb = 0xFF00FF00; // green  
 for(int j=0;j<10;j++)
	 for(int k=0;k<10;k++)
		 bufferedImage.setRGB(j,k, rgb);
//Instead of setting the pixels to green, 
//it is instead set to Gray... :confused:

(if you want to see the syntax highlighting...

ok, this thread is old, but still, maybe an answer would help some peoples...

so, the value you have with rgbs, after bufferedImage.getRGB(0, 0, w, h, rgbs, 0, w)
IS the color, it's the conversion from it's hexadecimal value.

The RGB system is based on three nombers, ([0-255], [0-255], [0-255]) or (red color, green color, blue color)

so, the number returned by rgbs is -(256^2 * (256-red) + 256 * (256-green) + (256-blue)) ... a little bit complicated, i'm not CERTAIN of these numbers...

-red = (256^3 + rgbs) / 256^2
-green = ((256^3 + rgbs) / 256) % 256
-blue = (256^3 + rgbs) % 256

explanations, "256^3 + rgbs" is used to convert the negative number to a positive one.
the "/ 256^2" with the red color is to keep only the first of the 3 hexadecimals numbers, example: 256 == FF, so 256^3 == ff ff ff, so 256^3 / 256^2 == ff,ff ff so the two last "ff" are removed since it's an Int, you only keep "ff = 256 = your color value"

well... i'm not too god at explanations sorry, but i hope you can now understand this rgb system a little bit more.


Please give me the whole code to read pixel in a image.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.