运行在docker环境下的图片压缩小工具

embedded/2024/9/22 18:01:04/

声明

1. 本工具主要针对png、jpg、jpeg格式图片进行压缩,由于png图片的特殊性,压缩过程中会将png转换成jpg再压缩
2. 考虑到jdk环境的问题,所以本工具需要运行在docker容器中,使用时你需要有个docker环境
3. 若符合你的需求,请继续看下面使用步骤


1. 新建maven项目,pom文件中加入

<dependencies><dependency><groupId>net.coobird</groupId><artifactId>thumbnailator</artifactId><version>0.4.8</version></dependency><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.11.0</version></dependency></dependencies><build><finalName>image-compression</finalName><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-shade-plugin</artifactId><version>3.2.4</version><executions><execution><phase>package</phase><goals><goal>shade</goal></goals><configuration><transformers><transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"><mainClass>com.test.img.ImageCompression</mainClass></transformer></transformers></configuration></execution></executions></plugin></plugins></build>

说明:项目依赖了thumbnailatorcommons-io,若获取jar包失败,可尝试将jar下载本地,然后打入本地仓库

2.源码

package com.test.img;import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;import java.util.Scanner;public class ImageCompression {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.println("请输入图片源路径:");String inputDirPath = scanner.nextLine();if (inputDirPath == null || inputDirPath.isEmpty() || inputDirPath.trim().isEmpty()) {System.out.println("输入路径不能为空,请重新输入!");return;}System.out.println("请输入图片输出路径:");String outputDirPath = scanner.nextLine();if (outputDirPath == null || outputDirPath.isEmpty() || outputDirPath.trim().isEmpty()) {System.out.println("输入路径不能为空,请重新输入!");return;}compressImages(inputDirPath, outputDirPath);}public static void compressImages(String inputDirPath, String outputDirPath) {Path inputDir = Paths.get(inputDirPath);Path outputDir = Paths.get(outputDirPath);try {// 创建输出目录Files.createDirectories(outputDir);// 获取输入目录下的所有文件Collection<File> files = FileUtils.listFiles(new File(inputDir.toString()), null, true);ExecutorService executor = Executors.newFixedThreadPool(6); // 根据需要调整线程数for (File file : files) {if (file.isFile() && isImageFile(file.getName()) && isValidFileName(file.getName())) {String relativePath = inputDir.relativize(file.toPath()).toString();String outputPath = outputDir.resolve(relativePath).toString();// 创建输出目录结构Files.createDirectories(Paths.get(outputPath).getParent());// 提交任务到线程池executor.submit(() -> {try {Thumbnails.Builder<File> builder = Thumbnails.of(file).scale(1f).outputQuality(getQuality(file.length()));String extension = FilenameUtils.getExtension(file.getName());if ("png".equals(extension)) {builder.outputFormat("jpg");}builder.toFile(outputPath);} catch (Exception e) {System.err.println("发生错误:" + e.getMessage());e.printStackTrace();}});}}// 关闭线程池executor.shutdown();executor.awaitTermination(1, TimeUnit.HOURS);System.out.println("图片压缩完成!");} catch (IOException | InterruptedException e) {System.err.println("发生错误:" + e.getMessage());e.printStackTrace();}}// 排除掉名称以blob_开头的文件private static boolean isValidFileName(String fileName) {return !fileName.startsWith("blob_");}private static boolean isImageFile(String fileName) {String extension = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();return extension.equals("jpg") || extension.equals("jpeg") || extension.equals("png") || extension.equals("gif");}private static double getQuality(long size) {if (size < 900) {return 0.85;} else if (size < 2047) {return 0.6;} else if (size < 3275) {return 0.44;}return 0.3;}
}

说明:使用时根据实际需要调整源码

3.将项目打成jar包

mvn clean package

4.Dockerfile

# 使用java8镜像作为基础镜像
FROM java:8RUN mkdir /test# 设置工作目录
WORKDIR /testADD /image-compression.jar .VOLUME /test# 设置容器启动命令,这里传递命令行参数
CMD ["java", "-jar", "image-compression.jar", "param1", "param2"]

5.新建copy.bat

@echo off
setlocal:: Step 1: Determine the path to the generated JAR file
set JAR_FILE=target\image-compression.jar
if not exist %JAR_FILE% (echo Error: JAR file not found.exit /b 1
):: Step 2: Create the dest directory if it doesn't exist
echo Creating dest directory...
mkdir dest 2>nul:: Step 3: Copy the JAR file to the dest directory
echo Copying the JAR file to dest directory...
xcopy /F /I /Y "%JAR_FILE%" "dest\":: Step 4: Copy the Dockerfile to the dest directory
echo Copying the Dockerfile to dest directory...
xcopy /F /I /Y "Dockerfile" "dest\"echo Done!
endlocal

6.执行copy.bat

完成后

在这里插入图片描述

7.将生成的dest目录上传至目标服务器,进入dest目录,构建镜像

cd /dest
docker build -t image-compression:v1 .

8.运行容器

docker run -it --rm -v /test/upload/2023/:/2023 -v /test/upload/2023bak/:/2023bak -v /test/upload/2024/:/2024 -v /test/upload/2024bak/:/2024bak --name image-compression image-compression:v1

说明:运行容器时需要执行目录,防止在容器内部找不到目录,程序报错

  • -v 就是为了指定目录挂载,这里将宿主机器的/test/upload/2023映射到容器内的/2023,其它路径挂在同理
  • -it使容器采用交互式运行,--rm会在容器退出后自动删除容器

9.分别输入图片源路径、图片输出路径,将进行压缩,压缩完成后容器自动删除


http://www.ppmy.cn/embedded/115160.html

相关文章

Java律师法律咨询小程序

技术&#xff1a;Java、Springboot、mybatis、Vue、Mysql、微信小程序 1.代码干净整洁&#xff0c;可以快速二次开发和添加新功能 2.亮点可以添加AI法律咨询作为 创新点 系统分&#xff1a;用户小程序端&#xff0c;律师web端和管理员端 用户可以在小程序端登录系统进入首…

解密.bixi、.baxia勒索病毒:如何安全恢复被加密数据

导言 在数字化时代&#xff0c;数据安全已成为个人和企业面临的重大挑战之一。随着网络攻击手段的不断演进&#xff0c;勒索病毒的出现尤为引人关注。其中&#xff0c;.bixi、.baxia勒索病毒是一种新型的恶意软件&#xff0c;它通过加密用户的重要文件&#xff0c;迫使受害者支…

大学生必看!60万人在用的GPT4o大学数学智能体有多牛

❤️作者主页&#xff1a;小虚竹 ❤️作者简介&#xff1a;大家好,我是小虚竹。2022年度博客之星&#x1f3c6;&#xff0c;Java领域优质创作者&#x1f3c6;&#xff0c;CSDN博客专家&#x1f3c6;&#xff0c;华为云享专家&#x1f3c6;&#xff0c;掘金年度人气作者&#x1…

【代码随想录训练营第42期 续Day58打卡 - 图论Part8 - Dijkstra算法

目录 一、Dijkstra算法 实现方式 1、使用优先队列&#xff08;最小堆&#xff09; 2、朴素法&#xff08;简单数组&#xff09; 二、经典例题 题目&#xff1a;卡码网 47. 参加科学大会 题目链接 题解&#xff1a;朴素Dijkstra 三、小结 一、Dijkstra算法 刚入门Dijks…

828华为云征文|华为Flexus云服务器搭建Cloudreve私人网盘

一、华为云 Flexus X 实例&#xff1a;开启高效云服务新篇&#x1f31f; 在云计算的广阔领域中&#xff0c;资源的灵活配置与卓越性能犹如璀璨星辰般闪耀。华为云 Flexus X 实例恰似一颗最为耀眼的新星&#xff0c;将云服务器技术推向了崭新的高度。 华为云 Flexus X 实例基于…

spring boot 定时器配置

1、首先在主类上加EnableScheduling注解 2、在应用类上加Scheduled注解&#xff0c;同时记得添加spring的组件注解Component&#xff0c;不然无法成功

Access denied for user ‘root‘@‘114.254.154.110‘ (using password: YES)

navicat 连接远程服务器报错 1045 - Access denied for user root114.254.154.110 (using password: YES)报错解释&#xff1a; 这个错误表示客户端从IP地址114.254.154.110尝试以用户’root’身份连接到MySQL服务器时&#xff0c;被拒绝访问。原因可能是密码错误、用户’roo…

Rust编写Windows服务

文章目录 Rust编写Windows服务一&#xff1a;Windows服务程序大致原理二&#xff1a;Rust中编写windows服务三&#xff1a;具体实例 Rust编写Windows服务 编写Windows服务可选语言很多, 其中C#最简单。本着练手Rust语言&#xff0c;尝试用Rust编写一个服务。 一&#xff1a;Win…