图片压缩工具类

图片压缩工具类 ,只对jpg有效 png、 gif效果不好


import java.awt.Image;
import java.io.File;
import java.io.IOException;

import javax.swing.ImageIcon;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.coobird.thumbnailator.Thumbnails;

public class ImageUtils {

	private static final Logger log = LoggerFactory.getLogger(ImageUtils.class);

	/**
	 * 图片按比缩小
	 * 
	 * @param srcFile     原文件
	 * @param resizedFile 压缩目标文件
	 * @param newWidth    压缩后的图片宽度
	 * @throws IOException
	 */
	public static void resize(File srcFile, Integer newWidth) throws IOException {

		String name = srcFile.getName();

		name = name.toLowerCase();
		if (name.contains(".png") || name.contains(".jpg") ||  name.contains(".jpeg") ) {
			resize(srcFile, srcFile, newWidth);
		} else {

			log.info("暂时不擅长处理这类型文件 fileName=" + srcFile.getPath() + " " + srcFile.getName());
		}

	}

	/**
	 * 图片按比缩小
	 * 
	 * @param srcFile     原文件
	 * @param resizedFile 压缩目标文件
	 * @param newWidth    压缩后的图片宽度
	 * @throws IOException
	 */
	public static void resize(File srcFile, File targetFile, Integer newWidth) throws IOException {

		if (newWidth == null) {
			newWidth = 2000;
		}

		ImageIcon ii = new ImageIcon(srcFile.getCanonicalPath());
		Image i = ii.getImage();

		int iWidth = i.getWidth(null);
		int iHeight = i.getHeight(null);

		System.out.println("iWidth:" + iWidth + " ; iHeight:" + iHeight);

		if (iWidth < newWidth) {
			newWidth = iWidth;
		}

		if (iWidth > iHeight) {

			Thumbnails.of(srcFile).size(newWidth, newWidth).toFile(targetFile);

		} else {
			Thumbnails.of(srcFile).size(newWidth, newWidth).toFile(targetFile);
		}

	}



	// 测试
	public static void main(String[] args) throws IOException {

		File originalImage1 = new File("C:\\data\\image\\mm-1.jpeg");
		resize(originalImage1,2500 );

//		File originalImage = new File("C:\\data\\image\\aa.jpg");
//		resize(originalImage, new File("C:\\data\\image\\s\\aa_1.jpg"), 500);

//		File originalImageB = new File("C:\\data\\image\\bb.jpg");
//		resize(originalImageB, new File("C:\\data\\image\\s\\bb_1.jpg"), 500);
//
//		File originalImageC = new File("C:\\data\\image\\c1.jpg");
//		resize(originalImageC, new File("C:\\data\\image\\s\\c1_2.jpg"), 500);
//
//		File originalImage2001 = new File("C:\\data\\image\\2001.png");
//		resize(originalImage2001, new File("C:\\data\\image\\s\\2001_2.png"), 500);
//
//		File originalImageGif = new File("C:\\data\\image\\dd.gif");
//		resize(originalImageGif, new File("C:\\data\\image\\s\\dd_2.gif"), 500);

		System.out.println("success");
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值