将Base64编码的图像写入文件 [英] Write Base64-encoded image to file
问题描述
如何将Base64编码的图像写入文件?
How to write a Base64-encoded image to file?
我已使用Base64将图像编码为字符串。
首先,我读取文件,然后将其转换为字节数组,然后应用Base64编码将图像转换为字符串。
I have encoded an image to a string using Base64. First, I read the file, then convert it to a byte array and then apply Base64 encoding to convert the image to a string.
现在我的问题是如何解码它。
Now my problem is how to decode it.
byte dearr[] = Base64.decodeBase64(crntImage);
File outF = new File("c:/decode/abc.bmp");
BufferedImage img02 = ImageIO.write(img02, "bmp", outF);
变量 crntImage
包含字符串表示形式图像。
The variable crntImage
contains the string representation of the image.
推荐答案
假设图像数据已经是你想要的格式,你不需要图像 ImageIO
- 你只需要将数据写入文件:
Assuming the image data is already in the format you want, you don't need image ImageIO
at all - you just need to write the data to the file:
// Note preferred way of declaring an array variable
byte[] data = Base64.decodeBase64(crntImage);
try (OutputStream stream = new FileOutputStream("c:/decode/abc.bmp")) {
stream.write(data);
}
(我假设你在这里使用Java 7 - 如果没有,你需要编写一个手动的try / finally语句来关闭流。)
(I'm assuming you're using Java 7 here - if not, you'll need to write a manual try/finally statement to close the stream.)
如果图像数据不是的格式你想要的,你需要提供更多细节。
If the image data isn't in the format you want, you'll need to give more details.
这篇关于将Base64编码的图像写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!