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

导读:本篇文章讲解 java图像裁剪(生成文件缩略图),希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

/**
	 * 生成文件缩略图
	 * @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();
	}
	

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/15027.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!