Java 如何将字节数组作为图像文件存储在磁盘上?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2138913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 04:02:24  来源:igfitidea点击:

How to store a byte array as an image file on disk?

javaimageiobytearray

提问by Yatendra Goel

I have a byte array representation of a Image. How to save it on disk as an image file.

我有一个图像的字节数组表示。如何将其作为图像文件保存在磁盘上。

I have already done this

我已经这样做了

OutputStream out = new FileOutputStream("a.jpg");
out.write(byteArray);
out.flush();
out.close();

But when I open the image by double-clicking it, it doesn't show any image.

但是当我通过双击打开图像时,它不显示任何图像。

采纳答案by Jon Skeet

Other than failing to use a try/finally block (at least in the code you've shown) that should be fine. (You don't need to flush an output stream if you're closing it, by the way.)

除了未能使用 try/finally 块(至少在您显示的代码中)之外,应该没问题。(顺便说一下,如果您要关闭输出流,则不需要刷新它。)

As it's not working, that suggests byteArraydoesn't actuallycontain a JPEG-encoded image. How have you created byteArrayto start with? If it's a "raw" representation, you'll probably want to encode it, e.g. using the javax.imageiopackage.

由于它不工作,这表明byteArray实际包含JPEG编码的图像。你是byteArray如何开始创作的?如果它是“原始”表示,您可能需要对其进行编码,例如使用javax.imageio包。

回答by Darin Dimitrov

You could use the FileOutputStreamclass:

您可以使用FileOutputStream类:

FileOutputStream fos = new FileOutputStream("image.jpg");
try {
    fos.write(someByteArray);
}
finally {
    fos.close();
}

回答by Joonas Pulakka

You can use ImageIO API.

您可以使用ImageIO API

The details can be a bit hairy, but first you'll probably want to create a BufferedImage using TYPE_BYTE_INDEXED type and some suitable IndexColorModel instance. Then put your byte array there. Hint: you can get the internal representation of BufferedImage with:

细节可能有点麻烦,但首先您可能想要使用 TYPE_BYTE_INDEXED 类型和一些合适的 IndexColorModel 实例创建一个 BufferedImage。然后把你的字节数组放在那里。提示:您可以通过以下方式获得 BufferedImage 的内部表示:

myDataBuffer = myBufferedImage.getRaster().getDataBuffer();

Which will likely return a data buffer of type DataBufferByte (check!), from which you get a byte array with

这可能会返回一个 DataBufferByte 类型的数据缓冲区(检查!),从中你可以得到一个字节数组

myByteArray = ((DataBufferByte) myDataBuffer).getData();

Then you can use System.arraycopy to copy your byte array onto that.

然后你可以使用 System.arraycopy 将你的字节数组复制到它上面。