【问题标题】:Java - Saving byte[] into an image fileJava - 将字节 [] 保存到图像文件中
【发布时间】:2018-12-12 22:15:56
【问题描述】:

这篇文章是对以下内容的跟进: ImageIO.read can't read ByteArrayInputStream (image processing)

与 OP 类似,每当我尝试从我的 ByteArrayInputStream 中读取数据时,我都会得到一个空指针(正如上面的答案所解释的那样)。注意到这一点,我已经实现了上面帖子中@haraldK 的答案中的代码,以纠正这个问题,但我遇到了另一个问题。我有以下代码:

byte[] imageInByteArr = ...

// convert byte array back to BufferedImage
int width = 1085;
int height = 696;
BufferedImage convertedGrayScale = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
convertedGrayScale.getRaster().setDataElements(0, 0, width, height, imageInByteArr );

try {
    ImageIO.write(convertedGrayScale, "jpg", new File("C:\\test.jpg"));
}
catch (IOException e) {
    System.err.println("IOException: " + e);
}

在执行时,我在 try/catch 块之前的行中遇到了 java.lang.ArrayIndexOutOfBoundsException: null 错误。我的第一个想法是这个空指针是由于我的 C 驱动器中没有一个名为 test.jpg 的文件而产生的。我调整以解决这个问题,但我仍然在convertedGrayScale.getRaster().setDataElements(0, 0, width, height, imageInByteArr ); 遇到同样的空指针问题。为什么会这样?

另一方面,除了编写使用 ImageIO 的文件之外,我还有其他方法可以将 byte[] 转换为图像的视觉表示吗?我试图将数组打印到文件上并将其保存为“.jpg”,但文件不会打开。任何建议都会有所帮助。总而言之,我希望将 byte[] 转换为图像并将其保存或渲染到浏览器上。哪个更容易/可行。

【问题讨论】:

  • imageInByteArr 是从哪里来的?它必须是正好 755,160(即 1,085×696)字节的数组。如果直接从文件或 URL 中读取,则没有数据元素数组;你有一个最有可能的压缩图像格式的快照,它不能直接应用于光栅(这正是另一个问题中的答案所指出的)。
  • 也许 BufferedImage.TYPE_BYTE_GRAY 支持 alpha 通道,因此由于缺少该信息,您的数组可能没有包含足够的元素?
  • 1) 为了尽快获得更好的帮助,edit 添加minimal reproducible example 或Short, Self Contained, Correct Example。 2) 例如,获取图像的一种方法是热链接到this Q&A 中看到的图像。例如。 This answer 指向嵌入在 this question 中的图像的热链接。

标签: java image bufferedimage javax.imageio


【解决方案1】:

您的imageInByteArr 似乎太短了。我能够得到与您从中得到的相同的错误

public static void main(String[] args) {
    int width = 1085;
    int height = 696;
    byte[] imageInByteArr = new byte[width ];
    BufferedImage convertedGrayScale = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
    convertedGrayScale.getRaster().setDataElements(0, 0, width, height, imageInByteArr);

}

当使用width*height 的大小为imageInByteArr 或任何更大的值时,我没有收到任何错误,但是当它小于您尝试更新的数据时,它会引发异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    • 1970-01-01
    • 1970-01-01
    • 2011-12-20
    • 2016-11-23
    • 2013-04-16
    • 1970-01-01
    相关资源
    最近更新 更多