0

How do I get byte[] from raster image in java? I have tried:

byte[] data = ((DataBufferByte)bufferedImage.getData().getDataBuffer()).getData();

but this throws a ClassCastException runtime exception: "DataBufferInt cannot be cast to DataBufferByte".

Thanks for the help.

4

1 回答 1

2

您可以使用 ByteArrayOutputStream 获取字节数组,这样应该可以工作:(注意,未经测试的代码)

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write( bufferedImage, "jpg", baos ); // if your image is a jpg
baos.flush();
byte[] imageInByte = baos.toByteArray();
baos.close();

编辑 这个怎么样?您需要图像的 FileInputstream 来读取它并将其写入 ByteArrayOutputStream

ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
    for (int readNum; (readNum = fis.read(buf)) != -1;) {
        bos.write(buf, 0, readNum); 
    }
} catch (IOException ex) {
    //
}
byte[] bytes = bos.toByteArray();
于 2012-08-21T06:56:27.130 回答