Convert Image to String and String to Image using Base64 encoding

This is very helpful when sending Image files or other binary files to Web server using Http post.

What is Base64 encoding ?

Base64 is a group of similar encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The Base64 term originates from a specific MIME content transfer encoding.

Base64 encoding schemes are commonly used when there is a need to encode binary data that needs be stored and transferred over media that are designed to deal with textual data. This is to ensure that the data remains intact without modification during transport. Base64 is commonly used in a number of applications including email via MIME, and storing complex data in XML.
package com.as400samplecode;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;

public class EncodeDecode {

    public static void main(String[] args) {

        try {

            //Convert binary image file to String data
            String encoded = Base64.encodeFromFile("data/inputImage.png");
            
            //Convert String data to binary image file
            Base64.decodeToFile(encoded, "data/outputImage.png");
            
            //Convert binary image file to byte array to base64 encoded string
            FileInputStream mFileInputStream = new FileInputStream("data/inputImage.png");
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int bytesRead = 0;
            while ((bytesRead = mFileInputStream.read(b)) != -1) {
               bos.write(b, 0, bytesRead);
            }
            byte[] ba = bos.toByteArray();
            encoded = Base64.encodeBytes(ba);
            
            //Convert String data to binary image file
            Base64.decodeToFile(encoded, "data/outputImage.png");
            
            //Convert binary image file to base64 encoded String data file
            Base64.encodeFileToFile("data/inputImage.png","data/encodedImage.txt");
            
            //Convert base64 encoded String data file to binary image file
            Base64.decodeFileToFile("data/encodedImage.txt","data/outputImage.png");

        }
        catch( java.io.IOException e ) {
            System.out.println(e);
        }  
    }


}

Source code for Base64.java

Just go to link, http://iharder.sourceforge.net/current/java/base64/ for the latest version and download the zip file, Extract it and find the Base64.java file. Copy it into your project.

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.