Flatten multiple layers, all centered

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
syl_leroux
Posts: 18
Joined: 2017-04-12T09:05:38-07:00
Authentication code: 1151

Flatten multiple layers, all centered

Post by syl_leroux »

Hi everyone,

I have N layers I would like to flatten in only one image. The layers are of various size and I would like them to be all centered in the final image. And I wasn't able to to find a solution to do that using the `-layers flatten` operator.

Code: Select all

convert 'bkgnd.png' \
           'legal.png' \
           'c2a827c66a5b37625c95626f8b84d07b-parts1.png' \
           # potentially many ofther files here 
           '-gravity' 'center' '-flatten' \
           'c2a827c66a5b37625c95626f8b84d07b.png'
I read in the doc (https://www.imagemagick.org/Usage/layers/#flatten , https://www.imagemagick.org/Usage/compose/#geometry) the `-layers flatten` operator does not use the `-gravity` setting. But that's ideally something equivalent I would like to achieve.

I could use the `-composite` operator instead to merge layers two by two. But the ImageMagick command will be generated by a script and using the `-layers` operator would be somewhat preferable since the filenames would be grouped together, instead of being interleaved with operators.
syl_leroux
Posts: 18
Joined: 2017-04-12T09:05:38-07:00
Authentication code: 1151

Re: Flatten multiple layers, all centered

Post by syl_leroux »

I found a solution using FX escape sequences and `-layers merge`:

Code: Select all

convert 'bkgnd.png' \
           'legal.png' \
           'c2a827c66a5b37625c95626f8b84d07b-parts1.png' \
           -set page '+%[fx:-w/2]+%[fx:-h/2]' \
           '-layers merge' \
           '+repage' \
           'c2a827c66a5b37625c95626f8b84d07b.png'
Let me know if there are other solutions and/or if this can be improved!
snibgo
Posts: 12159
Joined: 2010-01-23T23:01:33-07:00
Authentication code: 1151
Location: England, UK

Re: Flatten multiple layers, all centered

Post by snibgo »

Use "-layers merge", but set the image offsets before that, with "-repage":

Code: Select all

magick logo: toes.png rose: -repage -%[fx:w/2]-%[fx:h/2] +write info: -layers merge +repage out.png
[You beat me to it.]
snibgo's IM pages: im.snibgo.com
syl_leroux
Posts: 18
Joined: 2017-04-12T09:05:38-07:00
Authentication code: 1151

Re: Flatten multiple layers, all centered

Post by syl_leroux »

;)
Thank you @snibgo!
Post Reply