toFrankie / blog

种一棵树,最好的时间是十年前。其次,是现在。
20 stars 1 forks source link

批量图片旋转脚本 #328

Open toFrankie opened 7 months ago

toFrankie commented 7 months ago

之前有一个批量旋转图片的场景,写了个脚本处理。

使用

.
├── source/  # 源文件目录
├── output/  # 处理后产出目录
└── rotate   # 可执行脚本文件

先安装 ImageMagick,接着将要处理的文件放置于 source 目录,双击 rotate 文件执行旋转操作完成后文件存放于 output 目录。

$ brew install imagemagick

实现

rotate 添加执行权限:

$ chmod u+x rotate

扩展名不重要,但为了避免在 Finder 双击打开时,被其他软件默认打开,这里删除扩展名。

获取 rotate 脚本的绝对路径:

$(dirname "$(readlink -f "$0")")

判断是否安装了 ImageMagick,这里用到了它的 convert 命令:

if ! command -v convert &>/dev/null; then
  echo "Error: 'convert' command not found. Please install ImageMagick."
  exit 1
fi

遍历 source 目录,并获取图片文件,并执行旋转操作,比如这里顺时针旋转 90°:convert <source-file> -rotate 90 <output-file>

完整脚本如下:

#!/bin/bash

# 获取脚本或可执行文件的路径
script_path="$(dirname "$(readlink -f "$0")")"

# 检查 convert 工具是否已安装
if ! command -v convert &>/dev/null; then
  echo "Error: 'convert' command not found. Please install ImageMagick."
  exit 1
fi

# 设置源目录和输出目录
source_dir="$script_path/source"
output_dir="$script_path/output"

# 清空输出目录
if [ -d "$output_dir" ]; then
  rm -rf "$output_dir"
fi

# 创建输出目录,如果不存在
mkdir -p "$output_dir"

# 遍历源目录中的图像文件
for file in "$source_dir"/*; do
  # if [ -e "$file" ]; then
  # 提取文件名和扩展名
  file_name=$(basename "$file")
  base_name="${file_name%.*}"
  extension="${file_name##*.}"

  if [ -f "$file" ] && [ -n "$extension" ] && { [ "$extension" = "png" ] || [ "$extension" = "jpg" ] || [ "$extension" = "jpeg" ] || [ "$extension" = "gif" ]; }; then

    # 使用 convert 工具旋转图像并导出到输出目录
    convert "$file" -rotate 90 "$output_dir/$file_name"

    echo "已处理文件: $file_name"
  fi
done

echo "处理完成!"

The end.