如何在Pillow中用颜色替换透明色

27

我需要用白色替换PNG图像的透明层。我尝试了以下方法

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

但透明图层变成了黑色。有人可以帮我吗?


透明度图层没有颜色 - 它只表示像素的透明度。 - Mark Setchell
2个回答

33

将图像粘贴到完全白色的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

看看这个这个


8
其他答案给了我一个 “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")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接