字节数组转换为图像对象

62
我在Java中有一个byte[]数组,其中包含图像的字节,我需要将其输出为图像。我该如何实现?
非常感谢。
5个回答

98
BufferedImage img = ImageIO.read(new ByteArrayInputStream(bytes));

10
这不回答问题,问题是关于将内容写入图像文件。这个回答是关于从图像文件中读取内容。所有的点赞是怎么回事? - Supercreature
10
标题说了,但问题是他们有一个字节数组,需要一个图像,这就是它的作用。 - Nick Veys

26

如果您知道图像的类型并且只想生成文件,那么就不需要获取BufferedImage实例。只需使用正确的扩展名将字节写入文件即可。

try (OutputStream out = new BufferedOutputStream(new FileOutputStream(path))) {
    out.write(bytes);
}

5
From Database.
Blob blob = resultSet.getBlob("pictureBlob");               
byte [] data = blob.getBytes( 1, ( int ) blob.length() );
BufferedImage img = null;
try {
img = ImageIO.read(new ByteArrayInputStream(data));
} catch (IOException e) {
    e.printStackTrace();
}
drawPicture(img);  //  void drawPicture(Image img);

2

1
根据Java文档,看起来您需要使用MemoryImageSource类将字节数组放入内存中的对象中,然后接下来使用Component.createImage(ImageProducer)(传递您的MemoryImageSource,它实现了ImageProducer)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接