Java实现图片压缩的功能

package com.mtx.controller;
import java.awt.Image;
import java.awt.image.*;
import java.io.*;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import javax.imageio.ImageIO;

/**
 * 批量压缩图片,像素可调
 * @author Administrator
 *
 */
public class ShearImg {

	public static void main(String[] args) {
                 //宽度:a和高度:b 自己定义
		changeSize(a,b,"E://images");
	}

	/**
	 * 改变图片的尺寸
	 *
	 * @param newWidth,
	 *            newHeight, path
	 * @return boolean
	 */
	public static void changeSize(int newWidth, int newHeight, String path) {
		// 放一个目录过去,遍历里面的图片
		BufferedInputStream in = null;
		File[] files = new File(path).listFiles();
		for (int i = 0; i < files.length; i++) {
                             //可任意添加任何格式
			if (files[i].getName().replaceAll("(.jpg|.png|.bmp|.gif)+", "").length() != files[i].getName().length()) {

				try {
					in = new BufferedInputStream(new FileInputStream(files[i]));

					// 字节流转图片对象
					Image bi = ImageIO.read(in);
					// 构建图片流
					BufferedImage tag = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
					// 绘制改变尺寸后的图
					tag.getGraphics().drawImage(bi, 0, 0, newWidth, newHeight, null);
					// 输出流
					BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(files[i]));
					//更改格式“JPG”为任意格式png,bmp,gif等
					ImageIO.write(tag, "JPG", out);
					in.close();
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值