Summary

Cameleon (mwanasimba, Flickr Creative Commons)The goal here is to convert/transform Image into Base64 String and convert/transform Base64 String back to Image without compromising a Image data.  I will be using Apache Commons Codec library to achieve the same. (This article was triggered by Linkedin Discussion)

Class: org.apache.commons.codec.binary.Base64

Methods: Base64 class has overloaded methods

  • Base64.encodeBase64URLSafeString – accepts input as byte array and converts into Base64 String
  • Base64.decodeBase64 – accepts input as Base64 String and converts into byte array

How to do: step by step?

Step 1:

Preparing a byte array from image.  Typically achieved in following ways:

  • During File upload – at server side application will be receiving a file data as byte stream
  • Reading a image file from File System as byte stream

Step 2:

Once we have byte array of Image file, apply below method to convert byte array into Base64 string.  Here even though string is not used in URL param, consider using URL safe Base 64 string.  The url-safe variation emits – and _ instead of + and / characters.

Method signature: 
public static String encodeBase64URLSafeString(byte[] binaryData)

Usage: 
String imageDataString = Base64.encodeBase64URLSafeString(imageByteArray)

Now, we have image file as string data type, it can be easily transmitted as need (through XML, JSON, etc).

Step 3:

At receiving end, we will be receiving a Base64 String of Image data, apply below method to covert Base64 String into byte array

Method signature: 
public static byte[]  decodeBase64(String base64String)

Usage: 
byte[] imageDataBytes = Base64.decodeBase64(imageDataString)

Step 4:

We have imageDataBytes byte array, write this stream as file in the File system


Complete Sample Code (Downloadable Java file Click here)

package com.myjeeva.image;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.codec.binary.Base64;

/**
 * @desc Image manipulation - Conversion
 * 
 * @filename ImageManipulation.java
 * @author Jeevanandam M.
 * @copyright myjeeva.com
 */
public class ImageManipulation {
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		File file = new File("/Users/jeeva/Pictures/wallpapers/water-drop.jpg");

		try {			
			// Reading a Image file from file system
			FileInputStream imageInFile = new FileInputStream(file);
			byte imageData[] = new byte[(int) file.length()];
			imageInFile.read(imageData);

			// Converting Image byte array into Base64 String
			String imageDataString = encodeImage(imageData);

			// Converting a Base64 String into Image byte array
			byte[] imageByteArray = decodeImage(imageDataString);
			
			// Write a image byte array into file system
			FileOutputStream imageOutFile = new FileOutputStream(
					"/Users/jeeva/Pictures/wallpapers/water-drop-after-convert.jpg");
			imageOutFile.write(imageByteArray);

			imageInFile.close();
			imageOutFile.close();

			System.out.println("Image Successfully Manipulated!");
		} catch (FileNotFoundException e) {
			System.out.println("Image not found" + e);
		} catch (IOException ioe) {
			System.out.println("Exception while reading the Image " + ioe);
		}

	}
	
	/**
	 * Encodes the byte array into base64 string
	 *
	 * @param imageByteArray - byte array
	 * @return String a {@link java.lang.String}
	 */
	public static String encodeImage(byte[] imageByteArray) {
		return Base64.encodeBase64URLSafeString(imageByteArray);
	}
	
	/**
	 * Decodes the base64 string into byte array
	 *
	 * @param imageDataString - a {@link java.lang.String}
	 * @return byte array
	 */
	public static byte[] decodeImage(String imageDataString) {
		return Base64.decodeBase64(imageDataString);
	}
}

Result

Successfully, we were are able to manipulate the Image as String data and vice versa (convert image to string and string to image in java).

Screenshot: Java Image Manipulation Result

Screenshot: Java Image Manipulation Result


Downloadable

This article sample code available at GitHub repo “ImageManipulation.java“.

