XiaO

PNG 与 JPG 的压缩与存储

XiaO / 2021-12-29


个人原则,能矢量化的图形,则选用矢量格式;无法矢量化,则:

PNG 压缩

pngquant

免费开源的无损压缩工具:pngquant,专注 PNG 格式,压缩率不错。

brew install pngquant

pngquant input.png --quality 100 --force --strip --skip-if-larger --ext _mini.png

# 参数说明
--quality 0~100 控制压缩质量,100 则是无损压缩
--force 目标文件存在时,覆盖之
--strip 去除 meta 信息
--skip-if-larger 压缩后文件大于原始文件,则跳过
--ext 输出文件的后缀名,可用 _new.png 的方式防止原始文件被覆盖

Automator 设置快捷批量处理:

  1. 启动 Automator (CMD + SPACE, “automator”, 回车)
  2. 文件 启动AutomatorFile -> New, 选择 Select “Service”.
  3. 在左侧搜索栏中搜索并选中 “run shell script”, 将其拖入右侧区域.
  4. 并作如下设置:
    1. “Service receives selected” = “image files”
    2. “in” = “finder”
    3. “Shell” = “/bin/zsh/”
    4. “Pass input” = “as arguments”
  5. 将以下代码粘贴到 “run shell script” 的文本框中(删除预置的示例代码):
export PATH=/usr/local/bin:$PATH

for f in "$@"
do
    file=$(basename $f)
    file_extension=${file##*.}
    if [ ${file_extension} = "png" ]; then
  	  pngquant $f --quality 100 --force --strip --skip-if-larger --ext _mini.png
  	else
	  osascript -e 'display notification "This is NOT a PNG file!" with title "pngquant"'
	  afplay /System/Library/Sounds/Submarine.aiff
    fi
done

JPG 压缩与存储

对于 jpg 格式而言,个人并没有找到比较理想的压缩处理工具。其实这里面主要考虑的有如下几个因素;

当然,以上几个要素之间,只能寻得一个平衡,并没有绝对的优解。所以,且试且看吧。

ImageOptim

ImageOptim 是一款免费开源软件。相比较于 ImageAlpha、pngquant、TinyPNG、JPEGMini、MozJPEG 等默认有损压缩来一定程度缩小文件,ImageOptim 则默认采用无损压缩模式,这也使得 ImageOptim 压缩后的文件相对大一些。如果需要,ImageOptim 也可在选项中直接设置压缩的比率。

brew install --cask imageoptim

另外,可安装非官方 imageoptim-cli 终端工具,进而实现在终端对 ImageOptim 的调用。

# 安装
brew install imageoptim-cli

# 查看帮助
imageoptim -h 

Lepton

Lepton 可将 JPG 格式照片压缩为 LEP 格式文件,文件体积可减少 20% 以上,适合不常打开的照片的存储。当需要查看的时候,需再次使用 Lepton 对其解码。解码后的文件,除日期与原始文件不同外,其它的 meta 信息与源文件一致。

故而,个人做法是将照片以拍摄时间命名并压缩为 LEP 格式进行存储。这样做的好处是可以记录拍摄时间,同时,在需要解码的时候,可以直接通过名称大致找到需要的文件。

brew install lepton

Usage: lepton [switches] input_file [output_file]

Automator 设置快捷批量处理:

export PATH=/usr/local/bin:$PATH

for f in "$@"
do
  file=$(basename $f)
  file_extension=${file##*.}
  if [ ${file_extension} = "jpg" -o ${file_extension} = "JPG" -o ${file_extension} = "JPEG" -o ${file_extension} = "jpeg" -o ${file_extension} = "lep" ]; then
  	lepton $f
	osascript -e 'display notification "Compress complete!" with title "lepton"'
  else
	osascript -e 'display notification "This is NOT a JPG or LEP file!" with title "lepton"'
	afplay /System/Library/Sounds/Submarine.aiff
  fi
done