rudson alves
rudson alves

Reputation: 437

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?

Upvotes: 33

Views: 22995

Answers (3)

snoob dogg
snoob dogg

Reputation: 2865

The paste method doesn't work very well; instead, use alpha_composite. If you intend to replace alpha with a color, I assume your image is originally in RGBA format, so there's no need to convert it

from PIL import Image

img_without_bg = Image.open('test.png')
white_bg = Image.new("RGBA", img_without_bg.size, "WHITE")
result = Image.alpha_composite(white_bg, img_without_bg)

result.save('result_with_white_bg.png')

Upvotes: 2

Denziloe
Denziloe

Reputation: 8131

The other answers gave me a Bad transparency mask error. The solution is to make sure the original image is in RGBA mode.

image = Image.open("test.png").convert("RGBA")
new_image = Image.new("RGBA", image.size, "WHITE")
new_image.paste(image, mask=image)

new_image.convert("RGB").save("test.jpg")

Upvotes: 9

Alperen
Alperen

Reputation: 4592

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.

Upvotes: 39

Related Questions