将Base64编码的图像写入文件
如何将Base64编码的图像写入文件?
我使用Base64将图像编码为字符串。 首先,我读取文件,然后将其转换为字节数组,然后应用Base64编码将图像转换为字符串。
现在我的问题是如何解码它。
byte dearr[] = Base64.decodeBase64(crntImage); File outF = new File("c:/decode/abc.bmp"); BufferedImage img02 = ImageIO.write(img02, "bmp", outF);
变量crntImage
包含图像的字符串表示forms。
假设图像数据已经是您想要的格式,您根本不需要图像ImageIO
– 您只需要将数据写入文件:
// 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语句来关闭流。)
如果图像数据不是您想要的格式,则需要提供更多详细信息。
使用Java 8的Base64
API
byte[] decodedImg = Base64.getDecoder().decode(encodedImg.getBytes(StandardCharsets.UTF_8)); Path destinationFile = Paths.get("/path/to/imageDir", "myImage.jpg"); Files.write(destinationFile, decodedImg);
如果您的编码图像以data:image/png;base64,iVBORw0...
开头data:image/png;base64,iVBORw0...
,则必须删除该部分。 请参阅此答案以获得简单的方法。
不需要使用BufferedImage,因为您已经在字节数组中拥有图像文件
byte dearr[] = Base64.decodeBase64(crntImage); FileOutputStream fos = new FileOutputStream(new File("c:/decode/abc.bmp")); fos.write(dearr); fos.close();
使用apache-commons的其他选项:
import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.FileUtils; ... File file = new File( "path" ); byte[] bytes = Base64.decodeBase64( "base64" ); FileUtils.writeByteArrayToFile( file, bytes );
尝试这个:
import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.net.URL; import javax.imageio.ImageIO; public class WriteImage { public static void main( String[] args ) { BufferedImage image = null; try { URL url = new URL("URL_IMAGE"); image = ImageIO.read(url); ImageIO.write(image, "jpg",new File("C:\\out.jpg")); ImageIO.write(image, "gif",new File("C:\\out.gif")); ImageIO.write(image, "png",new File("C:\\out.png")); } catch (IOException e) { e.printStackTrace(); } System.out.println("Done"); } }