Java:BufferedImage 到字节数组并返回 [英] Java: BufferedImage to byte array and back

查看:21
本文介绍了Java:BufferedImage 到字节数组并返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到很多人都遇到了类似的问题,但是我还没有尝试找到我正在寻找的内容.

I see that a number of people have had a similar problem, however I'm yet to try find exactly what I'm looking for.

所以,我有一个方法可以读取输入图像并将其转换为字节数组:

So, I have a method which reads an input image and converts it to a byte array:

    File imgPath = new File(ImageName);
    BufferedImage bufferedImage = ImageIO.read(imgPath);
    WritableRaster raster = bufferedImage .getRaster();
    DataBufferByte data   = (DataBufferByte) raster.getDataBuffer();

我现在想做的是将其转换回 BufferedImage(我有一个需要此功能的应用程序).请注意,test"是字节数组.

What I now want to do is convert it back into a BufferedImage (I have an application for which I need this functionality). Note that "test" is the byte array.

    BufferedImage img = ImageIO.read(new ByteArrayInputStream(test));
    File outputfile = new File("src/image.jpg");
    ImageIO.write(img,"jpg",outputfile);

然而,这会返回以下异常:

However, this returns the following exception:

    Exception in thread "main" java.lang.IllegalArgumentException: im == null!

这是因为 BufferedImage img 为空.我认为这与以下事实有关,即在我从 BufferedImage 到字节数组的原始转换中,信息已更改/丢失,因此数据无法再被识别为 jpg.

This is because the BufferedImage img is null. I think this has something to do with the fact that in my original conversion from BufferedImage to byte array, information is changed/lost so that the data can no longer be recognised as a jpg.

有人对如何解决这个问题有任何建议吗?将不胜感激.

Does anyone have any suggestions on how to solve this? Would be greatly appreciated.

推荐答案

这里建议转成字节数组

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", baos);
byte[] bytes = baos.toByteArray();

这篇关于Java:BufferedImage 到字节数组并返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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