Write Base64-encoded image to file

JavaImageBase64DecodeEncode

Java Problem Overview


How to write a Base64-encoded image to file?

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

The variable crntImage contains the string representation of the image.

Java Solutions


Solution 1 - Java

Assuming the image data is already in the format you want, you don't need 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);
}

(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.

Solution 2 - Java

With Java 8's 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);

If your encoded image starts with something like data:image/png;base64,iVBORw0..., you'll have to remove the part. See this answer for an easy way to do that.

Solution 3 - Java

No need to use BufferedImage, as you already have the image file in a byte array

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

Solution 4 - Java

import java.util.Base64;

.... Just making it clear that this answer uses the java.util.Base64 package, without using any third-party libraries.

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

Solution 5 - Java

Other option using 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 );

Solution 6 - Java

Try this:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDCoderView Question on Stackoverflow
Solution 1 - JavaJon SkeetView Answer on Stackoverflow
Solution 2 - JavaMatthias BraunView Answer on Stackoverflow
Solution 3 - JavaKaviKView Answer on Stackoverflow
Solution 4 - JavaDABView Answer on Stackoverflow
Solution 5 - JavaFabio De CarliView Answer on Stackoverflow
Solution 6 - JavaJamel ESSOUSSIView Answer on Stackoverflow