user3295361
user3295361

Reputation: 11

BufferedImage & Rasters (Java)

Hi can someone explain this piece of code to me

private int[] pixels = ((DataBufferInt)image.getRaster().getDataBuffer()).getData();

From what I understand a raster simply represents a group of pixels. getDataBuffer() gives me the editable buffer, so that I can actually alter pixel properties. I am confused, primarily, about .getData() and the DataBufferInt cast, what exactly do those two things do.

Thanks in advance.

Upvotes: 1

Views: 2585

Answers (1)

Harald K
Harald K

Reputation: 27054

Assuming image is a BufferedImage, getRaster() will give you the WritableRaster for the image. Then, getDataBuffer() will give you the data buffer, which is a thin wrapper around the pixel array.

Because the native pixel arrays of a BufferedImage may be byte[], short[], int[] or even float[] or double[], multiple subclasses of DataBuffer exists for each type of backing array (there's even a TYPE_USHORT for unsigned short data, it's still using short[]). As there's no getData() or similar method in the abstract DataBuffer superclass, you need to cast the buffer to the proper subclass to be able to access the data in its native form. This is DataBufferInt in your case, but you can check it, using dataBuffer.getType().

With the proper data buffer subclass, you can access the native pixels using the getData() method. You can now modify the pixels directly, any way you want.

However, note that accessing the pixel array directly will make your image "unmanaged", and disable some hardware accelerations of the BufferedImage. This may not be a problem, but it may cause slower rendering and frame rate drops, if you paint this image to screen often.

Upvotes: 3

Related Questions