Spring MVC Thymeleaf:将缓冲图像显示为HTML文件

问题描述:

无法在html文件中显示图像。我哪里做错了?Spring MVC Thymeleaf:将缓冲图像显示为HTML文件

@RequestMapping(value = "/image/{usr.id}", headers = "Accept=image/jpeg, image/jpg, image/png, image/gif", method = RequestMethod.GET) 
public @ResponseBody BufferedImage getImage(@PathVariable("usr.id") Long id) { 
    Attachment att = attSvc.getPicById(id); 

    try { 

     InputStream in = new ByteArrayInputStream(att.getAttachmentFile()); 
     return ImageIO.read(in); 
    } catch (IOException e) { 
     System.out.println("ERROR:" + e); 
     throw new RuntimeException(e); 
    } 
} 

如果您需要更多参考资料,请告诉我!非常感谢。

这应该可以解决您的问题。

... 
public @ResponseBody byte[] getImage(@PathVariable("usr.id") Long id) { 
    ... 
     InputStream in = new ByteArrayInputStream(att.getAttachmentFile()); 
     BufferedImage img = ImageIO.read(in); 
     ByteArrayOutputStream bao = new ByteArrayOutputStream(); 
     ImageIO.write(img, "jpg", bao); 
     return bao.toByteArray(); 
    ...