如何使用 Java 将图像转换为 base64 字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2781545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I convert an image to a base64 string using Java?
提问by hussain
As the title indicates, I want to know how to convert an image to a base64 string in Java. How can I do this?
正如标题所示,我想知道如何在 Java 中将图像转换为 base64 字符串。我怎样才能做到这一点?
回答by aioobe
Use the Base64
class.
使用Base64
类。
If you're on pre-Java 8, have a look at one of the following resources:
如果您使用的是 Java 8 之前的版本,请查看以下资源之一:
回答by Lars
The Apache Commons Base64for encoding and decoding
用于编码和解码的Apache Commons Base64
回答by Raman B
java code to convert image to string
将图像转换为字符串的java代码
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
并可以将其嵌入到 XSL 中,如下所示
<img src="data:image/png;base64,iVBORw0......."/>