Linux 下我常用的兩個圖片壓縮工具就是:optipng 和 jpegoptim。
但是今天在谷歌網(wǎng)頁加載測評中,這兩個工具表現(xiàn)不佳。于是使用在線工具來壓縮。
網(wǎng)址:https://tinypng.com
還有個姐妹站,自己百度,壓縮 JPG 格式的圖片。這里以 PNG 格式為例。
申請 API 直接點導(dǎo)航欄那里的開發(fā)者,輸入郵箱名稱即可。

API 申請
收到 API_KEY 之后可以使用 curl 來測試。
curl --user api:YOUR_API_KEY \
--data-binary @unoptimized.png -i https://api.tinify.com/shrink
使用次數(shù)有限制,每個月500張。當然你可以換個郵箱申請什么的,一般來說個人用也不會超過500張的數(shù)量。

使用次數(shù)與收費
只是 curl 還是挺麻煩的,所以寫成腳本來處理吧。
首先新建一個文件,名為 api.key,然后里面填寫收到的 API_KEY。
新建腳本,內(nèi)容如下,放在同一個目錄中。
#!/usr/bin/bash
# 使用 TinyPNG 壓縮圖片
API_KEY=`cat "$(dirname $0)"/api.key`
API_URL=https://api.tinify.com/shrink
# 壓縮后的文件保存在這里
output_dir=
# 要壓縮的文件
files=()
show_help() {
echo -e \
"使用 TinyPNG 壓縮圖片的腳本,默認覆蓋原文件。支持 png 和 jpg 格式。
Usage: $0 [option] [file/directory]...
選項:
-o [輸出目錄] 指定壓縮后的文件保存目錄,默認覆蓋原文件。
-h, --help 顯示幫助信息。
}
# 檢查輸出目錄是否存在,并嘗試創(chuàng)建文件夾。
parse_output_dir() {
if [[ "$1" = '-o' ]]; then
# 確保以 '/' 結(jié)尾
output_dir=${2%/}/
if [[ -e "$output_dir" ]]; then
if [[ ! -d "$output_dir" ]]; then
echo "Error: $output_dir 不是一個目錄。"
exit 1
elif [[ ! -w "$output_dir" ]]; then
echo "Error: $output_dir 目錄不可寫"
exit 1
fi
else
mkdir "$output_dir" || exit 1
fi
fi
}
# 索引文件和目錄,放進數(shù)組中等待處理。如果文件或者目錄不存在則退出。
parse_files() {
start=0
if [[ -n "$output_dir" ]]; then
start=2
fi
args=("$@")
for (( i = $start; i <= $#; i++ )); do
path=${args[$i]}
if [[ -f "$path" ]]; then
files+=($path)
elif [[ -d "$path" ]]; then
for file in "`find \"$path\" -type f -regex '.*\.\(png\|jpg\)'`"; do
if [[ -n "$file" ]]; then
files+=("$file")
fi
done
fi
done
}
# 逐一處理圖片
minify_image() {
local file=$1
local response=`curl $API_URL -s --user api:$API_KEY --data-binary @"$file"`
if [[ "$response" = *"\"error\""* ]]; then
message=`echo "$response" | sed 's#.*"message":"\([^"]*\)".*#\1#'`
if [[ -n "$message" ]]; then
echo "$file: $message"
else
echo "$file: $response"
fi
else
local url=`echo "$response" | sed 's#.*"url":"\([^"]*\)".*#\1#'`
if [[ -n "$output_dir" ]]; then
local output_path="$output_dir$file"
local dir=`dirname $output_path`
if [[ ! -d "$dir" ]]; then
mkdir -p "$dir"
fi
else
local output_path=$file
fi
curl $url -sSo "$output_path" --user api:$API_KEY
if [[ "$?" = "0" ]]; then
echo "$file: 壓縮成功"
else
echo "$file: 下載失敗"
fi
fi
}
if [[ "$#" = "0" || "$1" = "--help" || "$1" = "-h" ]]; then
show_help
exit
elif [[ -e "$API_KEY" ]]; then
echo "請保證 api.key 位置與內(nèi)容正。"
fi
parse_output_dir $@
parse_files $@
export API_KEY
export API_URL
export output_dir
export -f minify_image
if [[ "${#files[@]}" -lt "1" ]]; then
echo "沒有文件需要壓縮"
else
echo ${files[@]} | xargs -r -n1 -P10 bash -c 'minify_image "$@"' _{}
fi
源代碼來自:
https://github.com/bianjp/image-minifier/blob/master/minify.sh