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


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


This article source code is available at GitHub repo

  • WilliamsRivas

    Thanks, it is I need

    • jeevatkm

      @WilliamsRivas I’m glad, Thanks!

      • 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 please suggest me(converting image to string program)

        • jeevatkm

          @nagarjuna renintech  @WilliamsRivas If your project is mavenized then add this into your pom.xml
          Else download the jar from and add it your project build path.

          • ThankGod

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

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


          • 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?

          • 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

            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?


            // 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()];

            // 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.close();

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

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

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

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


          • subham

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

          • 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″…

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

            – 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(….)’

          • Manjeet kumar

            import ;
            after importing this u try to use the method as ..Base64.encode(imageByteArray) ;

            //use this method in both encoding and decoding…
            return Base64.encode(imageByteArray);
            return Base64.encode(imageByteArray);

            Manjeet Kumar ([email protected])

          • 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).

  • 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



    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.

  • @jeevatkm


    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.

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


      • Chanduram Naidu

        hi jeevanandam ,this is chandu i am working on a project where i need to get numeric data or text data from that image .For example if picture is daily news paper then i have to extract data from that picture
        Please help me …..

  • 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.

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


  • 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

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


  • 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.

    • @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.


  • 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.

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


    • Chanduram Naidu

      hi gnanamoorthi ,this is chandu did u find any solution for your problem if u do please share that solution. My mail id [email protected]

  • Satyam Singh

    unable to call Base64.encodeBase64URLSafeString(); method……

    • @disqus_O7oNlyXeXz:disqus ensure you have apache commons-codec lib in your classpath.


      • Satyam Singh

        Ohhh…..! thanks sir….actually i was using old version of commmon-codec lib……….but now i have downloaded new one…..and it is working…….but i also have another issue…..your code reads and image and convert it into another image after encoding and decoding its content, but i only need to extract Characters or Strings and Integers from an Image and print it…..if it is possible with this code or some other code snippet then kindly help me….

        Thanks in adv…
        Satyam Singh

        • Chanduram Naidu

          hi satyam ,this is chandu i am also searching on the same issue could you help me out

          Thank you

        • Ruchi

          I am having the same issue if you can help me out It’s not taking import as org.apache.commons.codec.binary.Base64 so it gives error
          error: cannot find symbol
          return Base64.encodeBase64URLSafeString(imageByteArray);

          I have added common-codec 1.9 jar file in the libraries folder .
          How can I resolve this issue?
          Any kind of help is appreciated :)
          Thank you.

          • @disqus_DlC205HlZn:disqus Did you added to your project BUILD PATH? then it should resolve.


          • Ruchi

            Basically , where am I supposed to add this apache common codec lib?
            I have added it in the libraries
            Can you please send me the link to download the jar file maybe there is something wrong with the one I have?


  • Satyam Singh

    @jeevatkm:disqus whenever u’ll be online…..i need some conversation regarding this issue…..

  • rafa457

    hi,how to convert image to binary data and binary data back to image??

  • thandar

    although import still the error Base64.encodeBase64URLSafeString(imageByteArray)

  • thandar

    When I run this sample code the following error occur. After import the org.apache.commons.codec.binary.Base64 still the error like that

  • Aviral

    Is it possible to read and extract text written on the image and save it some where in some file??

    • @disqus_B4ycNxZe6F:disqus No, It is not feasible with this approach! you might have to try OCR approach.


  • Thanks buddy. Was searching for encoding and decoding examples using Base64. Finally got it.

  • Fahid

    is this code can be used for txt file uploading and can you please tell me that what shoud be written in php header function as in case of text file ???

    • @disqus_4sat54vpHX:disqus – what is your objective? for a text file, upload as-is. why you need one extra layer of conversion.


  • Rahul Kadam

    sir, I m new to java.. i paste your code in net beans.. and i got some errors

  • Sittichai Saramad

    Why I do not

    • Tự Nông Lâm

      should use lid 1.7

  • Darshita

    I am not getting the right output jpg file. I wrote the same code in scala. Scala uses Java File, FileInputStream, FileOutputStream, so code is almost same. I have downoladed jpg file from web and stored into my filesystem. The size of the image is 611.0 KB but when it reads the file in Byte[] Array, it shows the length of Byte[] is 44 bytes only and after encoding and decoding operation, it generates 44 bytes output jpg file which gives error when I try to open it.

    Can you please help me to solve the problem ?

    Thank You

  • Darshita

    Got my mistake. Problem Solved.

    • @disqus_c7VkD7O4xt:disqus Thanks for the update. I was looking at my end, glad to hear that it’s solved.


  • Amay Trivedi

    hey there ..It was a nice tutorial :)..
    but im looking forward to replace my text with emoji..can u tell me how i can achieve that thing
    Thanks in advance..:)

  • Huy Lê


  • venkatakrishnareddy medam


  • prudhvi raj

    Hi, I have group of screenshots that are saved in a word format I need to read the word document file using java script get the data in the image & compare with the reports in excel sheet is it possible?? please help me out

  • Sandeep Narayanan

    Thanks a lot

  • Dragos Aghiniei

    Some help?

  • Dragos Aghiniei

    anyone here for some help?

  • Stanislas Paliard

    nice ! Thank you :-)

  • Santosh shetye
  • Bruno Eleodoro Roza

    Hi, you don’t know how much it helps me……


    You are the best

  • buto ijo

    hi, Jeeva. is it possible to insert some text into convetter string?
    thanks for the above code BTW.
    help me please, its my email [email protected]

  • Rakesh .p

    hi ,i uploaded image into mysql database using spring mvc and hibernate and now want to display the image ?what is the process to be followed.

  • Noel Kaaya

    that is very nice