最后能够使用 img 标签在网络浏览器上显示图像。我现在遵循的步骤: 1. 我使用 BufferedImage 读取图像。2.使用ByteArrayOutputStream将bufferedImage转换为字节。3.使用 apache commons codec lib 将该流编码为 Base64 并转换为字符串 4.使用 img 标签在 html 上返回该图像的字符串值
//Pseudo Code
BufferedImage bufferedImage=ImageIO.read(new File(imagePath));
//imageDao contains the image name that i stored in the database
String []formatSplit=imageDao.split("\\.");
if(formatSplit.length==2){
String format=formatSplit[1];
//ImageUtility is class that contain code for converting bufferedimage to string
String traineeImage=ImageUtility.encodeToString(bufferedImage,format );
model.addAttribute("imagePath", traineeImage);
}
//ImageUtilty class -method
public static String encodeToString(BufferedImage image, String type) {
String imageString=null;
String encodedImage=null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ImageIO.write(image, type, bos);
byte[] imageBytes = bos.toByteArray();
encodedImage=org.apache.commons.codec.binary.Base64.encodeBase64String(imageBytes);
imageString = "data:image/"+type+";base64,"+encodedImage;
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
return imageString;
}
在 img 标签 src 属性中,我通过了 imageString 并且它起作用了。为了找到解决方案,我从 stackoverflow 和其他博客中找到了很多提示,这些提示帮助我实现了我正在寻找的东西。谢谢。