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

问题描述 投票:-1回答:1

我正在尝试将BufferedImage转换为字节数组但我每次都得到一个异常我有一个返回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

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

java nio
1个回答
3
投票

您可以使用ByteArrayOutputStream类并使用以下代码从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或写入文件。

© www.soinside.com 2019 - 2024. All rights reserved.