欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

压缩图片分辨率

程序员文章站 2022-07-01 16:04:48
...
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);

		}
	}

}

 

相关标签: image