Java 图片转 Base64 编码 - 代码示例
以下是 Java 代码示例,读取电脑目录下的图片文件,并将其转换成 Base64 编码:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;
public class ImageToBase64 {
public static void main(String[] args) {
File file = new File('C:\path\to\image\file.jpg'); // 指定图片文件路径
String base64Image = convertImageToBase64(file);
System.out.println(base64Image);
}
public static String convertImageToBase64(File file) {
String base64Image = '';
try (FileInputStream imageInFile = new FileInputStream(file)) {
// 读取图片文件并转换成字节数组
byte[] imageData = new byte[(int) file.length()];
imageInFile.read(imageData);
// 使用 Base64 编码将字节数组转换成字符串
base64Image = Base64.getEncoder().encodeToString(imageData);
} catch (IOException e) {
System.out.println('Error while reading image file: ' + e.getMessage());
}
return base64Image;
}
}
这个示例代码可以读取指定路径下的图片文件,并将其转换成 Base64 编码后输出到控制台。你可以根据自己的需求进行修改和扩展。
原文地址: https://www.cveoy.top/t/topic/m64a 著作权归作者所有。请勿转载和采集!