Derrick Miller
Derrick Miller

Reputation: 1951

How to add a border to a transparent PNG using ImageMagick, while preserving transparency?

I am trying to add a 10px red border to a transparent PNG using ImageMagick, while preserving any existing transparency that might exist within the image. Here is my source image:

enter image description here

If you download and view that image with an image viewer, you'll see that it has a transparent background.

According to everything I've read, the following Imagemagick command should add a 10px red border to the image:

convert input.png -bordercolor red -border 10 output.png

It actually does add the red border to the image, since the output dimensions are 20px larger in both directions. Unfortunately it also changes the background color of the image to red as well. Here is the output file:

enter image description here

I do not want the transparent area to be changed to red. I only want to add a red border around the transparent image.

I've tried using both ImageMagick version 6.9.10-23 (Ubuntu) and 7.1.0 (via CloudConvert API), with the same result. I've spent hours(!) trying to solve this.

What am I doing wrong?

Upvotes: 2

Views: 1744

Answers (3)

fmw42
fmw42

Reputation: 53071

Here is a simple way to do that in Imagemagick. Change the compose setting from over to copy.

Input:

enter image description here

convert logo_transp.png  -compose copy -bordercolor red -border 10 logo_transp_border.png

enter image description here

Upvotes: 1

Nick Charney Kaye
Nick Charney Kaye

Reputation: 4340

Here's an answer that fully preserves the transparency

convert input.png +write mpr:INP -alpha extract -morphology dilate disk:10 \\( +clone -fill Black -colorize 100 \\) +swap -compose CopyOpacity -composite mpr:INP -compose Over -composite output.png

From https://legacy.imagemagick.org/Usage/crop/#extent

Upvotes: 0

Derrick Miller
Derrick Miller

Reputation: 1951

I found the answer in this thread: https://legacy.imagemagick.org/discourse-server/viewtopic.php?t=31843 . Here are the two money quotes:

So, "-bordercolor red -border 2" should create an opaque red image 2 pixels larger than the input, and composite the input over this. As your input is "-size 100x100 xc:none", the result should be 102x102 opaque red pixels. You might think this is "pretty obviously incorrect", but it is the documented behaviour.

and

Nevertheless, you can get it to work to have the transparent inside, if you add -compose copy before -bordercolor red -border 2 in both the current IM 6 and IM 7. This just may have to be the way to do it from here on, if there is a good reason for the changed behavior.

Here is the command that produces the result I am after:

convert -background transparent -bordercolor red -compose Copy -border 10 input.png output.png

Upvotes: 2

Related Questions