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;


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 = != -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
            //Convert base64 encoded String data file to binary image file

        catch( e ) {


Source code for

Just go to link, for the latest version and download the zip file, Extract it and find the 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.