Tuesday, January 6, 2009

Converting a base64 encoded image back to jpg file

Below is a small snippet of java code for converting a base64 encoded image back to jpg format. For the smooth running of the program I assume that the base64 encoded image is stored in a .txt file and the program will read the file and create jpg image from it.

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.imageio.ImageIO;

public class ImageDecode {

* @param args
public static void main(String[] args) {
// TODO Auto-generated method stub

try {

StringBuffer Line= new StringBuffer();

FileInputStream fstream = new FileInputStream("c:\\temp\\test2.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
//Close the input stream

String base64 = Line.toString();
byte decoded[] = new sun.misc.BASE64Decoder().decodeBuffer(base64);
FileOutputStream fos = null;
fos = new FileOutputStream("c:\\temp\\test212.jpg");

} catch (java.lang.Exception ex2) {
System.out.println("Exception: " + ex2);



Note: create the respective folders before you test the program


  1. Your example was a tremendous help in solving a problem for a project that I am currently working on. Thanks.

  2. Hi Abeish,

    Thanks very much for your code.

    But The converted jpg image did not load, error displayed was "Loading image failed, loading meta information failed"

    i am not getting what to do further

    please help