The Computer Oracle

How do I change the canvas size of a PNG with ImageMagick (GraphicsMagick)? (How to pad with transparency?)

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Track title: CC D Schuberts Piano Sonata D 850 in D

--

Chapters
00:00 How Do I Change The Canvas Size Of A Png With Imagemagick (Graphicsmagick)? (How To Pad With Transpa
01:24 Accepted Answer Score 9
01:59 Answer 2 Score 9
02:19 Answer 3 Score 1
02:46 Thank you

--

Full question
https://superuser.com/questions/415892/h...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#images #graphics #imagemagick #graphicsmagick

#avk47



ACCEPTED ANSWER

Score 9


This command will take any sized input file and fit it best to a 40x40 square and pad with transparency:

convert \
   original.png \
  -thumbnail '40x40>' \
  -background transparent \
  -gravity center \
  -extent 40x40 \
  -compose Copy_Opacity \
  -composite mask.png \
   original-resized.png

The gravity option ensures the image is centered in both directions, and transparent is used wherever there are no pixels. Then the compositing is done with the mask.png




ANSWER 2

Score 9


One command to convert all PNGs from one folder:

mogrify \
 -resize 50x50 \
 -background transparent \
 -gravity center \
 -extent 50x50 \
 -format png \
 -path resized \
 *.png

mogrify is a command from ImageMagick package. You have to create output directory first.




ANSWER 3

Score 1


Here's what I eventually went with. A two step process:

gm convert \
  -thumbnail '40x40>' \
  -background transparent \
  -gravity center \
  -extent 40x40 \
   original.png \
   intermediate.png

gm composite \
  -compose in \
   intermediate.png \
   mask.png \
   out.png

Where mask.png is white pixels for what I wanted to keep, and transparent pixels for what I wanted to mask out (discard).