27

开源一段 Mac 批量压缩图片的脚本

 4 years ago
source link: https://www.kymjs.com/note/2020/03/17/01/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

近日处理了一批照片,现在分享一下如何在mac平台进行图片批量处理。

0、安装 xCode 命令行工具,需要确定电脑上已经安装了 xCode,如果没有,自己去 AppStore 里面搜索就看到了。

打开终端,输入命令:

xcode-select --install

如果看到如下提示,表示已经安装了

xcode-select: error: command line tools are already installed, use "Software Update" to install updates

1、安装brew:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

2、使用 brew 安装 imagemagick

brew install imagemagick

3、 去桌面新建一个 zip.sh 的文件,里面写入

#!/bin/bash
# 查找目录及子目录的图片文件(jpg,gif,png),将大于某值的图片进行压缩处理
# Config
folderPath=$1   # 图片目录路径

maxSize='200'    # 图片尺寸允许值
maxWidth=600   # 图片最大宽度
maxHeight=500  # 图片最大高度
quality=60      # 图片质量


# 压缩处理
# Param $folderPath 图片目录
function compress(){

    folderPath=$1

    if [ -d "$folderPath" ]; then

        for file in $(find "$folderPath" \( -name "*.jpg" -or -name "*.jpeg" -or -name "*.gif" -or -name "*.png" \) -type f -size +"$maxSize" ); do

            echo $file

            # 调用imagemagick resize图片
            $(convert -resize "$maxWidth"x"$maxHeight" "$file" -quality "$quality" -colorspace sRGB "$file")

        done

    else
        echo "$folderPath 不存在"
    fi
}

# 执行compress
compress "$folderPath"

exit 0

4、 给脚本执行权限

cd ~/Desktop

chmod a+x  zip.sh

5、 可以压缩图片了,下面命令的path替换成你要压缩的图片文件夹路径

cd ~/Desktop
./zip.sh  path

了解更多有深度技术的文章,与移动端、大前端未来方向的认知, 前往订阅 开源实验室小专栏。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK