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

前端 未结 3 922
忘了有多久
忘了有多久 2020-12-18 05:03

I have some errors atm while im coding with JAVA, I have been trying to fix this for along time, also trying to find oterh ppl who have same problem and fixed it but nothing

相关标签:
3条回答
  • 2020-12-18 05:41

    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

    0 讨论(0)
  • 2020-12-18 05:45

    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.

    0 讨论(0)
  • 2020-12-18 06:01

    image.getRaster().getDataBuffer().getDataType() delivers a type constant from class DataBuffer, e.g. TYPE_BYTE, TYPE_SHORT, TYPE_INT, each of these binding a unique DataBuffer[Type] subclass of DataBuffer. So you can detect, whether a typed buffer cast will succeed.

    Conversion between int and byte[4] basically depends on a byte-order-rule, which is not defined on the level Java internal types and so a reinterpret cast of arrays of such cannot be well-defined.

    If you are not the originator the image as the accepted answer assumes, you need to define and apply type conversions.

    EDIT
    DataInputStream.readInt actually uses a defined conversion: Big-endianness

    Conversion from byte[] to int[] may be performed be reading integers from a DataInputStream with ByteArrayInputStream as source, initialized with the byte array.

    0 讨论(0)
提交回复
热议问题