使用java实现多种方式解决图片压缩的问题

  前段时间在使用对图片加水印后,由于需加水印的图片的宽度和高度都非常的大,加了水印后图片从几百KB,变成了几MB,严重影响了图片在页面的加载速度!


经过仔细的琢磨,决定先对图片进行压缩,再加水印。采用这种方式户,图片占用的空间没多大变化。

下面对压缩的代码的分享


 一、采用指定宽度、高度或压缩比例 的方式对图片进行压缩 方法:

         

/**
	 * 采用指定宽度、高度或压缩比例 的方式对图片进行压缩
	 * @param imgsrc 源图片地址
	 * @param imgdist 目标图片地址
	 * @param widthdist 压缩后图片宽度(当rate==null时,必传)
	 * @param heightdist 压缩后图片高度(当rate==null时,必传)
	 * @param rate 压缩比例 
	 */
	public static void reduceImg(String imgsrc, String imgdist, int widthdist,
			int heightdist, Float rate) {
		try {
			File srcfile = new File(imgsrc);
			// 检查文件是否存在
			if (!srcfile.exists()) {
				return;
			}
			// 如果rate不为空说明是按比例压缩
			if (rate != null && rate > 0) {
				// 获取文件高度和宽度
				int[] results = getImgWidth(srcfile);
				if (results == null || results[0] == 0 || results[1] == 0) {
					return;
				} else {
					widthdist = (int) (results[0] * rate);
					heightdist = (int) (results[1] * rate);
				}
			}
			// 开始读取文件并进行压缩
			Image src = javax.imageio.ImageIO.read(srcfile);
			BufferedImage tag = new BufferedImage((int) widthdist,
					(int) heightdist, BufferedImage.TYPE_INT_RGB);

			tag.getGraphics().drawImage(
					src.getScaledInstance(widthdist, heightdist,
							Image.SCALE_SMOOTH), 0, 0, null);

			FileOutputStream out = new FileOutputStream(imgdist);
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
			encoder.encode(tag);
			out.close();

		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

二、获取图片宽度和高度的方法:

/**
	 * 获取图片宽度
	 * 
	 * @param file
	 *            图片文件
	 * @return 宽度
	 */
	public static int[] getImgWidth(File file) {
		InputStream is = null;
		BufferedImage src = null;
		int result[] = { 0, 0 };
		try {
			is = new FileInputStream(file);
			src = javax.imageio.ImageIO.read(is);
			result[0] = src.getWidth(null); // 得到源图宽
			result[1] = src.getHeight(null); // 得到源图高
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

三、运行代码的main方法:

	public static void main(String[] args) {
		/**
		 * d://3.jpg 源图片
		 * d://31.jpg 目标图片
		 * 压缩宽度和高度都是1000
		 * 
		 */
		System.out.println("压缩图片开始...");
		File srcfile = new File("d://3.jpg");
		System.out.println("压缩前srcfile size:" + srcfile.length());
		reduceImg("d://3.jpg", "d://31.jpg", 1000, 1000,null);
		File distfile = new File("d://31.jpg");
		System.out.println("压缩后distfile size:" + distfile.length());
	
	}

以上就是压缩的代码,有需要的朋友可以拷到文件里面使用,亲测是可用的。

如果大家想了解水印的,可以访问:java实现斜水印铺满整张图

  • 14
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 9
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值