如何在不使用文件的情况下将BufferedImage转换为字节数组 [英] How I can convert BufferedImage to a byte array without using files

查看:168
本文介绍了如何在不使用文件的情况下将BufferedImage转换为字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将BufferedImage转换为字节数组,但是每次遇到异常时,我都会得到一个返回bufferImage的服务,这是我的代码:

I'm trying to convert a BufferedImage to an array of bytes but I get every time an exception I have a service that return a bufferImage ,this my code :

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

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

How I can do this conversion without using files

推荐答案

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

You can use ByteArrayOutputStream class and write data from BufferedImage object using following code,

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或写入文件.

And all of this just in memory without using any disk io or writing to files.

这篇关于如何在不使用文件的情况下将BufferedImage转换为字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