I've got some PNG images with transparency, and I need to create versions with the image layer composed onto a white background. I've tried various things with Image Magick "convert" operations, but either nothing happens at all or I get an error. I don't want to go to an intermediate JPG form because I don't want the artifacts. Of course it's easy to do this in Gimp or Photoshop or whatever, but I'd really rather script it from the command line because there are many of these things.
An example of a non-working Image Magick command is:
convert img1.png -background white -flatten img1-white.png
That results in an error.
Thanks!
Flattening image and applying background image is straight forward in ImageMagick
However, order of the commands is very important
To apply any background on a transparent image and flatten it, first apply the background than flatten it. The reverse doesn't work.
I saw this question and answers which really help me but then I was needed to do it for a lot of files, So in case you have multiple images (PNG images) in one folder and you want to do it for all:
The Alpha Remove section of the ImageMagick Usage Guide suggests using the
-alpha remove
option, e.g.:...using the
-background
color of your choosing.The guide states:
It additionally adds the note:
Thus, if you do not need the alpha channel you can make your output image size smaller by adding the
-alpha off
option, e.g:There are more details on other, often-used techniques for removing transparency described in the Removing Transparency from Images section.
Included in that section is mention of an important caveat to the usage of
-flatten
as a technique for removing transparency:So, if you are converting several images at once, e.g. generating thumbnails from a PDF file,
-flatten
will not do what you want (it will flatten all images for all pages into one image). On the other hand, using the-alpha remove
technique will still produce multiple images, each one having transparency removed.