Page 1 of 1

Setting gravity depending on image size

Posted: 2018-03-23T02:31:53-07:00
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

Re: Setting gravity depending on image size

Posted: 2018-03-23T04:01:01-07:00
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.

Re: Setting gravity depending on image size

Posted: 2018-03-23T08:15:59-07:00
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.