Replace transparency in PNG image with white background
Asked Answered
S

17

410

I have a PNG image with an alpha channel (i.e. transparency), and I need to create versions with the image layer composed onto a white background. I want to use a scriptable command using a CLI tool such as Image Magick to directly convert PNG to PNG losslessly.

An example of a non-working Image Magick command which results in an error is:

convert input.png -background white -flatten output.png
Sagittal answered 24/2, 2010 at 0:4 Comment(3)
In my specific case the transparency layer in PNG conflicted when going through a (Apache) FO processor to create a PDF/A. PDF/A does not allow transparency. The hack I used is to turn to JPG instead.Apples
"That results in an error." What is the error message?Superabound
That command should work fine. If it does not, then you may have a buggy install of Imagemagick or libpng or your versions of either are too old. What is your version of Imagemagick and libpng?Pathetic
M
311

This works for me:

convert -flatten img1.png img1-white.png

Documentation references:

Michaeline answered 24/2, 2010 at 0:27 Comment(9)
Somehow this doesn't work for me... I tried "-transparent-color white", but got an exception/warning.Arsenate
It turns out that I need to set the -background to white as well. I also had to download the colors.xml, which was missing.Arsenate
Check out my answer below. It was added 2 years after this one.Venerate
may be it doesnst work anymore on 2014? it overwrite the background with the main image oneMacready
On the Mac, open Automator, create a new 'Run Shell Script' action and then add this to it: for f in "$@" do /opt/local/bin/convert -flatten "$f" "$f" done Save this as a service and now you can simply right click on any file(s) to remove alpha.Epidemiology
DO NOT try to convert multi-page documents with -flatten. It will flatten the pages into one page.Engeddi
If you want to do it on all files from your folder you can do it this way: mogrify -flatten *.png just in case, do not forget to do backup. More info here: imagemagick.org/script/mogrify.phpBonny
I tried -flatten in a batch command and all the images got super-imposed into 1 image. Next I tried -background white -alpha remove and it worked, in batch mode.Critter
this does seem to reduce the quality of the image.Ledbetter
V
536
-background white -alpha remove -alpha off

Example:

convert image.png -background white -alpha remove -alpha off white.png

Feel free to replace white with any other color you want. Imagemagick documentation says this about the -alpha remove operation:

This operation is simple and fast, and does the job without needing any extra memory use, or other side effects that may be associated with alternative transparency removal techniques. It is thus the preferred way of removing image transparency.

Venerate answered 8/12, 2011 at 20:53 Comment(15)
may be it doesnt work anymore on 2014? my transparent background png did not merge, it just got overwritten and I lost the background file (I had a backup btw)Macready
I have edited this answer on 2014-09-08. Feel free to try it again.Venerate
Seems that -background white is not needed (it likely is for other colors though).Isonomy
@SkippyleGrandGourou: It is needed, as the transparency fallback color for PNG is not always white.Venerate
How would you change that one-liner to batch-convert all *.png in a given folder?Partook
it is work on I convert pdf to tiff convert file1.pdf -resize 1728x2255 -background white -alpha remove -monochrome -units PixelsPerInch -density 204x196 -compress Fax lsb img2.tiff thank youBarbi
@nuttyaboutnatty Try this: find /your/path -name "*.png" -exec convert {} -background white -alpha remove {}.white.png \;Hamforrd
better than the accepted answer (which in case of more than one layer doesn't do the right thing)Cumulation
@nuttyaboutnatty, you could try the morgrify command (installed with imagemagic: mogrify -background white -alpha remove *.pngRaulrausch
The resulting image will still have an alpha channel. It will be empty but it will still be there. To completely remove the channel add -alpha off.Amhara
Doesn't work. I made a new PNG with a transparent background and a red dot in the middle. Always produced a black background, no matter what color I specified. convert image.png -background white -alpha off white.png produced an image with a black background. convert image.png -background "#00ff33" -alpha off 00ff33.png produced a black backgroundInalterable
As an additional step I ran the "pngcrush" program on the results. This shaved the final file size back down to the same size as the original.Overscrupulous
For available colours see here: imagemagick.org/script/color.phpAviv
Potentially you would like a boder too: -border 7 -bordercolor whiteAviv
@mcnutty I had a similar problem. It seems that (as per the comment from @josch) you need -alpha remove before -alpha off. So your sequence should be convert image.png -background white -alpha remove -alpha off white.png.Sixtynine
M
311

This works for me:

convert -flatten img1.png img1-white.png

Documentation references:

Michaeline answered 24/2, 2010 at 0:27 Comment(9)
Somehow this doesn't work for me... I tried "-transparent-color white", but got an exception/warning.Arsenate
It turns out that I need to set the -background to white as well. I also had to download the colors.xml, which was missing.Arsenate
Check out my answer below. It was added 2 years after this one.Venerate
may be it doesnst work anymore on 2014? it overwrite the background with the main image oneMacready
On the Mac, open Automator, create a new 'Run Shell Script' action and then add this to it: for f in "$@" do /opt/local/bin/convert -flatten "$f" "$f" done Save this as a service and now you can simply right click on any file(s) to remove alpha.Epidemiology
DO NOT try to convert multi-page documents with -flatten. It will flatten the pages into one page.Engeddi
If you want to do it on all files from your folder you can do it this way: mogrify -flatten *.png just in case, do not forget to do backup. More info here: imagemagick.org/script/mogrify.phpBonny
I tried -flatten in a batch command and all the images got super-imposed into 1 image. Next I tried -background white -alpha remove and it worked, in batch mode.Critter
this does seem to reduce the quality of the image.Ledbetter
F
48

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.

$ convert sourceimage.png -background BackgroundColor -flatten destinationimage.png
Fatma answered 6/6, 2011 at 15:13 Comment(1)
For whatever reason, this worked fine for me. Not sure why your original attempt didn't work.Brnaba
C
23

The only one that worked for me was a mix of all the answers:

convert in.png -background white -alpha remove -flatten -alpha off out.png
Chemist answered 16/2, 2015 at 3:51 Comment(3)
Cool, that worked. I actually needed another color than white and you can use ... -background "#010203" ... instead of using white.Dieter
here's how to replace the same image in all folders in a directory mogrify -background white -flatten */*.pngUnderpin
-alpha remove was what did it for meJewish
U
19

here's how to replace the same image in all folders in a directory with white instead of transparent:

mogrify -background white -flatten */*.png

Underpin answered 28/9, 2016 at 4:4 Comment(0)
O
11

Using -flatten made me completely mad because -flatten in combination with mogrify crop and resizing simply doesn't work. The official and for me only correct way is to "remove" the alpha channel.

-alpha remove -alpha off (not needed with JPG)

See documention: http://www.imagemagick.org/Usage/masking/#remove

Overbalance answered 21/4, 2014 at 10:7 Comment(3)
so how would become the command? this did not work here: convert imgWithTranspBkg.png -alpha remove -alpha off bkg.jpg resultImg.pngMacready
I only wanted to remove alpha. Convert to JPG did it, nice and easy. Thanks for the tip.Nihility
This is the only solution of the above that worked for me. Now the iTunes store is happy with my image.Coelom
M
7

The Alpha Remove section of the ImageMagick Usage Guide suggests using the -alpha remove option, e.g.:

convert in.png  -background white  -alpha remove  out.png

...using the -background color of your choosing.

The guide states:

This operation is simple and fast, and does the job without needing any extra memory use, or other side effects that may be associated with alternative transparency removal techniques. It is thus the prefered way of removing image transparency.

It additionally adds the note:

Note that while transparency is 'removed' the alpha channel will remain turned on, but will now be fully-opaque. If you no longer need the alpha channel you can then use Alpha Off to disable it.

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:

convert in.png  -background white  -alpha remove  -alpha off  out.png

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:

However this will not work with "mogrify" or with a sequence of multiple images, basically because the "-flatten" operator is really designed to merge multiple images into a single image.

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.

Maramarabel answered 22/6, 2016 at 16:37 Comment(0)
T
5

It appears that your command is correct so the problem might be due to missing support for PNG (). You can check with convert -list configure or just try the following:

sudo yum install libpng libpng-devel
Tomsk answered 1/7, 2013 at 11:10 Comment(5)
Yes, thanks; this (old) issue was a bug in "graphicks magick", which is a fork/rewrite/whatever of "image magick'.Sagittal
@Sagittal I see! Out of curiosity, what was the actual cause of the issue (that was only in one version)?Tomsk
Well I really don't know exactly; it was just a bug. I'm not a maintainer of Graphicks Magick so I have no insight into their code. I need to try again at some point I guess.Sagittal
ubuntu doesnt have it? here is libpng12-0 but still doesnt work :(Macready
I'm using Ubuntu 13.04 with libpng12-0 installed and working. Can you see png if you run this? convert -list configure | grep \pngTomsk
W
5

This is not exactly the answer to your question, but I found your question while trying to figure out how to remove the alpha channel, so I decided to add this answer here:

If you want to remove alpha channel using imagemagick, you can use this command:

mogrify -alpha off ./*.png
Wheelsman answered 17/4, 2015 at 8:22 Comment(0)
S
3

Welp it looks like my decision to install "graphics magick" over "image magick" has some rough edges - when I reinstall genuine crufty old "image magick", then the above command works perfectly well.

edit, a long time later — One of these days I'll check to see if "graphics magick" has fixed this issue.

Sagittal answered 24/2, 2010 at 0:21 Comment(0)
A
2

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:

find ./ -name "*.png" -exec convert {} -flatten {} \;
Aldebaran answered 12/9, 2018 at 15:52 Comment(0)
I
2

I needed either: both -alpha background and -flatten, or -fill.

I made a new PNG with a transparent background and a red dot in the middle.

convert image.png -background green -alpha off green.png failed: it produced an image with black background

convert image.png -background green -alpha background -flatten green.png produced an image with the correct green background.

Of course, with another file that I renamed image.png, it failed to do anything. For that file, I found that the color of the transparent pixels was "#d5d5d5" so I filled that color with green:

convert image.png -fill green -opaque "#d5d5d5" green.png replaced the transparent pixels with the correct green.

Inalterable answered 17/12, 2018 at 4:48 Comment(1)
the proper command with current ImageMagick would be convert image.png -background green -alpha background -alpha off green.png or convert image.png -background green -alpha background -alpha remove green.png or convert image.png -background green -flatten green.pngPathetic
D
2

Tried all, none worked. This one did:

convert input.png -channel rgba -alpha set \
            -fill none -opaque white \
            -fill white -opaque black \
            -fill white -opaque none \
            -alpha off output.png
Dena answered 21/4, 2022 at 12:29 Comment(0)
M
0

this creates an image just placing the 1st with transparency on top of the 2nd

composite -gravity center ImgWithTransp.png BackgroundSameSizeOfImg.png ResultImg.png

originally found the tip on this post

Macready answered 30/6, 2014 at 18:46 Comment(0)
L
0

To actually remove the alpha channel from the file, use the alpha off option:

convert in.png -background white -alpha off out.png
Lawn answered 9/9, 2014 at 15:41 Comment(1)
Actually, the link you provided says: "It does not actually delete or destory the alpha channel attached to the image, it just turns off any effect that channel has on the image." To really remove the alpha channel, see my answer.Venerate
S
-1

It's -alpha off, NOT -alpha remove! iOS app store upload fails when there is an alpha channel in any icon!!

Here's how to do it: mogrify -alpha off *.png

Steadman answered 13/11, 2018 at 23:54 Comment(0)
C
-1

This does the job for me:

magick convert OLD.png -background white -alpha remove NEW.png

Here is a starter image with a transparent background in case it helps with testing:

image with transparent background

Also, for one-offs on PC, you can always open the PNG file in Windows Paint and click Save. This will automatically turn the transparency to opaque white.

Churchwarden answered 12/2, 2020 at 23:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.