Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove transparency/alpha from any image using PIL

Tags:

How do I replace the alpha channel of any image (png, jpg, rgb, rbga) with specified background color? It must also work with images that do not have an alpha channel.

like image 445
Humphrey Avatar asked Mar 08 '16 04:03

Humphrey


People also ask

What is alpha transparency in image?

The alpha channel is a special channel that handles transparency. When an image has an alpha channel on it, it means you can adjust the image's opacity levels and make bits translucent or totally see-through. The alpha channel is instrumental when you want to remove the background from an image.

Does PNG support alpha transparency?

An alpha channel, representing transparency information on a per-pixel basis, can be included in grayscale and truecolor PNG images. An alpha value of zero represents full transparency, and a value of (2^bitdepth)-1 represents a fully opaque pixel.


2 Answers

This can be done by checking if the image is transparent

def remove_transparency(im, bg_colour=(255, 255, 255)):      # Only process if image has transparency (http://stackoverflow.com/a/1963146)     if im.mode in ('RGBA', 'LA') or (im.mode == 'P' and 'transparency' in im.info):          # Need to convert to RGBA if LA format due to a bug in PIL (http://stackoverflow.com/a/1963146)         alpha = im.convert('RGBA').split()[-1]          # Create a new background image of our matt color.         # Must be RGBA because paste requires both images have the same format         # (http://stackoverflow.com/a/8720632  and  http://stackoverflow.com/a/9459208)         bg = Image.new("RGBA", im.size, bg_colour + (255,))         bg.paste(im, mask=alpha)         return bg      else:         return im 
like image 87
Humphrey Avatar answered Oct 23 '22 12:10

Humphrey


I'd suggest using Image.alpha_composite.
This code can avoid a tuple index out of range error if png has no alpha channel.

from PIL import Image  png = Image.open(img_path).convert('RGBA') background = Image.new('RGBA', png.size, (255,255,255))  alpha_composite = Image.alpha_composite(background, png) alpha_composite.save('foo.jpg', 'JPEG', quality=80) 

I also recommend you inspect both results with a image.show().

Credits for this answer goes to shuuji3 and others who helped build a vast answers repertoire in this other question.

like image 36
Vinícius M Avatar answered Oct 23 '22 11:10

Vinícius M