Java的:BufferedImage中的字节数组和背部 [英] Java: BufferedImage to byte array and back

查看:256
本文介绍了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(我有我需要此功能的应用程序)。请注意,测试是字节数组。

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.

有没有人有关于如何解决这个问题有什么建议?将大大AP preciated。

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

推荐答案

这是建议转换为字节数组

This is recommended to convert to a byte array

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

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

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