画像解像度の圧縮

2281 ワード

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
" + e); } } }