3

these few lines retrieve an array of all pixels of an image.

ImageInputStream is = ImageIO.createImageInputStream(f);
Iterator iter = ImageIO.getImageReaders(is);
ImageReader imageReader = (ImageReader) iter.next();
imageReader.setInput(is);
BufferedImage image = imageReader.read(0);
final byte[] a = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();

How can I retrieve actual R G B channels for a pixel (for example 0,0)?

EDIT I'm using this array because of faster access to the image. That's why I'm not using higher APIs' methods like getRGB or getSample...

1 Answer 1

7

Assuming image.getType() == TYPE_INT_RGB then you have an array like this:

R, G, B, R, G, B, R, G, B, ...

You can access the values of pixel (x,y) via

int width = image.getWidth();

...

byte R = a[3*(x+y*width)];
byte G = a[1+3*(x+y*width)];
byte B = a[2+3*(x+y*width)];

There are several other imagetypes to consider as you can read in the documentation.

The access method basically stays the same, you just have different color ordering or an additional alpha channel. However, for those 4 channel pixels you have to adjust the formular for first channel of the pixel (x,y) to

byte A = a[4*(x+y*width)];
1
  • How can I call getPixel() method on a simple byte array ?!?
    – myro
    Nov 24, 2011 at 22:21

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.