如何将字节数组存储为磁盘上的映像文件?

Yat*_*oel 11 java io image bytearray

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

我已经这样做了

OutputStream out = new FileOutputStream("a.jpg");
out.write(byteArray);
out.flush();
out.close();
Run Code Online (Sandbox Code Playgroud)

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

Dar*_*rov 8

您可以使用FileOutputStream类:

FileOutputStream fos = new FileOutputStream("image.jpg");
try {
    fos.write(someByteArray);
}
finally {
    fos.close();
}
Run Code Online (Sandbox Code Playgroud)


Jon*_*eet 8

除了没有使用try/finally块(至少在你已经显示的代码中)应该没问题.(顺便说一句,如果要关闭输出流,则不需要刷新输出流.)

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