Tagged with →  
  • WilliamsRivas

    Thanks, it is I need

    • jeevatkm

      @WilliamsRivas I’m glad, Thanks!

      • nagarjuna renintech

        @jeevatkm
        i have tried your program and am unable to import the header file
        import org.apache.commons.codec.binary.Base64;
        and it is very important to me please suggest me(converting image to string program)
        @WilliamsRivas

        • jeevatkm

          @nagarjuna renintech  @WilliamsRivas If your project is mavenized then add this into your pom.xml
          <dependency>
          <groupId>commons-codec</groupId>
          <artifactId>commons-codec</artifactId>
          <version>1.7</version>
          </dependency>
           
          Else download the jar from http://commons.apache.org/codec/download_codec.cgi and add it your project build path.

          • ThankGod

            is it possible to send the Base64 String as an SMS to a mobile phone?

          • http://myjeeva.com/ Jeevanandam M.

            Yes, technically it is feasible to send. However SMS has length limit, i.e. 160 characters per SMS. So plan out your implementation accordingly.

            Cheers,
            Jeeva

          • ThankGod

            After converting my barcode to base64 string, i sent it via the HTTPSMS API to be delivered to a phone as a barcode sms. I keep getting the error message “Bad request message from server”. Can you please help me out by pasting sample code here?
            Thanks

          • http://myjeeva.com/ Jeevanandam M.

            Are you sure you’re not receiving an error for SMS character limit of 160?

            If error is related to conversion then send me a code snippet to jeeva at myjeeva dot com

          • ThankGod

            Hello,
            Below is the part of the code; I observed that from
            the program below, i sent the variable, imageDataString which value is
            as shown below, then concatenate it with few plane text as show in the
            program at the bottom. AM i doign something wrong?


            iVBORw0KGgoAAAANSUhEUgAAAEgAAABICAIAAADajyQQAAABlUlEQVR42u2ZwQ6DMAxD-f-f3m4ToraTbSnJJnNAE7CqjzSOG47Hnx6HwQxmMIMZzGAGM5jBDGYwgxnMYAbbCnag43z3dWbPnx_Qo90Nxq5AKvYjHK0HbH39ySme_y5GGwe2rjQdmd8AY1dgKg4FE6tLJJJIwhE5JoTug_MUVfxGVKpmf0eOXVbgisdWphinLWLhVC5xY3X8kpmD6tiqbzAIEAP6le-DVqOKMH-Sag5fULN4wNRaowEnCqcuVmZ_jsEXv8ILW9xcoIXKCc_OVDEMZg-YthRsce5TjhqwjGlgWsIUslkV8_tLbcS0kLTVMbhJSap8qLRTIsb0kMVNh3FEjrGay-wiW35VtrjeeSQtstj1jLBULJdYmQqfHASWnGJoBQv9VM1SDN2Qrs46FWftoMWmU-8-dRtvUCcYljUog7UOeFeXStQ05uVnRUx0ETNGeVO3Y3snmDUCMp2f_o8Sos2WscJVlveOHAtvvfVGZnWCRW9HiE1tAP1F02AGM5jBDGYwgxnMYAYzmMEMZjCD_ePxBG_rF-AihezbAAAAAElFTkSuQmCC

            // File will be used for creating the QRCode barcode type.
            File qrCodeFile = new File(“C:/barcode/QRCode.png”);

            // Building the encoding configurations – using builder battern

            EncodeConfig encodeConfig =new EncodeConfig.Builder().createDirectories(Boolean.TRUE).isQRCodeFormat(Boolean.TRUE).withErrorCorrLevel(ErrorCorrectionLevel.M).build();

            // Generating the QRCode barcode

            String content = “This is the contents of the barcode. 1234567 (QRCode)”;

            // BarcodeEngine.encode(qrCodeFile, content, BarcodeFormat.QR_CODE, 150, 150, encodeConfig);
            BarcodeEngine.encode(qrCodeFile, content, BarcodeFormat.QR_CODE, 72, 72, encodeConfig);

            encodeConfig =new EncodeConfig.Builder().createDirectories(Boolean.TRUE).withCharactersMode(Mode.ALPHANUMERIC).build();

            // The main code start here

            try {
            // Reading a Image file from file system

            FileInputStream imageInFile = new FileInputStream(qrCodeFile);
            byte imageData[] = new byte[(int) qrCodeFile.length()];
            imageInFile.read(imageData);

            // Converting Image byte array into Base64 String

            imageDataString = encodeImage(imageData);

            // Converting a Base64 String into Image byte array
            byte[] imageByteArray = decodeImage(imageDataString);

            // Write a image byte array into file system

            //FileOutputStream imageOutFile = new FileOutputStream(“/Users/jeeva/Pictures/wallpapers/water-drop-after-convert.jpg”);
            //imageOutFile.write(imageByteArray);

            imageInFile.close();

            // imageOutFile.close();

            System.out.println(“Image Successfully Manipulated!”);

            // sms.setMessage(imageDataString+”n “+message);
            sms.setMessage(imageDataString+”n “+message);

            //System.out.println(imageDataString);
            } catch (Exception e) {
            System.out.println(“Error due to” + e);
            }

          • http://myjeeva.com/ Jeevanandam M.

            I have replied to your email. Have a look and let me know the outcome.

            Cheers,
            Jeeva

          • subham

            The method encodeBase64URLSafeString(byte[]) is undefined for the type Base64 giving error

          • http://myjeeva.com/ Jeevanandam M.

            You have to use apache commons-codec library. Since Base64 class present in commons-lang too. So use it appropriately.

          • Nirmal

            i have imported the apache commons-codec library . but stil i am getting the error “The method encodeBase64URLSafeString(byte[]) is undefined for the type Base64″…

          • http://myjeeva.com/ Jeevanandam M.

            It might be getting clash with commons-lang library class of ‘Base64′.

            Possibilites:
            - Remove commons-lang lib from project reference
            - If you need both library then use it with full reference like ‘org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(….)’

  • nagarjuna renintech

    i have tried your program and am unable to import the header file
    import org.apache.commons.codec.binary.Base64;
    and it is very important to me

  • srinivas

    @jeevatkm

    Hi,
    i have tried your code it is working properly.
    I need Image to text conversion in java. Because im working on a project in which i need to extract the text from a image. could you help me.

  • http://www.linkedin.com/profile/view?id=231214102&trk=tab_pro srinivas

    @jeevatkm

    Hi,
    I need Image to text conversion in java.
    im working on a project in which i need to extract the text from a image. could you help me.

    • http://www.myjeeva.com Jeevanandam Madanagopal

      Hello Srinivas – Share the detailed information on which you need a help.

      Cheers,
      Jeeva

  • Sanjeev

    I am able to create Image using Base64Decoder, but I am unable to display that created image in normal html using <img tag, any other image can be displayed but image created using decoder is not been able to display even in simple html Can anybody suggest on this.

    • http://www.myjeeva.com Jeevanandam Madanagopal

      Hello Sanjeev – Typically it should work. Can you please share code and sample image file you’re using?

      Cheers,
      Jeeva

  • stanblaster

    Hi, i have a problem converting an image to binary data. I want to store the binary data into notepad in file system. hopefully hear you soon sir. This is for my final year project. Thank you

    • http://myjeeva.com/ Jeevanandam M.

      Hello – Can you please explain your purpose/goal? then I will able to guide you in a right direction. Please let me know.

      Cheers,
      Jeeva

  • kp

    Hello sir, i have Screenshot of mobile with contant like “your balance is 5.00 rs. ” Now i need to change this image to text for dispy in UI as text and msg it to other.

    • http://myjeeva.com/ Jeevanandam M.

      @disqus_zMaNa9cAEH:disqus – I’m sorry for late response. When you call encodeImage(…) you will get string of image. After that you can message it.

      Cheers,
      Jeeva

  • gnanamoorthi

    Hi,i have Screenshot of mobile with content like below image .Now i need to change this image to text for display in UI . can u please help me.

    • http://myjeeva.com/ Jeevanandam M.

      Sure, share your method code snippet to jeeva at myjeeva dot com

      Cheers,
      Jeeva