I load an image in Java and want to convertit to a RGB-Array so I can read the color of each single pixel. I searched on Google, but I only found how to convert Color-Arrays to Images.
Asked
Active
Viewed 6,320 times
3
-
Check out the documentation http://docs.oracle.com/javase/6/docs/api/java/awt/image/BufferedImage.html, specifically `getRGB()`. – Reinstate Monica -- notmaynard Apr 08 '13 at 14:16
-
How can I convert Images into BufferedImages? – jalgames Apr 08 '13 at 14:20
-
How are you loading your `Image`? Most likely you can just pass a `BufferedImage` instead. – Reinstate Monica -- notmaynard Apr 08 '13 at 14:36
-
Or you can cast your `Image` as `BufferedImage`. If you post your code where you load you image, I can be more specific. – Reinstate Monica -- notmaynard Apr 08 '13 at 14:44
1 Answers
3
The following lines illustrate the usage of the API methods:
BufferedImage bi = ImageIO.read( new File( "image.png" ) );
int[] data = ( (DataBufferInt) bi.getRaster().getDataBuffer() ).getData();
for ( int i = 0 ; i < data.length ; i++ ) {
Color c = new Color(data[i]);
// RGB is now accessible as
c.getRed();
c.getGreen();
c.getBlue();
}
If you face issues due to the color model, create a copy first
BufferedImage img2 = new BufferedImage( bi.getWidth(), bi.getHeight(), BufferedImage.TYPE_INT_RGB );
img2.getGraphics().drawImage( bi, 0, 0, null );
and use img2 in the above code.

stacker
- 68,052
- 28
- 140
- 210
-
-
-
-
1@GiannisTzagarakis thats because width*height is the number of pixels and a pixel can have more than a byte. (RGB values plus alpha deoending on the type e.g. BufferedImage.TYPE_INT_RGB) – stacker Nov 26 '15 at 22:32