Convert Image to Base64 String or Base64 String to Image in Java

In this tutorial you will learn how to convert or encode image to Base64 string and convert or decode Base64 string to image in Java.

 

What is Base64?

Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation.

 

Convert Image to Base64 String or Base64 String to Image in Java

 

Why we need to convert image to Base64 string?

Let’s consider some real life scenarios.

  • What we will do if we want to store some image in database without using blob type?
  • What we will do if we want to send and receive image to and from server?

These kinds of situations can be solved easily by converting the image into Base64 string format.

 

Note: Here we will require Apache Common Codec library. So download it from below link.

http://commons.apache.org/proper/commons-codec/download_codec.cgi

 

How to Convert or Encode Image to Base64 String?

  • Read the image using FileInputStream and convert it to byte array.
  • Convert the byte array to Base64 string by using encodeBase64String() method.

 

How to Convert or Decode Base64 String to Image?

  • Convert Base64 string to byte array using decodeBase64() method.
  • Now convert the byte array to image using FileOutputStream.

 

In below example I am first reading an image from some location and then converting it to string. After that I am converting it to image and saving to some location.

Make sure you change the path of the image according to your system.

 

Example

 

Comment below if you are facing any difficulty regarding above tutorial.

4 comments

Leave a Reply

Your email address will not be published. Required fields are marked *