Tuesday, January 6, 2009

Convert a jpg image to base64 encoding

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();
}
}



}

5 comments:

  1. thank you.........

    ReplyDelete
  2. Thanks a lot.!! it really helped me!

    ReplyDelete
  3. how to use this..can any one help me out???pleaseeeee

    ReplyDelete
  4. I have read the following program

    1.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

    ReplyDelete