rostok
rostok

Reputation: 2137

Is it possible to trim an image and force its dimensions to be even with ImageMagick?

Is it possible to trim image (say PNG with alpha) with command line version of ImageMagick in such a way that both width and height of output image will be even (not odd)?

To be precise, the output image should be first trimmed and then padded with transparent pixels. I need this for sprite sheet packing so after all necessary operations I would like to access stored 'Page geometry' or 'Origin geometry' (also avaiable as %[fx:page.x] %[fx:page.y] format variables).

I understand this can be achieved with extensive shell/batch scripting but frankly I am looking for smart one-liner.

Upvotes: 4

Views: 680

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207465

Updated Answer

It seems you want the image padded, rather than trimmed or resized, so you can do that using -extent as you say in the comments:

convert image.png -background orange -extent  $(convert image.png -format '%[fx:2*int((w+1)/2)]x%[fx:2*int((h+1)/2)]!' info:) result.png

If you would like the image padded with transparent pixels, instead of my rather stylish orange ones (!), change orange to none.

As the default -gravity is NorthWest, this will pad to the right and bottom. If you would like to pad to the left and top, for example, use -gravity SouthEast before the -extent.


Original Answer

Untested, but should work...

This will get you the new dimensions:

convert image.png -format '%[fx:2*int((w+1)/2)]x%[fx:2*int((h+1)/2)]!' info:

So you need to do:

convert image.png -resize $(COMMAND ABOVE) result.png

Upvotes: 2

Related Questions