DCoder
DCoder

Reputation: 3488

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.

Upvotes: 62

Views: 206862

Answers (7)

Milton Aguilar
Milton Aguilar

Reputation: 11

public class MensajeArchivoDto {

    private String base64;
    private String ruta;
    private String nom_archivo;
    private String ext_archivo;
}
-----------
    @Override
    public void descargarArchivo(MensajeArchivoDto msgArchivo) {
        
        List<ErrorEntity> lstErrores = new ArrayList<ErrorEntity>();
        try {
            
            String rutaRaiz = "D:\\";
            byte[] archivoByte = Base64.getDecoder().decode(msgArchivo.getBase64());
            String rutaCompleta  =rutaRaiz+ msgArchivo.getRuta();
            crearDirectorio(rutaCompleta);
            String nombreCompleto  =rutaCompleta+"\\"+msgArchivo.getNom_archivo()+"."+msgArchivo.getExt_archivo();
            OutputStream out = new FileOutputStream(nombreCompleto);
            out.write(archivoByte);
            out.close();
        } catch (Exception e) {
            lstErrores.add(new ErrorEntity("Exception", e.getMessage()));
        }
    } 
    
    private void crearDirectorio(String ruta) {
        try {
            File directorio = new File(ruta);
            if (!directorio.exists()) {
                if (directorio.mkdirs()) {
                    System.out.println("Directorio creado");
                } else {
                    System.out.println("Error al crear directorio");
                }
            }

        } catch (Exception e) {
            lstErrores.add(new ErrorEntity("Exception", e.getMessage()));
        }
    }

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503090

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.

Upvotes: 94

Matthias Braun
Matthias Braun

Reputation: 34403

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.

Upvotes: 41

DAB
DAB

Reputation: 1873

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

Upvotes: 2

Fabio De Carli
Fabio De Carli

Reputation: 379

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

Upvotes: 1

KaviK
KaviK

Reputation: 625

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

Upvotes: 6

Jamel ESSOUSSI
Jamel ESSOUSSI

Reputation: 200

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

Upvotes: -7

Related Questions