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) {
Line.append(strLine);
}
//Close the input stream
in.close();
String base64 = Line.toString();
System.out.println(base64);
byte decoded[] = new sun.misc.BASE64Decoder().decodeBuffer(base64);
FileOutputStream fos = null;
fos = new FileOutputStream("c:\\temp\\test212.jpg");
fos.write(decoded);
fos.close();
} catch (java.lang.Exception ex2) {
System.out.println("Exception: " + ex2);
ex2.printStackTrace();
}
}
}
Note: create the respective folders before you test the program
Subscribe to:
Post Comments (Atom)
Your example was a tremendous help in solving a problem for a project that I am currently working on. Thanks.
ReplyDeleteHi Abeish,
ReplyDeleteThanks 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
you can try this free online service to convert base64 to image online.
ReplyDelete