java-同一个图片源,输出不同尺寸的图片

第一步,用户上传一个图片,数据库存储文件属性,包含宽度,高度等,同时把图片存储到服务器。

 

第二步,访问图片的时候带入参数(图片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

输出效果图:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yqwang_cn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值