Shell 脚本自动将图片生成,Appicons

Xcode 在 MacOS 程式开发设置Appicons 的时候,需要设置多种规格的尺寸,过程比较繁琐。
现只需要一张 1024 x 1024 像素的图片,通过调用本脚本,会实现所有符合规格的尺寸用来设置图标。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/bin/zsh

# 一键PNG图片尺寸生成器
# 用法:./resize.sh input.png

# 检查依赖项
if ! command -v convert &> /dev/null; then
echo "错误:需要安装ImageMagick!"
echo "请使用以下命令安装:"
echo "sudo apt-get install imagemagick # Debian/Ubuntu"
echo "或"
echo "sudo brew install imagemagick # macOS"
exit 1
fi

# 验证输入参数
if [ $# -ne 1 ]; then
echo "用法:$0 <输入文件.png>"
exit 1
fi

input_file="$1"

# 检查文件有效性
if [ ! -f "$input_file" ]; then
echo "错误:文件 '$input_file' 不存在"
exit 1
fi

if ! file "$input_file" | grep -qi "png"; then
echo "错误:文件必须是PNG格式"
exit 1
fi

# 定义目标尺寸数组
sizes=(16x16 32x32 64x64 128x128 256x256 512x512 1024x1024)

# 获取不带扩展名的文件名
filename=$(basename -- "$input_file")
filename="${filename%.*}"

# 创建输出目录
output_dir="./${filename}_resized"
mkdir -p "$output_dir"

# 处理每个尺寸
for size in "${sizes[@]}"; do
output_path="${output_dir}/${filename}_${size}.png"

# 使用ImageMagick进行高质量缩放
convert "$input_file" \
-resize "$size" \
-background none \
-gravity center \
-extent "$size" \
-unsharp 0.5x0.5+0.5+0.008 \
"$output_path"

echo "已生成:$output_path"
done

echo "所有尺寸生成完成!输出目录:$output_dir"

代码用法

sh …/covert_png.sh …/icon.png
生成的目录在 User**_resized

代码解释

为什么使用&>而不是>>

  1. &> 是一个重定向操作符,用于将标准输出(stdout)和标准错误(stderr)同时重定向到同一个目标.
  2. >>,则只能重定向标准输出,而标准错误仍然会显示在终端上.

Shell 脚本自动将图片生成,Appicons
https://jackiedai.github.io/2025/03/18/007unix_shell/Shell_covert_img/
Author
lingXiao
Posted on
March 18, 2025
Licensed under