Setting gravity depending on image size

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?".
Locked
Erik
Posts: 12
Joined: 2016-04-30T00:18:15-07:00
Authentication code: 1151

Setting gravity depending on image size

Post by Erik »

I'd like to set the gravity depending on the size of the image.
I tried fx and set:option, but IM reported errors.

I could solve that problem with additional code, but I would prefer a pure IM solution.
Is there a way to achieve this?

Code: Select all

convert -units PixelsPerInch $infile \
  -background white \
  -gravity WIDTH-AND-HEIGHT-DEPENDENT-GRAVITY-HERE -extent ${wmax2}x${hmax2} +repage \
  $outfile

snibgo
Posts: 13034
Joined: 2010-01-23T23:01:33-07:00
Authentication code: 1151
Location: England, UK

Re: Setting gravity depending on image size

Post by snibgo »

IM doesn't have IF..THEN..ELSE..ENDIF. But we can kludge it, like this (Windows BAT syntax):

Code: Select all

%IMG7%magick ^
  in.png ^
  -set GRAV North ^
  ( +clone ^
    -set GRAV South ^
  ) ^
  -delete %%[fx:w*h^>10000?0:1] ^
  -gravity %%[GRAV] ^
  -background Blue ^
  -extent 200x200 ^
  -verbose +write info: ^
  out.png
We clone the image, and the two images have different values for the attribute "GRAV". We delete either #0 or #1, depending on a function of width and height. (For this example, we delete #0 if the area is greater than 10000 pixels.)

Then we apply the gravity setting.
snibgo's IM pages: im.snibgo.com

User avatar
GeeMack
Posts: 757
Joined: 2015-12-01T22:09:46-07:00
Authentication code: 1151
Location: Central Illinois, USA

Re: Setting gravity depending on image size

Post by GeeMack »

Erik wrote:
2018-03-23T02:31:53-07:00
I'd like to set the gravity depending on the size of the image.
There are at least a couple approaches I can think of to easily create this effect, although not by using "-gravity" and "-extent".

One way would be to use conditional FX expressions to set the page geometry. That would let you use the input dimensions to calculate an output canvas size and the location of the input image within that canvas. Then you can use "-coalesce" to create the finished result.

Another method would be to set the output canvas size with "-set option:distort:viewport ..." and use "-distort affine ..." to adjust the position of the input image within that viewport. That can be done with conditional FX expressions, too.

I'd have to know if "size of the image" means aspect, total area, longest side, etc. I'd also want to know if you only want the image placed north or south, or if you need other gravity/direction adjustments according to some particular criteria. Give us a more detailed description of what sorts of conditions you want to test for and what results you'd like based on those conditions.

Locked