第一步,用户上传一个图片,数据库存储文件属性,包含宽度,高度等,同时把图片存储到服务器。
第二步,访问图片的时候带入参数(图片id,要求输出宽度,要求输出高度,其他):
http://xxx.xxx.xxx.xx/regionout?id=ba50dbc29aec11e8ac7000163e080199&w=458&h=290&device=pc
第三步,根据参数输出
/**
* TODO 裁剪图片一部分显示
* @param id
* @param w
* @param h
* @param device (wx|pc)默认微信(wx)
* @param response
* @author yqwang0907
* @date 2018年6月14日下午6:29:26
*/
@RequestMapping("/regionout")
@ResponseBody
public void regionout(String id,Integer w,Integer h,String device,HttpServletResponse response){
try {
if(StringUtils.isEmpty(id)){
throw new BaseException("未指定图片id");
}
Attach attach = attachService.selectByPrimaryKey(id);
if(attach == null){
throw new BaseException("图片记录不存在");
}
//启用缓存
response.setHeader("Cache-Control", "public"); //Cache-Control来控制页面的缓存与否,public:浏览器和缓存服务器都可以缓存页面信息;
response.setHeader("Pragma", "Pragma"); //Pragma:设置页面是否缓存,为Pragma则缓存,no-cache则不缓存
response.setDateHeader("Expires",System.currentTimeMillis()+60*60*1000);//缓存1小时=60分钟=60*60秒=60*60*1000秒
String path = sysdir+attach.getSavePath();//获取图片的磁盘路径
File f = new File(path);
if(!f.exists()){
f.mkdirs();
}
// 输出
Integer posi = 200;
if(attach.getWidth() != null && attach.getHeight() != null){
if(attach.getWidth()<w && attach.getHeight()<h){//原图的宽高都不够?
w = attach.getWidth();
h = attach.getHeight();
}
}
BufferedImage bufferedImage = Thumbnails.of(path).sourceRegion(Positions.CENTER, w, h).size(w, h).keepAspectRatio(false).outputFormat("png").asBufferedImage();//.toFile("d:/www/d200.jpg");
//BufferedImage bufferedImage = Thumbnails.of(path).sourceRegion(Positions.CENTER, posi, posi).size(w, h).keepAspectRatio(false).outputFormat("png").asBufferedImage();//.toFile("d:/www/d200.jpg");
ImageIO.write(bufferedImage, "png", response.getOutputStream());
} catch (Exception e) {
try {
String errSrc = "/assets/updoc/images/error/default_wx.png";
if("pc".equalsIgnoreCase(device)){
errSrc = "/assets/updoc/images/error/default_pc.png";
}
response.sendRedirect(errSrc);
} catch (IOException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
}
主要用到的jar包:thumbnailator-0.4.8.jar
输出效果图: