Wednesday, August 1, 2012

JAVA: Convert Image to Base64 String and Base64 String to Image


Introduction

Sometimes we will want to convert an image to a string, for example, store it in database or transfer it via XML. This post will show how to convert image to string/string to image.

The Program

ImageUtils.java

package test;

import java.io.IOException;

import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;

public class ImageUtils {

    /**
     * Decode string to image
     * @param imageString The string to decode
     * @return decoded image
     */
    public static BufferedImage decodeToImage(String imageString) {

        BufferedImage image = null;
        byte[] imageByte;
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            imageByte = decoder.decodeBuffer(imageString);
            ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
            image = ImageIO.read(bis);
            bis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return image;
    }

    /**
     * Encode image to string
     * @param image The image to encode
     * @param type jpeg, bmp, ...
     * @return encoded string
     */
    public static String encodeToString(BufferedImage image, String type) {
        String imageString = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        try {
            ImageIO.write(image, type, bos);
            byte[] imageBytes = bos.toByteArray();

            BASE64Encoder encoder = new BASE64Encoder();
            imageString = encoder.encode(imageBytes);

            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imageString;
    }

    public static void main (String args[]) throws IOException {
        /* Test image to string and string to image start */
        BufferedImage img = ImageIO.read(new File("files/img/TestImage.png"));
        BufferedImage newImg;
        String imgstr;
        imgstr = encodeToString(img, "png");
        System.out.println(imgstr);
        newImg = decodeToImage(imgstr);
        ImageIO.write(newImg, "png", new File("files/img/CopyOfTestImage.png"));
        /* Test image to string and string to image finish */
    }
}


Reference
Working with Images
http://docs.oracle.com/javase/tutorial/2d/images/index.html


Download
File at github
https://github.com/benbai123/JSP_Servlet_Practice/blob/master/Practice/JAVA/Commons/src/test/ImageUtils.java

45 comments:

  1. where we dowanload in this jar sun.misc.BASE64Encoder
    send the link this manil id

    ReplyDelete
    Replies
    1. I use Alternate JRE (jre7) as JRE System Library then it works. But I think you can use any other Base64 Encoder/Decoder as needed.

      Delete
  2. And how i get Text in BufferedImage ?

    i make printScreen of text and how get it ?
    thanks

    ReplyDelete
    Replies

    1. What you need is an OCR tool for java (if you using java), refer to the thread at stackoverflow for more information

      http://stackoverflow.com/questions/971344/java-based-ocr-sdk-api

      Delete
  3. Replies
    1. I am not familiar with android, probably you can use it directly or you need to find appropriate package/class accordingly.

      Found some related articles at stackoverflow

      http://stackoverflow.com/questions/7360403/base-64-encode-and-decode-example-code

      http://stackoverflow.com/questions/4836760/how-to-use-base64-included-in-android-since-api-8-2-2-in-a-android-project-a

      http://stackoverflow.com/questions/9768611/encode-and-decode-bitmap-object-in-base64-string-in-android

      Delete
  4. Really i am killed in scanning. Could you please help me. i will pay for your service.
    my email id vbsenthilinnet@gmail.com

    ReplyDelete
    Replies
    1. The problem is not with respect to payed or not, but I cannot help you without your environment (the scanning tool and its hardware/software accordingly), you should ask the vendor of that tool instead of me since what I can help is only ZK-related questions.

      Delete
  5. Hello i am almost done. can you please give me hint after decoding how to show the image directly to ZK Image component without storing in the server cide

    ReplyDelete
    Replies
    1. You can change src of image with javascript:

      <image id="img" />

      then

      zk.Widget.$('$img').getImageNode().src = 'PATH_TO_IMAGE';

      Delete
  6. how if we want to convert an imageIcon to Base64 ? plz

    ReplyDelete
    Replies
    1. what is "imageIcon" here? actually you can convert any java Object to Base64 String if you can get an byte array from that object.

      Delete
  7. what if we use byte array in our programs to store the images? can we just use getByteArray() methods with this to store it to database?

    ReplyDelete
  8. thank u, very much useful ...

