java.awt.image.DataBufferByte cannot be cast to java.awt.image.DataBufferInt

半城伤御伤魂 提交于 2019-11-29 12:00:38
the13ghost

To solve your problem, you need to change the BufferedImage type of

private BufferedImage image = new BufferedImage(WIDTH, HEIGHT,  
BufferedImage.TYPE_3BYTE_BGR);

and change it to

private BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);

the problem is that BufferedImage.TYPE_3BYTE_BGR uses byte[3] to represent each pixel and BufferedImage.TYPE_INT_RGB just uses an int

The problem is that image.getRaster().getDataBuffer() is returning a DataBufferByte, and you're attempting to cast to a DataBufferInt. Those are two distinct classes, both subclasses of DataBuffer, but one is not a subclass of the other, so casting between them is not possible.

The spec for Raster doesn't clearly describe what determines whether getDataBuffer returns a DataBufferByte or a DataBufferInt (or perhaps some other flavor of DataBuffer). But presumably this varies depending on the type of image being dissected. You're probably dissecting a byte-per-pixel image and the code, as it stands, expects 32-bits-per-pixel.

As it is, you probably need to remove some of that logic from the <init> section and add it to the explicit constructor, so you can test the type of DataBuffer returned and handle it accordingly, rather than unconditionally casting it to DataBufferInt.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!