首页 > 解决方案 > 如何用枕头中的颜色替换透明

问题描述

我需要用白色替换 png 图像的透明层。我试过这个

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

但是透明层变黑了。任何人都可以帮助我吗?

标签: pythonpython-3.ximagepillow

解决方案


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

看看这个这个


推荐阅读