As the title indicates, I want to know how to convert an image to a base64 string in Java. How can I do this?
Asked
Active
Viewed 2.9k times
3 Answers
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
-
4Usually 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