700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > java 图片等比例压缩工具

java 图片等比例压缩工具

时间:2024-03-31 00:30:19

相关推荐

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);// 构造一个类型为预定义图像类型之一的 BufferedImageBufferedImage 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;}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。