27

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?

Alperen
  • 3,772
  • 3
  • 27
  • 49
rudson alves
  • 367
  • 1
  • 3
  • 3

2 Answers2

32

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.

Alperen
  • 3,772
  • 3
  • 27
  • 49
7

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")
Denziloe
  • 7,473
  • 3
  • 24
  • 34