Write Base64-encoded image to file
Asked Answered
B

7

61

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.

Bioastronautics answered 2/1, 2014 at 9:13 Comment(0)
G
92

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.

Gilbertogilbertson answered 2/1, 2014 at 9:18 Comment(8)
I used your above code. I am working on java web services where i am getting base64 string of uploaded image form IOS device. When i tried your above code in separate application i get original image as it is. But when i tried it with web services image is not created. When i debug application in both cases the byte array for same base64 string is different in length. Why i am getting this problem.Cascio
@Aniket: That doesn't give nearly enough information for us to help you. I suggest you ask a new question with more context - what the web service is, how it's implemented, how you're uploading the image data, what you've observed etc.Gilbertogilbertson
I posted question on below link #27378569Cascio
"I'm assuming you're using Java 7" => you meant Java 8, not Java 7. Afaik both Base64 and try-with-resources are Java 8.Standee
@Toto: No, try-with-resources was definitely in Java 7: docs.oracle.com/javase/7/docs/technotes/guides/language/… Java 8 wasn't released when I wrote this answer, although I guess it was available in beta. But the Base64 class that the OP is using isn't the one in the JDK, either. (It doesn't have a decodeBase64 method.)Gilbertogilbertson
Helpful answer,but it didn't work first time. I needed to use the Base64 getDecoder() method, like so: byte[] data = Base64.getDecoder().decode(crntImage);Alded
@DAB: I strongly suspect we're talking about different Base64 classes then. I suspect the OP was using the Apache one: commons.apache.org/proper/commons-codec/apidocs/org/apache/…Gilbertogilbertson
@jonskeet Yes, you're right, I think. I have added another answer below.Alded
R
39

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.

Recuperator answered 22/10, 2016 at 18:57 Comment(0)
M
6

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();
Medication answered 2/1, 2014 at 9:26 Comment(0)
A
2
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...");
}
Alded answered 22/11, 2018 at 13:42 Comment(0)
H
1

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 );
Humus answered 30/12, 2015 at 12:33 Comment(0)
T
0
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()));
        }
    }
Transfiguration answered 12/4, 2024 at 1:10 Comment(0)
D
-7

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");
    }
}
Dessiedessma answered 2/1, 2014 at 9:18 Comment(1)
The OP doesn't have a URL. They have the image data in base64 - something your answer completely ignores.Gilbertogilbertson

© 2022 - 2025 — McMap. All rights reserved.