【问题标题】:How replace transparent with a color in pillow如何用枕头中的颜色替换透明
【发布时间】:2018-11-26 14:59:41
【问题描述】:
我需要将 png 图像的透明层替换为白色。我试过这个
from PIL import Image
image = Image.open('test.png')
new_image = image.convert('RGB', colors=255)
new_image.save('test.jpg', quality=75)
但是透明层变黑了。谁能帮帮我?
【问题讨论】:
标签:
python
python-3.x
image
pillow
【解决方案1】:
将图像粘贴到完全白色的 rgba 背景上,然后将其转换为 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
看看this和this。
【解决方案2】:
其他答案给了我一个Bad transparency mask 错误。解决办法是确保原图是RGBA模式。
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")