ImageMagick extend canvas with transparent background

BackgroundImagemagickPngTransparency

Background Problem Overview


convert input.png -extent 100x100 -gravity center -background white output.png

If the input is 50x50 the surrounding background is white. Can I somehow set this to transparent without declaring any color within input as transparent?

Background Solutions


Solution 1 - Background

Use this instead:

convert               \
      input.png       \
     -background none \
     -gravity center  \
     -extent 100x100  \
      output.png

Note well: The order of the parameters is significant! (To convince yourself, just put -background none at the end of the parameters instead of the start...)


Updated: Thanks to @jesmith who noticed that the commandline I originally provided does no longer work as intended. More recent versions of convert additionally require that the -gravity center is called before -extent 100x100. (This was one of the changes introduced to one ImageMagick's most recent versions [at the time of originally writing this answer]).

Solution 2 - Background

Kurt's note is ironically spot on, order matters greatly. Kurt's command results in gravity not being applied to the extent, so the transparent 'border' will all be to the bottom and/or right of the image.

Moving gravity before extent will correctly create equal transparent 'borders' on all applicable sides.

> convert input.jpg -background none -gravity Center -extent 100x50 > output.png

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTobyView Question on Stackoverflow
Solution 1 - BackgroundKurt PfeifleView Answer on Stackoverflow
Solution 2 - BackgroundeprothroView Answer on Stackoverflow