AppleScript快速批量压缩图片大小及调整尺寸
如何实现对图片进行压缩以减少文件大小,同时保持一定的清晰度。有时,还需要将图片调整为指定的尺寸(例如长边固定为 3000 像素)。在 macOS 系统中,可通过macOS 自带的 sips
工具,对图片进行批量压缩和调整(包括尺寸和质量)
代码实现
以下是完整的 AppleScript 代码。通过此脚本,用户可以选择图片文件并进行压缩,同时可根据需要调整图片尺寸(M2 芯片测试通过)。可手动提高压缩比,修改set compressionQuality to 0.6 – 60% 质量。
set imageFiles to choose file with prompt ¬
"请选择要压缩的图片:" of type {"public.image"} with multiple selections allowed
set outputFolder to choose folder with prompt "请选择保存压缩图片的文件夹:"
set outputFolderPOSIX to POSIX path of outputFolder
-- 压缩比例,100 是原始质量,越低越压缩,可以手动修改
set compressionQuality to 0.6 -- 60% 质量
set shouldResize to false
display dialog "是否需要修改最长边的尺寸?" buttons {"否", "是"} default button "否"
if button returned of result is "是" then
set shouldResize to true
set longestSideSize to text returned of (display dialog "请输入最长边的尺寸:" default answer "3000")
set longestSideSize to longestSideSize as integer
end if
repeat with anImage in imageFiles
set imagePath to POSIX path of anImage
set imageName to name of (info for anImage)
set outputImagePath to outputFolderPOSIX & imageName
try
if shouldResize then
do shell script "sips -Z " & longestSideSize & " --setProperty formatOptions " & (compressionQuality * 100 as integer) & " " & quoted form of imagePath & " --out " & quoted form of outputImagePath
else
do shell script "sips --setProperty formatOptions " & (compressionQuality * 100 as integer) & " " & quoted form of imagePath & " --out " & quoted form of outputImagePath
end if
on error errMsg
display dialog "压缩图片时出错:" & errMsg buttons {"OK"} default button "OK"
end try
end repeat
display dialog "图片压缩完成!" buttons {"OK"} default button "OK"