尝试在 PNG 周围添加描边,是否可以改进?

Trying to add a stroke around a PNG, can it be improved?

我正在尝试找到一种向大量 png 文件添加 3px 白色描边的好方法,有效地使它们看起来像 "stickers."我有一些示例代码可以做得很好,但我似乎无法正确裁剪。此外,笔触看起来有点像素化,我想知道是否有可能获得更清晰的边缘!

我进行了大量的互联网搜索,找到了一些示例代码,对其进行了调整,并得出了与我正在寻找的几乎相似的东西。图像总是 PNG 格式,所以我从命令行查看了 inkscape/gimp 之类的东西,但意识到我应该能够只使用终端中的 convert 来做到这一点。

convert in.png \
\( -clone 0 -alpha extract -threshold 0 \) \
\( -clone 1 -blur 10x65000 -threshold 0 \) \
\( -clone 2 -fill red -opaque white \) \
\( -clone 3 -clone 0 -clone 1 -alpha off -compose over -composite \) \
-delete 0,1,3 +swap -alpha off -compose copy_opacity -composite \
out.png

在:

输出:

理想情况下:

你的主要问题是你没有足够的 space 在你的对象和图像的边之间。您只需添加具有透明度的图像,然后再删除多余的部分。

在 ImageMagick 6 中,这应该可以满足您的需求。

1) read the input
2) add a larger border than you need to add
3) extract the alpha channel from the input and dilate it by the amount of border (in this case 10)
4) copy the previous image and color the white as red and the black as transparent
5) composite the original over the red/transparent image
6) delete the original and the red/transparent image
7) swap the composite with the dilated alpha channel and put the dilated alpha channel into the alpha channel of the previous image
8) trim the excess transparency from the border padding
9) save to output

convert img.png \
-bordercolor none -border 20 \
\( -clone 0 -alpha extract -morphology dilate diamond:10 \) \
\( -clone 1 -fuzz 30% -fill red -opaque white -fill none -opaque black \) \
\( -clone 2,0 -compose over -composite \) \
-delete 0,2 \
+swap -alpha off -compose copy_opacity -composite \
-trim +repage \
result.png


对于 ImageMagick 7,将 convert 替换为 magick。

如果在类 Unix 系统上,您可能会对我的 bash ImageMagick 脚本 contour 感兴趣,位于 http://www.fmwconcepts.com/imagemagick/index.php

将diamond:10替换为disk:10

可以获得更好的结果