如何以有效的方式 trim 从我的图像中添加透明边框?

How do I trim transparent borders from my image in an efficient way?

我想使用 Node.js 自动化修剪 PNG 图像透明边缘的过程,而是使用 CLI 工具(由 child_process 调用)或具有本机绑定的 Node 模块出于性能原因的纯 JavaScript 实现。

这听起来像是一项相当简单的任务,但我搜索了数周都没有找到符合我需要的结果。

我目前使用的 Sharp and GraphicsMagick for a complex chain of image manipulations, but because I didn't find a tool for transparency trimming, I wrote a custom Jimp 插件以相当低效的方式处理修剪作业,但它仍然有效。

这是一个示例输入图像:

以及预期的输出图像:

不过我想摆脱 Jimp。

libvips, the image processing library used by sharp, has find_trim

在您的情况下,您只想测试 alpha 通道(波段 3),因此提取它并搜索 non-zero 值的边界框:

$ vips extract_band test-transparency.png x.png 3
$ vips find_trim x.png --background 0 --threshold 20
0
0
722
639

这就是您想要的区域 left/top/width/height。您可以使用以下方法从原始图像中裁剪掉它:

$ vips crop test-transparency.png y.png 0 0 722 639

制作:

您可以将其作为 one-liner 使用:

$ vips crop test-transparency.png y.png $(vips extract_band test-transparency.png x.png 3; vips find_trim x.png --background 0 --threshold 20)

您可以在 Python 中提高效率:

#!/usr/bin/python3

import sys
import pyvips

image = pyvips.Image.new_from_file(sys.argv[1])
left, top, width, height = image[3].find_trim(background=0, threshold=20)
image = image.crop(left, top, width, height)
image.write_to_file(sys.argv[2])

并且 shell 到此为止。当然,你可能不想添加 py 作为依赖项。