Last active
April 23, 2023 12:43
-
-
Save Doradx/a1c4b502958895a281e5770ed8dc14f1 to your computer and use it in GitHub Desktop.
A shell script to batch compress all images under a folder, based on ImageMagick.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
### | |
# @Author: Dorad, ddxi@qq.com | |
# @Date: 2023-04-22 00:04:43 +02:00 | |
# @LastEditors: Dorad, ddxi@qq.com | |
# @LastEditTime: 2023-04-22 00:18:13 +02:00 | |
# @FilePath: \compress.sh | |
# @Description: | |
# | |
# Copyright (c) 2023 by Dorad (ddxi@qq.com), All Rights Reserved. | |
### | |
# 输入文件夹路径和输出文件夹路径 | |
# 获取输入参数 | |
if [ $# -lt 2 ]; then | |
echo "Usage: $0 input_dir output_dir <quality%>" | |
exit 1 | |
fi | |
if [ ! -d "$1" ]; then | |
echo "Input dir $1 not exists" | |
exit 1 | |
fi | |
input_dir=$1 | |
output_dir=$2 | |
# 压缩后的图片质量百分比, 默认为 80 | |
if [ -z "$3" ]; then | |
quality=80 | |
else | |
quality=$3 | |
fi | |
# 检查convert命令是否存在 | |
if ! command -v convert &>/dev/null; then | |
echo "convert command not found, please install ImageMagick first" | |
exit 1 | |
fi | |
# 遍历输入文件夹下所有图片文件 | |
find $input_dir -type f -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.png' -o -iname '*.gif' | while read file; do | |
# 创建输出文件夹的相同目录结构 | |
relative_path=${file#"$input_dir"} | |
output_file="$output_dir/$relative_path" | |
echo "Output file: $output_file" | |
# 创建输出文件夹 | |
mkdir -p "${output_file%/*}" | |
# 压缩图片并输出到相应的文件夹下 | |
convert "$file" -quality $quality "$output_file" | |
echo "Compress $file, output to $output_dir/$file" | |
done | |
echo "Total files: $(find $input_dir -type f -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.png' -o -iname '*.gif' | wc -l)" | |
echo "Compressed files: $(find $output_dir -type f -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.png' -o -iname '*.gif' | wc -l)" | |
echo "Done!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment