如何用枕头中的颜色替换透明

问题描述 投票:1回答:2

我需要用白色替换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
2个回答
3
投票

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

看看thisthis


0
投票

基于@Alperen的答案,如果你想摆脱透明度,你可以将你的图像粘贴到一个新的非透明(RGB)图像上:

from PIL import Image

input = Image.open('image.png')
image = Image.new("RGB", input.size, "WHITE")
image.paste(input, (0, 0), input) 
image.save('image_out.png')
© www.soinside.com 2019 - 2024. All rights reserved.