Use sun.misc Classes for Base64 Image Conversion

The following code demonstrates how to use sun.misc classes for Base64 image conversion:

import java.io.*;import java.awt.*;import java.awt.event.*;class Base64Example extends Frame implements ActionListener{Image IMG=null;                        //image1Image IMGdecode=null;                  //image2-resultTextArea TA=new TextArea();            //printing the Base64 formButton B=new Button("Decoder");byte[] buffer_code=new byte[1024];byte[] buffer_decode;boolean bool=false;//constructorulpublic Base64Example(String titlu)    {    super(titlu);    }void init()    {    Dimension dim=Toolkit.getDefaultToolkit().getScreenSize();    setSize(550,460);    setLocation(dim.width/2-275,dim.height/2-280);    setLayout(null);    setResizable(false);        TA.setSize(300,390);    TA.setLocation(10,60);    add(TA);        B.setSize(60,20);    B.setLocation(250,35);    B.addActionListener(this);    add(B);        Toolkit tk=Toolkit.getDefaultToolkit();    IMG=tk.getImage(".\java.jpg");    //load image1       MediaTracker mt=new MediaTracker(this);               mt.addImage(IMG,1);    try {mt.waitForAll();}                    catch(InterruptedException e)                     {                     System.out.println(e.getMessage());                     };        setVisible(true);        //encode    codeBase64(IMG);        }private void codeBase64(Image i){int cnt=0;try{   InputStream is = new BufferedInputStream( new FileInputStream(".\java.jpg"));    while((cnt=is.read(buffer_code))!=-1)     {     String s = new sun.misc.BASE64Encoder().encode(buffer_code);      TA.append(s+"
");      }   }catch(IOException e){System.out.println(e.getMessage());}}//decodeprivate void decodeBase64(String sb){try{   buffer_decode=new sun.misc.BASE64Decoder().decodeBuffer(sb);    IMGdecode=Toolkit.getDefaultToolkit().createImage(buffer_decode);   bool=true;   repaint();   }catch(IOException e)      {System.out.println(e.getMessage());}}public void paint(Graphics g){//drawing image1g.drawImage(IMG,325,50,this);//drawing same image but after decodeif(bool)g.drawImage(IMGdecode,325,240,this);g.drawString("Before:",325,60);g.drawString("After:",325,250);g.drawString("Encode image:",10,55);}public void actionPerformed(ActionEvent e) { if(e.getActionCommand().equals("Decodare"))    {    //decode    decodeBase64(TA.getText());    } }}public class Base64{public static void main(String[] args){    Base64Example t=new Base64Example("Base64");       t.init();    }}
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: