Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How replace transparent with a color in pillow

I need to replace the transparency layer of a png image with a color white. I tried this

from PIL import Image
image = Image.open('test.png')
new_image = image.convert('RGB', colors=255)
new_image.save('test.jpg', quality=75)

but the transparency layer turned black. Anyone can help me?

like image 724
rudson alves Avatar asked Jun 17 '18 15:06

rudson alves


People also ask

How do I make a background color transparent in Python?

If you want to make something completely transparent, simply set the alpha value of the corresponding color to 0. For plt. savefig , there is also a "lazy" option by setting the rc-parameter savefig. transparent to True , which sets the alpha of all facecolors to 0%.

How do you make white pixels transparent in Python?

We should make all pixels with white color transparent. img. putpixel((x, y), (255, 255, 255, 0)) can make a pixel transparent.


1 Answers

Paste the image on a completely white rgba background, then convert it to jpeg.

from PIL import Image

image = Image.open('test.png')
new_image = Image.new("RGBA", image.size, "WHITE") # Create a white rgba background
new_image.paste(image, (0, 0), image)              # Paste the image on the background. Go to the links given below for details.
new_image.convert('RGB').save('test.jpg', "JPEG")  # Save as JPEG

Take a look at this and this.

like image 148
Alperen Cetin Avatar answered Nov 15 '22 23:11

Alperen Cetin