ImageMagick压缩图片

ImageMagic的官网链接为:https://www.imagemagick.org/.
更新于:2021-06-10

操作方式

转换为webp

1
2
3
4
# 简单
magick 1.jpg -quality 85% 1.webp
# 更高压缩,裁剪等
magick 1.jpg -resize 80% -strip -interlace Plane -sampling-factor 4:2:0 -quality 85% -layers Optimize 1.webp

这里的抽样参数有两种:

  • -sampling-factor 4:2:0 推荐
  • -gaussian-blur 0.05 进行blur,比sampling的压缩效果要好,但是清晰度会比较差

对比的解释参见:https://stackoverflow.com/questions/7261855/recommendation-for-compressing-jpg-files-with-imagemagick

If you dislike blurring, use -sampling-factor 4:2:0 instead. What this does is reduce the chroma channel’s resolution to half, without messing with the luminance resolution that your eyes latch onto. If you want better fidelity in the conversion, you can get a slight improvement without an increase in filesize by specifying -define jpeg:dct-method=float - that is, use the more accurate floating point discrete cosine transform, rather than the default fast integer version.

转换为avif

avif的转换不能用-quality 85%来控制,否则体积会很大

1
2
3
4
# 简单
magick 1.jpg 1.avif
# 更高压缩
magick 1.jpg -resize 80% -strip -interlace Plane -sampling-factor 4:2:0 -layers Optimize 1.avif

如果是gif

需要注意的是:
ImageMagick会对帧进行优化,但是如果原始gif的每一帧的图片质量太差,会导致ImageMagick难以对重复帧进行复用,这样压缩率就会很低。
因此,在制作GIF的时候,尽量设置为最高质量.

目前webp和avif都支持动图展现,chrome对两者是完美支持。
其他浏览器、微信公众号、移动端浏览器等对于avif的支持度并不是很好。建议优先使用webp

如何安装ImageMagic

mac

可参考官网链接:https://imagemagick.org/script/download.php

1
2
brew install ghostscript
brew install imagemagick

HomeBrew的加速参考Brew

Linux

CentOs/RedHat用户参考官网。
Debian/Ubuntu用户:
你需要首先安装基础包,参考Linux初始化
再参照官网的make流程。
注意,在configure

1
2
3
4
./configure --with-modules --with-gslib --with-rsvg  --with-perl
make
sudo make install
sudo ldconfig /usr/local/lib

,记得检查Delegate,Value后面是no的,你将无法处理对应的图片格式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
                  Option                        Value
------------------------------------------------------------------------------
Delegate library configuration:
BZLIB --with-bzlib=yes yes
Autotrace --with-autotrace=no no
DJVU --with-djvu=yes yes
DPS --with-dps=yes no
FFTW --with-fftw=no no
FLIF --with-flif=yes no
FlashPIX --with-fpx=yes no
FontConfig --with-fontconfig=yes yes
FreeType --with-freetype=yes yes
Ghostscript lib --with-gslib=no no
Graphviz --with-gvc=yes yes
HEIC --with-heic=yes yes
JBIG --with-jbig=yes yes
JPEG v1 --with-jpeg=yes yes
JPEG XL --with-jxl=no no
LCMS --with-lcms=yes yes
LQR --with-lqr=yes yes
LTDL --with-ltdl=yes yes
LZMA --with-lzma=yes yes
Magick++ --with-magick-plus-plus=yes yes
OpenEXR --with-openexr=yes yes
OpenJP2 --with-openjp2=yes yes
PANGO --with-pango=yes yes
PERL --with-perl=no no
PNG --with-png=yes yes
RAQM --with-raqm=yes yes
RAW --with-raw=yes yes
RSVG --with-rsvg=no no
TIFF --with-tiff=yes yes
WEBP --with-webp=yes yes
WMF --with-wmf=yes yes
X11 --with-x= yes
XML --with-xml=yes yes
ZIP --with-zip=yes yes
ZLIB --with-zlib=yes yes
ZSTD --with-zstd=yes yes