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.
1 Answer
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.
4 Comments
jalgames
Does img strand for the Image i want to convert?
stacker
@user2241553 sorry that was a mistake, I fixed that.
Giannis Tzagarakis
why is
data.length larger than img.width*img.height ?stacker
@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)
getRGB().Image? Most likely you can just pass aBufferedImageinstead.ImageasBufferedImage. If you post your code where you load you image, I can be more specific.