11

As the title indicates, I want to know how to convert an image to a base64 string in Java. How can I do this?

Brad Larson
  • 170,088
  • 45
  • 397
  • 571
hussain
  • 155
  • 1
  • 3
  • 5

3 Answers3

6

Use the Base64 class.

If you're on pre-Java 8, have a look at one of the following resources:

aioobe
  • 413,195
  • 112
  • 811
  • 826
5

java code to convert image to string

package com.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 Test{
public static void main (String args[]) throws IOException {
 BufferedImage img = ImageIO.read(new File("C:/Test/logo.png"));
        BufferedImage newImg;
        String imgstr;
 imgstr = encodeToString(img, "png");
        System.out.println(imgstr);
}
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;
    }
}

and can embed it in XSL as below

<img src="data:image/png;base64,iVBORw0......."/>
Raman B
  • 331
  • 4
  • 5
0

The Apache Commons Base64 for encoding and decoding

n00begon
  • 3,503
  • 3
  • 29
  • 42
Lars
  • 1,136
  • 7
  • 16
  • 4
    Usually it is worth adding a simple example or a small excerpt from the link, to provide more context and increase the value of the answer. – Alberto Zaccagni Mar 30 '15 at 14:41
  • You should answer the question, not refer to another source to look for the answer there - that's what Google exists for. – Shai Alon Nov 10 '22 at 12:56