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) {
String imagePath = "C:/images/myimage.jpg"; // 本地图片路径
String base64Image = null;
try {
File file = new File(imagePath);
FileInputStream imageInFile = new FileInputStream(file);
byte[] imageData = new byte[(int) file.length()];
imageInFile.read(imageData);
base64Image = Base64.getEncoder().encodeToString(imageData);
imageInFile.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Base64编码的图片:" + base64Image);
}
}
首先,我们需要指定本地图片的路径,然后使用FileInputStream类读取图片文件的数据,将其存储在一个byte数组中。接下来,我们使用Java 8中的Base64类将图像数据编码为base64字符串。最后,我们将编码后的字符串打印到控制台上。
请注意,此示例使用Java 8中的Base64类,如果您使用的是早期版本的Java,则需要使用其他库或自己实现base64编码
原文地址: https://www.cveoy.top/t/topic/ckAo 著作权归作者所有。请勿转载和采集!