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.

4
  • Check out the documentation docs.oracle.com/javase/6/docs/api/java/awt/image/…, specifically getRGB(). Commented Apr 8, 2013 at 14:16
  • How can I convert Images into BufferedImages? Commented Apr 8, 2013 at 14:20
  • How are you loading your Image? Most likely you can just pass a BufferedImage instead. Commented Apr 8, 2013 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. Commented Apr 8, 2013 at 14:44

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Does img strand for the Image i want to convert?
@user2241553 sorry that was a mistake, I fixed that.
why is data.length larger than img.width*img.height ?
@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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.