Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to square an image and pad with transparency from the commandline (imagemagick)

Tags:

imagemagick

The section entitled Square Padding or Cropping describes a method to generate a square image--for a file whose dimensions are unknown--and pad the background with a color.

How do I perform the same operation, but create a transparent background.

like image 203
bwv549 Avatar asked Jul 30 '15 01:07

bwv549


People also ask

How to resize an image with ImageMagick?

To resize an image to specific dimensions, use the convert command with an input file, the -resize parameter, your preferred dimensions, and an output filename: convert original. png -resize 100x100 new.

How do you crop on ImageMagick?

To crop an image using ImageMagick, you need to specify the X and Y coordinates of the top corner of the crop rectangle and the width and height of the crop rectangle. Use the mogrify command if you want the images to be replaced in-place or use the convert command otherwise to make a copy.

Is ImageMagick open source?

ImageMagick, invoked from the command line as magick , is a free and open-source cross-platform software suite for displaying, creating, converting, modifying, and editing raster images. Created in 1987 by John Cristy, it can read and write over 200 image file formats. It is widely used in open-source applications.


2 Answers

Let's make a red off-square image first, that is 300x200:

convert -size 300x200 xc:red image.png

enter image description here

Now let's put make a square image of it, but using a yellow background so you can see it:

convert -background yellow -gravity center image.png -resize 400x400 -extent 400x400 result.png

enter image description here

Now we can do the same thing again, but make the background transparent:

convert -background none -gravity center image.png -resize 400x400 -extent 400x400 result.png

enter image description here

and, just check to make sure it has worked:

identify result.png
result.png PNG 400x400 400x400+0+0 8-bit sRGB 418B 0.000u 0:00.000
like image 175
Mark Setchell Avatar answered Oct 14 '22 02:10

Mark Setchell


These modified methods from Anthony's examples both work for me:

  convert thumbnail.gif \
      \( +clone -rotate 90 +clone -mosaic +level-colors grey -transparent grey \) \
      +swap -gravity center -composite    square_padded.gif

convert thumbnail.gif  -virtual-pixel none -set option:distort:viewport \
 "%[fx:max(w,h)]x%[fx:max(w,h)]-%[fx:max((h-w)/2,0)]-%[fx:max((w-h)/2,0)]" \
 -filter point -distort SRT 0  +repage  square_external.gif
like image 40
Bonzo Avatar answered Oct 14 '22 01:10

Bonzo