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.


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.




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

9 thoughts on “Convert Image to Base64 String or Base64 String to Image in Java”

    1. It is not that much hard if you have interest in it. Yes if you compare it with other languages then one can say it is hard 😀

  1. How can we convert a String which is Base64 String to image ?


    String encodedString = “/9/xdfdsfdsfdsf………..”;

    FileOutputStream fos = new FileOutputStream(“D:/xyz.jpg”);

Leave a Comment

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