[java] Write Base64-encoded image to file

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.

This question is related to java image base64 decode encode

The answer is


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.


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

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

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

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

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to image

Reading images in python Numpy Resize/Rescale Image Convert np.array of type float64 to type uint8 scaling values Extract a page from a pdf as a jpeg How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter? Angular 4 img src is not found How to make a movie out of images in python Load local images in React.js How to install "ifconfig" command in my ubuntu docker image? How do I display local image in markdown?

Examples related to base64

How to convert an Image to base64 string in java? How to convert file to base64 in JavaScript? How to convert Base64 String to javascript file object like as from file input form? How can I encode a string to Base64 in Swift? ReadFile in Base64 Nodejs Base64: java.lang.IllegalArgumentException: Illegal character Converting file into Base64String and back again Convert base64 string to image How to encode text to base64 in python Convert base64 string to ArrayBuffer

Examples related to decode

How to decode encrypted wordpress admin password? How to decode a QR-code image in (preferably pure) Python? Write Base64-encoded image to file Base64 Java encode and decode a string Android - How to decode and decompile any APK file? UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function PHP replacing special characters like à->a, è->e UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined> How do I decode a string with escaped unicode? UnicodeDecodeError, invalid continuation byte

Examples related to encode

Write Base64-encoded image to file Base64 Java encode and decode a string C# Base64 String to JPEG Image UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function PHP "pretty print" json_encode Convert int to ASCII and back in Python Python Unicode Encode Error How to convert a string or integer to binary in Ruby? AJAX POST and Plus Sign ( + ) -- How to Encode? How to HTML encode/escape a string? Is there a built-in?