如何在不使用文件的情况下将 BufferedImage 转换为字节数组

How I can convert BufferedImage to a byte array without using files

我正在尝试将 BufferedImage 转换为字节数组,但每次出现异常时我都会得到一个 return bufferImage 服务,这是我的代码:

BufferedImage bufferedImage = myservice.getImage();
WritableRaster raster = bufferedImage.getRaster();
DataBufferByte data   = (DataBufferByte) raster.getDataBuffer();
 byte[] fileContent = data.getData();

此代码抛出异常:

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

如何在不使用文件的情况下进行这种转换

您可以使用 ByteArrayOutputStream class 并使用以下代码从 BufferedImage 对象写入数据,

BufferedImage image = null; // you have the data in this object
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "fileformat like png or jpg", baos);
baos.flush();
byte[] imageInByte = baos.toByteArray(); // you have the data in byte array
baos.close();

所有这些都在内存中,无需使用任何磁盘 io 或写入文件。