批量压缩图片为Webp

批量压缩图片为Webp

博客建站过程中,为了使图片加载更加顺畅和丝滑,我们通常会进行图片的批量压缩,传统的 ImageOptim 、TinyPNG等工具往往不能压缩的到一个比较极致的尺寸。转换格式并压缩成webp成了一个更好的选择。

为了做到这一点,我将所有图片从以前的 png、jpg、gif 格式转换为谷歌的 WebP 格式。我使用的是 cwebp 命令行工具。

Webp

cwebp

安装 cwebp

1
brew install webp

使用 cwebp

1
cwebp [options] input_file -o output_file.webp

常用的参数

  • -q float
    在 0 和 100 之间指定 RGB 通道的压缩系数。默认值为 75。

  • -lossless
    对图像进行编码,没有任何损失。

1
cwebp -lossless  infile.webp
  • -resize width height

对图像进行调整尺寸编码编码

1
cwebp -resize 800 0 infile.webp

这将 webp 文件的最大宽度调整为 800,0 表示 “保持高度的宽高比”。

更多示范

1
2
3
4
cwebp -q 50 -lossless picture.png -o picture_lossless.webp
cwebp -q 70 picture_with_alpha.png -o picture_with_alpha.webp
cwebp -sns 70 -f 50 -size 60000 picture.png -o picture.webp
cwebp -o picture.webp -- ---picture.png

更多命令参考文档

gif2webp

使用 gif2webp

1
gif2webp [options] input_file.gif -o output_file.webp

常用的参数

  • -lossy
    使用有损压缩对图像进行编码。

  • -mixed
    混合压缩模式:通过启发式地为每个帧选择有损压缩或无损压缩来优化图像压缩。

  • -min_size
    编码图像以实现最小尺寸。这将禁用关键帧插入,并选择处理方法,使每一帧的输出都最小。它默认使用无损压缩,但可与 -q 、 -m 和 -q 结合使用。, -m、 -lossy 或 -mixed 选项结合使用。

  • -f
    仅用于有损编码(由 -lossy 选项指定)。在 0 (无过滤)和 100 之间指定解锁过滤器的强度。(无过滤)和 100 之间(最大过滤)。(最大过滤强度)之间。 0 值将关闭任何过滤功能。数值越大,解码后应用的滤波处理强度越高。数值越大,图像越平滑。典型值通常在 20 到 50 之间。.

更多示范

1
2
3
4
5
6
gif2webp picture.gif -o picture.webp
gif2webp -q 70 picture.gif -o picture.webp
gif2webp -lossy -m 3 picture.gif -o picture_lossy.webp
gif2webp -lossy -f 50 picture.gif -o picture.webp
gif2webp -min_size -q 30 -o picture.webp -- ---picture.gif
cat picture.gif | gif2webp -o - -- - > output.webp

更多命令参考文档

批量压缩

cd 到图片的文件夹,执行以下命令。
命令会匹配文件格式image/png/gif,同名输出webp文件。

有损压缩

压缩编码调整,可以自己根据需要进行修改

  • jpeg/png,宽度最大 1920,保持保持高度的宽高比
  • gif 保留 50的质量
1
2
3
4
5
6
7
8
9
10
11
find . -type f -exec bash -c '
for x; do
case "$(file -b --mime-type "$x")" in
image/jpeg) cwebp -resize 1920 0 -mt "$x" -o "${x%.*}.webp" ;;
image/png) cwebp -resize 1920 0 -mt "$x" -o "${x%.*}.webp" ;;
image/gif) gif2webp -lossy -f 50 -mt "$x" -o "${x%.*}.webp" ;;
*) echo "Unsupported format: $x" ;;
esac
done
' bash {} +

无损压缩

1
2
3
4
5
6
7
8
9
10
find . -type f -exec bash -c '
for x; do
case "$(file -b --mime-type "$x")" in
image/jpeg) cwebp -q 75 -jpeg_like -mt "$x" -o "${x%.*}.webp" ;;
image/png) cwebp -lossless -mt "$x" -o "${x%.*}.webp" ;;
image/gif) gif2webp -mt "$x" -o "${x%.*}.webp" ;;
*) echo "Unsupported format: $x" ;;
esac
done
' bash {} +