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.

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

Step 4

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


 

Source Code – for Download Click here


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.