Convert Image to String and String to Image in Java

Convert Image to String and String to Image in JavaThe 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 ‘Convert Image to String and String to Image in Java’. This article was triggered by Linkedin Discussion.

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

Methods: Base64 class has overloaded methods

  • Base64.encodeBase64URLSafeString – accepts byte array and converts into Base64 String
  • Base64.decodeBase64 – accepts 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 needed; 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.


 

Source Code – for Download 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. ([email protected])
 * @copyright myjeeva.com
 */
public class ImageManipulation {

	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


Download

This article source code is available at GitHub repo ImageManipulation.java.