1

I have the following java code

final byte[] pixels;
DataBuffer rasterData = image.getRaster().getDataBuffer();
DataBufferByte rasterByteData = (DataBufferByte)rasterData;
pixels = rasterByteData.getData();

Where image is a object of type BufferedImage, I wish to convert the Image to a DataBufferByte object but my cast throws the following error.

java.lang.ClassCastException: java.awt.image.DataBufferInt cannot be cast to java.awt.image.DataBufferByte

I am trying to use the code from this post Java - get pixel array from image

Any ideas how to cast or why I cannot cast from DataBuffer to DataBufferByte?

EDIT: Changed Image to BufferedImage

Community
  • 1
  • 1

2 Answers2

1

DataBuffer to DataBufferByte cast throws error

Look at reference API - raster data can be anything not only bytes. So i think this is reason why you are getting Exception.

Try to use for your BufferedImage property:

BufferedImage.TYPE_3BYTE_BGR

this should fix it and raster data should be returned as bytes.

Simon Dorociak
  • 33,374
  • 10
  • 68
  • 106
  • Before I try to do this cast I also cast an `Image` object to a `BufferImage` object. My question I guess is then, how do I convert a `Image` to a `DataBufferByte`? How might in my cast I use `TYPE_3BYTE_BGR`, should it just be `(BufferImage.TYPE_3BYTE_BGR)image`? // EDIT, trying that gives me errors in my IDE. –  Nov 08 '13 at 08:41
  • You cannot cast image like this, you need to create image as `BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_3BYTE_BGR);` – Simon Dorociak Nov 08 '13 at 08:46
  • How would I write my `Image` into this new `BufferedImage` object? –  Nov 10 '13 at 20:06
  • Nevermind I have found the information elsewhere! // `BufferedImage image = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(), BufferedImage.TYPE_3BYTE_BGR); image.getGraphics().drawImage(bufferedImage, 0, 0, null);` –  Nov 10 '13 at 20:30
0

DataBuffer is the super class of DataBufferByte class so you can not assign ref of superclass object to subclass object

You will always get class cast exception while do so.

http://edelstein.pebbles.cs.cmu.edu/jadeite/main.php?api=java6&state=class&package=java.awt.image&class=DataBufferByte

Tej Kiran
  • 2,218
  • 5
  • 21
  • 42