首页 文章

将Base64编码的图像写入文件

提问于
浏览
29

如何将Base64编码的图像写入文件?

我使用Base64将图像编码为字符串 . 首先,我读取文件,然后将其转换为字节数组,然后应用Base64编码将图像转换为字符串 .

现在我的问题是如何解码它 .

byte dearr[] = Base64.decodeBase64(crntImage);
File outF = new File("c:/decode/abc.bmp");
BufferedImage img02 = ImageIO.write(img02, "bmp", outF);

变量 crntImage 包含图像的字符串表示形式 .

6 回答

  • -1

    使用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 );
    
  • 52
    import java.util.Base64;
    

    ....只是说明这个答案使用java.util.Base64包,而不使用任何第三方库 .

    String crntImage=<a valid base 64 string>
    
    byte[] data = Base64.getDecoder().decode(crntImage);
    
    try( OutputStream stream = new FileOutputStream("d:/temp/abc.pdf") ) 
    {
       stream.write(data);
    }
    catch (Exception e) 
    {
       System.err.println("Couldn't write to file...");
    }
    
  • 8

    假设图像数据已经是您想要的格式,您根本不需要图像 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语句来关闭流 . )

    如果图像数据不是您想要的格式,则需要提供更多详细信息 .

  • -5

    使用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... 之类的内容开头,则必须删除该部分 . 请参阅this answer以获得简单的方法 .

  • 0

    无需使用BufferedImage,因为您已经在字节数组中拥有图像文件

    byte dearr[] = Base64.decodeBase64(crntImage);
        FileOutputStream fos = new FileOutputStream(new File("c:/decode/abc.bmp")); 
        fos.write(dearr); 
        fos.close();
    
  • 3

    试试这个:

    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");
        }
    }
    

相关问题