数据库字段创建
在此之前,先科普几个数据库的字段类型:
数据库中有BLOB类型的字段用于存储二进制数据
MySQL中,BLOB是个类型系列,包括:TinyBlob、Blob、MediumBlob、LongBlob,这几个类型之间的唯一区别是在存储文件的最大大小上不同。
MySQL的四种BLOB类型
类型 大小(单位:字节)
TinyBlob 最大 255
Blob 最大 65K
MediumBlob 最大 16M
LongBlob 最大 4G,
在此我们选择MediumBlob 作为存储字段的类型。
当然在存储的时候要装成字节数据进行存储。
从数据库中取出二进制图片
@RequestMapping("/getImg/{id}")
public void coverImg(@PathVariable("id") String id, HttpServletResponse response) throws ServletException, IOException {
response.setHeader("Cache-Control", "max-age=760000");
response.setContentType("image/jpeg");
ServletOutputStream out = response.getOutputStream();
BufferedImage dbImage = ImageIO.read(new ByteArrayInputStream(查询图片接口(id)));
BufferedImage bufImage = new BufferedImage(dbImage.getWidth(),dbImage.getHeight(),BufferedImage.TYPE_3BYTE_BGR);
bufImage.getGraphics().drawImage(dbImage,0,0,null);
ImageIO.write(bufImage, "jpg", out);
IOUtils.closeQuietly(out);
}