Image to Array of colors

How can I convert an image to an array of Colors (by pixels)?

Create a java.awt.image.BufferedImage with the same dimensions as your image. Paint your image on the BufferedImage. Use BufferedImage.getRGB() to get the pixels.

Or use java.awt.image.PixelGrabber

Oh how do I load an image from disk (such as TGA) onto a BufferedImage?

And how do I convert the int given by BufferedImage.getRGB(x,y,) to the RGB values?


// although ImageIO.read pretends to returns an Image, in practice this is always a BufferedImage, so you can
// cast it to BufferedImage if you like...
Image image = ImageIO.read(new File("myFile.tga"));


int color = myBufferedImage.getRGB(x,y);

// red, green, blue in the range 0-255
int red = (color >> 16) & 0xFF;
int green = (color >> 8) & 0xFF;
int blue = color & 0xFF;

Cool thanks =P

Check the javadocs :slight_smile:

ImageIO returns a BufferedImage, not an Image. It’s not even pretending :slight_smile:

BufferedImage image = ImageIO.read(new File(“pic.jpg”));
That works, but it only takes JPG and GIF files… is there something else to load TGA/BMP files?

Annd how do you convert RGB vaules back into the single RGB int (so the reverse)?

You are right ofcourse. I looked something up from my own code and it was me who was casting to Image. lol.

http://java.sun.com/products/java-media/jai/forDevelopers/jaifaq.html#fileformat for supported file formats. BMP seems to be supported. TGA is just uncompressed anyway… but here is a plugin for ImageIO http://www.realityinteractive.com/software/oss/#ImageIOTGA


// shift them back
int finalColor = (red << 16) | (green << 8) | blue;

Wow thank you so much you guys are the greatest ;D