压缩图片分辨率

public class CompressImage {
	private static final Log log = LogFactory.getLog(CompressImage.class);

	private int destWidth;// 压缩后的长
	private int destHeight;// 压缩后的高

	/**
	 * 指定压缩后的长度,按比例计算出压缩后的高度
	 * 
	 * @param width
	 */
	public CompressImage(int width) {
		this.destWidth = width;

	}

	/**
	 * 指定压缩后的长度和高度
	 * 
	 * @param width
	 * @param height
	 */
	public CompressImage(int width, int height) {
		this.destHeight = height;
		this.destWidth = width;

	}

	// 根据长度计算出高度
	private int getHeight(int width, int height)  	{

		if (width > destWidth) {
			float scale;// 计算原图比例
			scale = (float) width / (float) destWidth;
			float hh = height / scale;
			return (int) hh;
		} else {
			this.destWidth = width;
			return height;
		}

	}

	/**
	 * 压缩图片分辨率
	 * 
	 * @param srcPath
	 * @param destPath
	 * @throws Exception
	 */
	public void compress(String srcPath, String destPath) {
		try {
			File _file = new File(srcPath);
			log.debug("SrcImagePath:" + _file.getAbsolutePath());
			Image src = javax.imageio.ImageIO.read(_file);
			int wideth = src.getWidth(null);// 获得图片长

			int height = src.getHeight(null);// 获得图片高度
			log.debug("StrImage:" + wideth + "*" + height);
			int htagHeight = this.destHeight == 0 ? this.getHeight(wideth,
					height) : this.destHeight;
			BufferedImage tag = new BufferedImage(this.destWidth, htagHeight,
					BufferedImage.TYPE_INT_RGB);
			Graphics g = tag.getGraphics();
			g.drawImage(src, 0, 0, this.destWidth, htagHeight, null);
			// if (t != null) {// 在底部图片上写文字
			// g.setColor(new Color(242, 242, 242));
			// g.fillRect(this.getWideth() - 120, htagHeight - 18, 120, 18);
			// g.setColor(new Color(180, 180, 180));
			// g.drawRect(this.getWideth() - 120, htagHeight - 18, 119, 17);
			// g.setColor(new Color(255, 102, 0));
			// g.drawString(t, this.getWideth() - 100, htagHeight - 5);
			// }
			log.debug("DestImagePath:" + _file.getAbsolutePath());
			log.debug("DestImage:" + tag.getWidth() + "*" + tag.getHeight());
			FileOutputStream out = new FileOutputStream(destPath);
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
			encoder.encode(tag);
			out.close();

		} catch (Exception e) {
			log.error("Compress Image [" + srcPath + "] error!!\r\n" + e);

		}
	}

}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值