1. Base64 简介
Base64 是一种将二进制数据编码为 ASCII 字符串的方案。它主要用于确保二进制数据在需要以文本形式处理时不会被损坏,如通过电子邮件发送文件或在 JSON 数据中嵌入图片。Base64 编码后的数据比原始数据大约多出 33%。
2、示例
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;
public class ImageToBase64Converter {
public static void main(String[] args) {
// 指定要转换的图片路径
String imagePath = "path/to/your/image.jpg"; // 替换为实际图片路径
try {
String base64String = convertImageToBase64(imagePath);
System.out.println("Base64 String: " + base64String);
} catch (IOException e) {
System.err.println("Error converting image to Base64: " + e.getMessage());
}
}
/**
* 将给定路径的图像转换为 Base64 编码字符串
*
* @param imagePath 图像文件的路径
* @return Base64 编码的字符串
* @throws IOException 如果读取文件时发生错误
*/
public static String convertImageToBase64(String imagePath) throws I