• Java Convert Image to Base64 String and Base64 to Image

    In this post, we will be converting an image to base64 string so that it can be save to a database, more accurately in a blob type column.

    Encode Image to Base64 String

    The below method will encode the Image to Base64 String. The result will be a String consisting of random characters, representing the image. This characters can then be save to the database. A blob type column is more applicable when saving an image to the database since a blob column can hold large amount of data.

    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;
        }
    

    Decode Base64 String to Image

    Meanwhile, you can also decode your base64 string to an image to be save or sent to the client. Below is a method on how to decode base64 string to 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;
        }
    

    For example, if the data/string came from a client request, if the base64 string starts with something like data:image/png;base64,iVBORw0KGgoAA….. you should remove data:image/png;base64, . Therefore, your base64 string should starts with eg. iVBORw0KGgoAA.

    Related Post

    • Omar Ezz Ed-Dien

      do you mean the extension by type?!!

    • Pradeep Kumar Reddy

      what jar file i need to include to use these APIs
      BASE64Decoder
      BASE64Encoder

      • Khushbu

        Do you get solution?

        which jars?

        • Rakesh .p

          Did you get the solution to include jar files?

          • AL

            You can use this: Base64.decodeBase64(imageBytes) it’s from apache commons library