#准备
- 数据库字段a
- 图片 test.png
- 项目
#过程
-
将图片上传,使用数据库字段a保存test.png的图片路径
-
后端获取到数据库字段a保存的地址数据,通过地址获取文件,读取文件转换为base64
-
在前端使用时,在img标签的src中,需要这样使用’data:image/jpeg;base64,’ + base64Data
//转换base64
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 = "路径/图片.jpg"; // 指定图片的路径
try {
String base64Image = convertImageToBase64(imagePath);
System.out.println(base64Image);
} catch (IOException e) {
e.printStackTrace();
}
}
public static String convertImageToBase64(String imagePath) throws IOException {
File file = new File(imagePath);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] imageBytes = new byte[(int) file.length()];
fileInputStream.read(imageBytes);
fileInputStream.close();
return Base64.getEncoder().encodeToString(imageBytes);
}
}