3

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.

jalgames
  • 781
  • 4
  • 23

1 Answers1

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