25

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?

1
  • The transparency layer doesn't have a colour - it only indicates how transparent a pixel is. Jun 17, 2018 at 15:44

2 Answers 2

31

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.

0
5

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")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.