java 图片等比例压缩工具

因做项目涉及到用户上传图片头像,上传头像很高清,导致显示卡顿,及需要压缩图片,便整理了一个压缩工具,就是同一个大小执行压缩后都可以达到最大的压缩比列,减少文件大小
直接上代码无需额外的依赖包

1.主执行方法

public class ImgCut {

    public static void main(String[] args) {
        //String dirPath = "D:\\图片压缩";
        //String toDir = "D:\\图片压缩result";
        //cutImg(dirPath, toDir, 1080);
        Scanner input = new Scanner(System.in);
        //输入图片路径
        String dirPath = getInputDirPath(input);
        //输入输出路径
        String toDir = getInputToDirPath(input, dirPath);

        //输入压缩大小
        Integer cutNum = getInputCutNum(input);
        input.close();
        //压缩
        cutImg(dirPath, toDir, cutNum);
    }

    private static String getInputDirPath(Scanner input) {
        String path = "";
        boolean inFlag = true;
        while (inFlag) {
            System.out.print("请输入图片路径:");
            path = input.nextLine();
            File filePath = null;
            File[] files = null;
            try {
                filePath = new File(path);
                files = filePath.listFiles();
            } catch (Exception e) {
                System.out.println(e.getMessage());
                System.out.println("请输入正确的文件路径!");
            }
            if (filePath.exists()) {
                if (files == null || files.length == 0) {
                    System.out.println("输入路径为:" + path + ",路径下没有文件!!!");
                } else {
                    System.out.println("路径下有文件:" + files.length + "个");
                    break;
                }
            } else {
                System.out.println("请输入正确的文件路径!");
            }
        }
        return path;
    }

    private static String getInputToDirPath(Scanner input, String dirPath) {
        String path = "";
        boolean inFlag = true;
        while (inFlag) {
            System.out.print("请输入输出路径:");
            path = input.nextLine();
            File filePath = null;
            try {
                filePath = new File(path);
            } catch (Exception e) {
                System.out.println(e.getMessage());
                System.out.println("请输入输正确的出路径!");
            }
            if (filePath.exists()) {
                if (dirPath.equals(path)) {
                    System.out.println("输入目录和输出目录不能在同一路径!");
                } else {
                    break;
                }
            } else {
                System.out.println("请输入正确的文件输出路径!");
            }
        }
        return path;
    }

    private static Integer getInputCutNum(Scanner input) {
        Integer cutNum = 0;
        String str = null;
        boolean inFlag = true;
        while (inFlag) {
            System.out.print("请输入图片压缩大小宽度:");
            try {
                str = input.nextLine();
                cutNum = Integer.valueOf(str);
            } catch (Exception e) {
                System.out.println(e.getMessage());
                System.out.println("请输入输正确的压缩数值!" + str);
            }
            if (cutNum > 0) {
                break;
            } else {
                System.out.println("请输入输正确的压缩数值!" + str);
            }
        }
        return cutNum;
    }

    public static void cutImg(String dirPath, String toDir, int minWidth) {
        File filePath = new File(dirPath);
        File[] files = filePath.listFiles();
        if (files != null) {
            int len = files.length;
            for (int i = 0; i < files.length; i++) {
                File file = files[i];
                if (file.exists()) {
                    System.out.print((i + 1) + "/" + len + "开始压缩:" + file.getName() + "...");
                    ImgCutUtil.reduceImg(dirPath + "\\" + file.getName(), toDir + "\\" + file.getName(), minWidth);
                    System.out.println("完成.");
                }
            }
            System.out.println(len + "个文件压缩完成!");
        }
    }
}

2.压缩图片工具类

package com.cut;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

public class ImgCutUtil {
    /**
     * 指定图片宽度和高度或压缩比例对图片进行压缩
     *
     * @param imgsrc  源图片地址
     * @param imgdist 目标图片地址
     */
    public static void reduceImg(String imgsrc, String imgdist, int minWidth) {
        int heightdist;
        int widthdist;
        //创建文件输出流
        FileOutputStream out = null;
        try {
            File srcfile = new File(imgsrc);
            // 检查图片文件是否存在
            if (!srcfile.exists()) {
                System.out.println("文件不存在");
            }
            int[] results = getImgWidthHeight(srcfile);
            if (minWidth <= (int) results[0]) {
                //计算压缩比列
                widthdist = minWidth;
                float widthOld = (float) results[0];
                float newRate = widthdist / widthOld;
                heightdist = (int) (results[1] * newRate);
            } else {
                //大小不改变,保持原大小
                widthdist = (int) results[0];
                heightdist = (int) results[1];
            }
            // 开始读取文件并进行压缩
            Image src = ImageIO.read(srcfile);

            // 构造一个类型为预定义图像类型之一的 BufferedImage
            BufferedImage tag = new BufferedImage((int) widthdist, (int) heightdist, BufferedImage.TYPE_INT_RGB);

            //绘制图像  getScaledInstance表示创建此图像的缩放版本,返回一个新的缩放版本Image,按指定的width,height呈现图像
            //Image.SCALE_SMOOTH,选择图像平滑度比缩放速度具有更高优先级的图像缩放算法。
            tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist, Image.SCALE_SMOOTH), 0, 0, null);

            //创建文件输出流
            out = new FileOutputStream(imgdist);
            //将图片按JPEG压缩,保存到out中
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            encoder.encode(tag);
            //关闭文件输出流
            out.close();
        } catch (Exception ef) {
            ef.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException ioe) {
                throw new RuntimeException(ioe.getMessage());
            }
        }
    }

    /**
     * 获取图片宽度和高度
     *
     * @return 返回图片的宽度
     */
    public static int[] getImgWidthHeight(File file) {
        InputStream is = null;
        BufferedImage src = null;
        int result[] = {0, 0};
        try {
            // 获得文件输入流
            is = new FileInputStream(file);
            // 从流里将图片写入缓冲图片区
            src = ImageIO.read(is);
            result[0] = src.getWidth(null); // 得到源图片宽
            result[1] = src.getHeight(null);// 得到源图片高
            is.close();  //关闭输入流
        } catch (Exception ef) {
            ef.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException ioe) {
                throw new RuntimeException(ioe.getMessage());
            }
        }
        return result;
    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值