【发布时间】:2020-07-13 22:04:37
【问题描述】:
我有以下代码,将图像转换为字节[]:
BufferedImage image = ImageIO.read(new File("Path/To/Custom/image.jpg"));
ByteArrayOutputStream baos=new ByteArrayOutputStream(1000);
ImageIO.write(image, "jpg", baos);
byte[] imageBytes = baos.toByteArray();
这段代码工作得很好,至少我得到了一个包含不同值的字节数组。但是现在困难的部分来了:必须再次将 byte[] 重建为 am 图像。以下代码不起作用,ImageIO.read(...) 返回 null。我阅读了文档,但仍然找不到要更改的内容以使代码按我想要的方式运行。
ByteArrayInputStream ba = new ByteArrayInputStream(imageBytes);
BufferedImage image = ImageIO.read(ba);
//image is always null, no matter what the stream or the byte values are.
【问题讨论】:
-
能否尝试将 ImageIO.read() 放入 try-catch-block 中并告诉我们是否发生错误,如果发生错误,是哪一个?
-
抱歉,不够具体。我已经在 try catch 中测试过了,但也不例外。 ImageIO.read(...) 只是返回 null,但原始图像不为 null。这里的代码很短,可以简化事情。