java图像裁剪(生成文件缩略图)

/**
	 * 生成文件缩略图
	 * @param src 
	 * @param dest
	 * @param proportion
	 * @param width
	 * @param height
	 * @throws IOException
	 * @throws ImageFormatException
	 */
	public static void compress(File src, File dest, Boolean proportion, Integer width, Integer height)
			throws IOException, ImageFormatException {
		if (!src.exists()) {
			throw new FileNotFoundException("CompressPic: src file is not exist! ");
		}
		Image img = ImageIO.read(src);

		int newWidth; int newHeight;
		// 判断是否是等比缩放
		if (proportion) {
			// 为等比缩放计算输出的图片宽度及高度
			double rate1 = ((double) img.getWidth(null)) / (double) width + 0.1;
			double rate2 = ((double) img.getHeight(null)) / (double) height + 0.1;
			// 根据缩放比率大的进行缩放控制
			double rate = rate1 > rate2 ? rate1 : rate2;
			newWidth = (int) (((double) img.getWidth(null)) / rate);
			newHeight = (int) (((double) img.getHeight(null)) / rate);
		} else {
			newWidth = width; // 输出的图片宽度
			newHeight = height; // 输出的图片高度
		}

		BufferedImage tag = new BufferedImage((int) newWidth, (int) newHeight, BufferedImage.TYPE_INT_RGB);
		/*
		 * Image.SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的
		 * 优先级比速度高 生成的图片质量比较好 但速度慢
		 */
		tag.getGraphics().drawImage(img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0, null);
		
		dest.getParentFile().mkdirs();
		FileOutputStream out = new FileOutputStream(dest);
		// JPEGImageEncoder可适用于其他图片类型的转换
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
		encoder.encode(tag);
		out.close();
	}
	

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值