????首先應該做的是安裝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()
//創(chuàng)建壓縮腳本字符串,將圖片路徑的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為項目目錄,創(chuàng)建腳本臨時文件、圖片名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)
//創(chuàng)建任務 執(zhí)行腳本文件。傳入腳本文件、項目文件、圖片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)
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。