Decode Base64 String to File in Java

Ibnu Arseno
Code Storm
Published in
2 min readJan 1, 2022

in this article we will discuss how to decode Base64 into an image while maintaining image quality.

Photo by Sachin Khadka on Unsplash

to convert from Base64 to an array of bytes we use the parseBase64Binary method of the DatatypeConverter class.

byte[] data = DatatypeConverter.parseBase64Binary(base64);

declaration of base64 decoded file storage directory and specifying base64 decoded filename.

String path = filePath + "/" + "nameFile.png";

you can adjust the file storage area and the Base64 decoded file name as you wish.

File file = new File(path);

Creates a new File instance by converting the given pathname string into an abstract pathname. If the given string is the empty string, then the result is the empty abstract pathname.

The ImageIO.write() would compress the image by default. the compressed image has a smaller size, but sometimes looks weird. I am using BufferedOutputStream to store byte array data, this will keep the original image size.

OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file));

Creates a new buffered output stream to write data to the specified underlying output stream.

outputStream.write(data);

Creates a file output stream to write to the file represented by the specified File object.

coding decode Base64
Coding decode Base64
Test with Postman to Decode Base64

--

--