Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 471
DCoder Avatar asked Jan 02 '14 09:01

DCoder


1 Answers

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.

like image 85
Jon Skeet Avatar answered Oct 03 '22 02:10

Jon Skeet