Below is a snippet of code in java for converting a jpg image to base64.
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import javax.imageio.ImageIO;
public class ImageEncode {
/**
* @param args
*/
public static String image;
public static void main(String[] args) {
try {
File f = new File("c:\\temp\\index.jpg");
BufferedImage _image = ImageIO.read(f);
if (_image != null) {
try {
java.io.ByteArrayOutputStream os= new java.io.ByteArrayOutputStream();
ImageIO.write(_image, "jpg", os);
byte[] data= os.toByteArray();
image = new sun.misc.BASE64Encoder().encode(data);
//write to file the encoded character
FileOutputStream fout=null;
OutputStreamWriter out = null;
OutputStream bout = null;
fout = new FileOutputStream ("c:\\temp\\encodedImage.txt");
bout= new BufferedOutputStream(fout);
out = new OutputStreamWriter(bout, "utf-8");
out.write(image);
out.close();
} catch (java.lang.Exception ex2) {
System.out.println("Exception: " + ex2);
ex2.printStackTrace();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Tuesday, January 6, 2009
Subscribe to:
Post Comments (Atom)
Thanks a lot
ReplyDeletethank you.........
ReplyDeleteThanks a lot.!! it really helped me!
ReplyDeletehow to use this..can any one help me out???pleaseeeee
ReplyDeleteI have read the following program
ReplyDelete1.Convert a jpg image to base64 encoding
2.Converting a base64 encoded image back to jpg file
If these are executed successfully, I will give ur reference in my phd thesis.
I will tell i if it is executed successfully
Thanks
Sanjeev Tyagi
Meerut
Asst. Professor
Dept Cs/It