Skip to main content

How to received raw pixel data as byte array from an Image?

2 replies [Last post]
k4simir
Offline
Joined: 2006-11-29

Hallo everybody,

I like to implement some performance crital pixel manipulations on Images. Therefore I need to receive the pure (raw) pixel data as ordered byte array:

Something like this would be cool:

aRGB {image} = byte[]
{
A(p[0,0]); R(p[0,0]); G(p[0,0]); B(p[0,0]);
A(p[1,0]); R(p[1,0]); G(p[1,0]); B(p[1,0]);
...
A(p[image.width-1,image.height-1]); R(p[image.width-1,image.height-1]); G(p[image.width-1,image.height-1]); B(p[image.width-1,image.height-1]);
}

Optional an ordered byte array for each color channel would be ok too:

a {image} = byte[]
{
A(p[0,0]); A(p[1,0]);
...
A(p[image.width-1,image.height-1]);
}

R {image} = byte[]
{
R(p[0,0]);
R(p[1,0]);
...
R(p[image.width-1,image.height-1]);
}

and so on.

How to receive this byte array from a BufferedImage? How to write the image data back to the BufferedImage? Does anybody have a little example for me? Does anybody knows a good book about image processing / computer graphics with Java2D?

Regards.
Kohannes alias k4simir

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
wmeissner
Offline
Joined: 2005-10-09

You can easily get access to the backing array as a 32bit int:
BufferedImage img = new BufferedImage(400, 300, BufferedImage.TYPE_INT_ARGB);
int[] pixels = ((DataBufferInt) img.getRaster().getDataBuffer()).getData();
Then you get access to the components by bitshifting, e.g.
int r = (pixels[0] >> 16) & 0xff;

You can also create a BufferedImage from a byte array using a PixelInterleavedSampleModel, ComponentColorModel, and wrapping your byte array in a DataBufferByte. I don't have any code for this, but if you search for it, there are examples on the web.

One thing to note: as soon as you access the backing array, java2d stops accelerating the image, so if you need to do a mix of accelerated and non-accelerated operations, use a temporary buffer for the direct pixel access, then write that to the main image using BufferedImage.getGraphics().drawImage()

k4simir
Offline
Joined: 2006-11-29

thank you. i will try this.