954,167 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Get Pixel values from Image

Hi,
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:


http://pastebin.stonekeep.com/1748
(if you want to see the syntax highlighting...

hanifa
Newbie Poster
22 posts since Jul 2006
Reputation Points: 10
Solved Threads: 0
 

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

so, the value you have with rgbs[i], 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[i] is -(256^2 * (256-red) + 256 * (256-green) + (256-blue)) ... a little bit complicated, i'm not CERTAIN of these numbers...

but still, IF YOU WANT TO GET YOUR COLORS:
-red = (256^3 + rgbs[i]) / 256^2
-green = ((256^3 + rgbs[i]) / 256) % 256
-blue = (256^3 + rgbs[i]) % 256

-------
explanations, "256^3 + rgbs[i]" 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.

-Dargonesti.

dargonesti
Newbie Poster
1 post since Oct 2010
Reputation Points: 10
Solved Threads: 0
 

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

rinky khan
Newbie Poster
1 post since Mar 2011
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You