图片压缩

本文介绍了一个使用Java编写的图片压缩工具类,该工具能够遍历指定目录下的所有.jpg图片文件,并进行等比压缩处理。文章提供了完整的代码示例,包括如何设置压缩参数、读取图片、生成新的压缩文件以及删除原始图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class ImgHelper {
	// 输入参数
	boolean flag = true;// 是否是删除原图片
	boolean ratio = true;// 是否是等比压缩

	public static void main(String[] args) {

		String root = "D:\\dd";
		File file = new File(root);
		new ImgHelper().show(file);
	}

	// 遍历文件夹
	public void show(File file) {
		if (file.isDirectory()) {
			File[] fs = file.listFiles();
			for (File f : fs) {
				show(f);
			}
		} else {
			if(file.getName().endsWith(".jpg")){
				String inpath = file.getAbsolutePath();
				String outpath = file.getParentFile().getAbsolutePath()
					+ File.separator + file.getName();
				boolean img = getImg(inpath, outpath, flag);
				System.out.println("图片压缩结果:"+img+",位置"+outpath);
			}
		}
	}

	// 得到700的图片,处理单件图片的总流程
	// 输入路径+文件名,输出路径+文件名,源文件是否删除(删除,是true)
	public boolean getImg(String inpath, String outpath, boolean flag) {
		try {
			File file = new File(inpath);
			if (file.exists()) {
				Image image = ImageIO.read(file);
				if (image == null) {
					System.out.println(file.getAbsoluteFile());
				} else {
					int height = image.getHeight(null);
					int width = image.getWidth(null);
					BufferedImage suitImgOut = getSuitImgOut(image, width, height);
					return getImgFile(suitImgOut, outpath);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	// 原子性,输入Image,尺寸大小,返回BufferedImage流
	// 输入想得到的尺寸,原图片的地址,名称,新图片的地址,名称,原图片是否删除
	public BufferedImage getSuitImgOut(Image img, int sizewidth, int sizeheight) {
		int newWidth = sizewidth;
		int newHeight = sizeheight;
		BufferedImage tag = new BufferedImage(newWidth, newHeight,
				BufferedImage.TYPE_INT_RGB);
		tag.getGraphics().drawImage(
				img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH),
				0, 0, null);
		return tag;
	}

	// 根据图像包装流生成文件
	public boolean getImgFile(BufferedImage buffimg, String outpath) {
		try {
			FileOutputStream out;
			out = new FileOutputStream(outpath);
			// JPEGImageEncoder可适用于其他图片类型的转换
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
			encoder.encode(buffimg);
			out.close();
			return true;
		} catch (Exception e) {
			System.out.println("根据图像包装流生成文件发生异常");
			return false;
		}
	}

	public boolean isRatio() {
		return ratio;
	}

	public void setRatio(boolean ratio) {
		this.ratio = ratio;
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

失落夏天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值