Crop to fill on a canvas with different aspect ratio

Questions and postings pertaining to the usage of ImageMagick regardless of the interface. This includes the command-line utilities, as well as the C and C++ APIs. Usage questions are like "How do I use ImageMagick to create drop shadows?".
Post Reply
holden
Posts: 79
Joined: 2013-02-07T08:22:57-07:00
Authentication code: 6789

Crop to fill on a canvas with different aspect ratio

Post by holden »

I've been struggling to find a nice simple way to do this- IM will fit an image onto a canvas of a different aspect ratio leaving white space, which is something I need to do at certain times, but I also need to do this: http://www.pasteall.org/pic/54347
I just can't find a non-hacky or consistent way to do it- I feel as though I am missing a powerful command somewhere. The image needs to be centered on the canvas as I tried to show in the link. Thanks
snibgo
Posts: 12159
Joined: 2010-01-23T23:01:33-07:00
Authentication code: 1151
Location: England, UK

Re: Crop to fill on a canvas with different aspect ratio

Post by snibgo »

Suppose the target width is %W% and the target height is %H%. This (Windows) script does what I think you want:

Code: Select all

convert in.png ^
  -resize "%W%x%H%^^" ^
  -gravity Center ^
  -crop %W%x%H%+0+0 ^
  out.png
snibgo's IM pages: im.snibgo.com
holden
Posts: 79
Joined: 2013-02-07T08:22:57-07:00
Authentication code: 6789

Re: Crop to fill on a canvas with different aspect ratio

Post by holden »

Creating my diagram got me thinking- so far this seems to work also:

Code: Select all

-size 2100x1500 xc:white ( foo.jpg -resize 2100x -gravity center +repage ) -composite out.jpg
Does this look like a proper solution? (Pixel sizes are just an example)
User avatar
fmw42
Posts: 25562
Joined: 2007-07-02T17:14:51-07:00
Authentication code: 1152
Location: Sunnyvale, California, USA

Re: Crop to fill on a canvas with different aspect ratio

Post by fmw42 »

-size 2100x1500 xc:white ( foo.jpg -resize 2100x -gravity center +repage ) -composite out.jpg
I would put the -gravity outside the parens and I don't think you need +repage, especially since jpg does not support virtual canvas and resize does not create one.

convert -size 2100x1500 xc:white ( foo.jpg -resize 2100x ) -gravity center -composite out.jpg
snibgo
Posts: 12159
Joined: 2010-01-23T23:01:33-07:00
Authentication code: 1151
Location: England, UK

Re: Crop to fill on a canvas with different aspect ratio

Post by snibgo »

Yup, that seems to do the same thing. Loads of ways to skin a cat.

(I should probably have had "+repage" before out.png.)
snibgo's IM pages: im.snibgo.com
Post Reply