Swift 命令行工具 使用Optipng、imagemagick压缩图片

    首先应该做的是安装homebrew。因为Optipng和imagemagick 都是通过homebrew安装的,所以要先安装homebrew。


1. 使用Optipng压缩图片

      //安装optipng
      print("\n安装optipng")
      let task = Process()
      task.launchPath = "/usr/local/bin/brew"
      task.arguments = ["install", "optipng"]
      task.launch()
      task.waitUntilExit()

      //压缩图片
      print("\n\n开始压缩图片")
      sleep(2)
      //获取所有图片路径
      let imageNames = FileHelper.shared.subpaths(atPath: folderPatch, ofType: "png")

      imageNames.forEach({
          let path = folderPatch + "/" + $0
          let compressProcess = Process()
          compressProcess.launchPath = "/usr/local/bin/optipng"
          compressProcess.arguments = ["-o7", "-strip all", path]
          compressProcess.launch()
          compressProcess.waitUntilExit()
      })


2. 使用imagemagick压缩图片

//安装imagemagick
print("\n安装imagemagick")
let task = Process()
task.launchPath = "/usr/local/bin/brew"
task.arguments = ["install", "imagemagick"]
task.launch()
task.waitUntilExit()

//创建压缩脚本字符串,将图片路径的MD5值输出到txtFilePath文件中
let bashString = """
#! /bin/bash
function compress(){
#读取 文件的所有图片字符串
path="${2}"
str=$(cat $path)

for name in $(find $1 -iname "*.png"); do
if [[ ! $str =~ $name ]]
then
echo "开始压缩图片"
/usr/local/bin/mogrify -strip +profile "*" -quality 75 $name $name
echo `/sbin/md5 -q $name` >> $path
fi
done
}
compress $1 $2
"""

//folderPatch为项目目录,创建脚本临时文件、图片名MD5值临时文件
let shFilePath = folderPatch + "/imgCompress.sh"
let txtFilePath = folderPatch + "/imagePath.txt"

//读取配置信息,配置信息中有图片的MD5值则不再进行压缩。
let config = ConfigManager()
var imagePathString = config.getConfigImagePathFile(name: projectName)
FileManager.default.createFile(atPath: txtFilePath, contents: imagePathString.data(using: .utf8), attributes: nil)
FileManager.default.createFile(atPath: shFilePath, contents: bashString.data(using: .utf8), attributes: nil)

//创建任务 执行脚本文件。传入脚本文件、项目文件、图片MD5值文件路径
let compressProcess = Process()
compressProcess.launchPath = "/bin/bash"
compressProcess.arguments = [shFilePath, folderPatch, txtFilePath]
compressProcess.launch()
compressProcess.waitUntilExit()

//获取txtFilePath中图片路径的所有MD5值,保存到配置文件中
imagePathString = try! String(contentsOfFile: txtFilePath, encoding: .utf8)
_ = config.changeConfig(withProjectName: projectName, key: ConfigKey.imagePathFile.rawValue, value: imagePathString )

//删除临时文件
try? FileManager.default.removeItem(atPath: shFilePath)
try? FileManager.default.removeItem(atPath: txtFilePath)

你可能感兴趣的:(Swift 命令行工具 使用Optipng、imagemagick压缩图片)