    ReplyDelete
  9. Hello Sir i used above code after getting byteString...I m trying to update in google Directory API...They Said invalid byteString

    https://developers.google.com/admin-sdk/directory/v1/reference/users/photos/update

    above is url can u help me where i did wrong?

    ReplyDelete
    Replies
    1. As mentioned in the document you need to convert the Base64 String to web-safe Base64, please refer to my testing strings (invalid and valid): https://gist.github.com/benbai123/a34bd1d5bdcf8037d831

      Delete
  10. your string is valid...i also did same thing but string is not valid......my Code is

    public static byte[] encodeToString(BufferedImage image, String type) {
    byte[] imageString = null;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
    ImageIO.write(image, type, bos);
    byte[] imageBytes = bos.toByteArray();
    Base64 encoder = new Base64();
    imageString = encoder.encodeBase64(imageBytes);
    bos.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    return imageString;
    }

    public static void main (String args[]) throws IOException {
    BufferedImage img = ImageIO.read(new File("/home/user166/Firefox_wallpaper.png"));
    BufferedImage newImg;
    String imgstr = new String(encodeToString(img,"png"));
    imgstr = imgstr.replace("/", "_");
    imgstr = imgstr.replace("+", "-");
    imgstr = imgstr.replace("=", "*");
    System.out.println(imgstr);
    }

    ReplyDelete
    Replies
    1. If i removed * from that ecoded string then its working fine

      Delete
    2. Can you provide an image for testing?

      Delete
    3. Sir it's Working fine......very helpful..Thanks

      Delete
  11. I would recommend against using Sun's internal proprietary API. I've modified your methods to use javax.xml.bind.DatatypeConverter instead:

    /**
    * Decode string to image
    * @param base64String The string to decode
    * @return decoded image
    */
    public static BufferedImage decodeToImage(String base64String) {

    BufferedImage image = null;
    byte[] imageByte;
    try {
    imageByte = DatatypeConverter.parseBase64Binary(base64String);
    ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
    image = ImageIO.read(bis);
    bis.close();
    } catch (Exception e) {
    e.printStackTrace();
    }
    return image;
    }

    /**
    * Encode image to string
    * @param image The image to encode
    * @param type jpeg, bmp, ...
    * @return encoded string
    */
    public static String encodeToString(BufferedImage image, String type) {
    String imageString = null;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {
    ImageIO.write(image, type, bos);
    imageString = DatatypeConverter.printBase64Binary(bos.toByteArray());

    bos.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    return imageString;
    }

    ReplyDelete
  12. Can't we get the string as output on the console?

    ReplyDelete
    Replies
    1. yes you can, you can find "System.out.println(imgstr);" in the sample code above.

      Delete
  13. Hi Ben,

    Any sample code you have on "Convert PDF to Base64 String" ...

    ReplyDelete
    Replies
    1. Yes, actually you can convert any type of file to string

      code at pastebin: http://pastebin.com/QML4AMYV

      Apache commons io: http://commons.apache.org/proper/commons-io/

      Delete
    2. Hey Ben,

      Below is my working code snippet..


      /**
      * Encode PDF to string
      *
      * @param filePath
      *
      * @return encoded string
      * @throws IOException
      */

      public static String encodePDFToString(String filePath) throws IOException {
      System.out.println("I am in encodePDFToString...");
      contenido = com.lowagie.text.pdf.codec.Base64.encodeFromFile(filePath);
      return contenido;
      }

      Delete
  14. Exactly what I was looking for.... thanks!

    ReplyDelete
  15. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. Sorry for that. There are also online services to convert image to base64. Here is also a tutorial to convert base64 image to string and string to base64 image: http://javapointers.com/tutorial/java-convert-image-to-base64-string-and-base64-to-image/

      Delete
    2. Ah...the code almost the same, but the date of that post is May 5, 2014.

      Well, glad someone make one more entry :D

      Delete
  16. Really its great to see this kind of useful blog. Thanks for sharing this blog with us.

    How much does it cost to develop an On Demand Computer Technician Hiring App? The App Ideas is leading web and Mobile App development. We provide the best IT Services at best rates. Contact us now!

    ReplyDelete