如何在PIL中将具有透明度的PNG图像粘贴到另一张图像上而不产生白色像素?

21

我有两张图片,一张是背景图,另一张是具有透明像素的PNG图像。我想使用Python-PIL将PNG粘贴到背景上,但在粘贴这两张图片时,PNG图像周围出现了白色像素,而在那些地方原本应该是透明像素。

我的代码:

import os
from PIL import Image, ImageDraw, ImageFont

filename='pikachu.png'
ironman = Image.open(filename, 'r')
filename1='bg.png'
bg = Image.open(filename1, 'r')
text_img = Image.new('RGBA', (600,320), (0, 0, 0, 0))
text_img.paste(bg, (0,0))
text_img.paste(ironman, (0,0))
text_img.save("ball.png", format="png")

我的图片:
图片描述 图片描述

我的输出图片:
图片描述

如何使白色变成透明像素?

1个回答

51
您需要在paste函数中指定图像作为蒙版,方法如下:
import os
from PIL import Image

filename = 'pikachu.png'
ironman = Image.open(filename, 'r')
filename1 = 'bg.png'
bg = Image.open(filename1, 'r')
text_img = Image.new('RGBA', (600,320), (0, 0, 0, 0))
text_img.paste(bg, (0,0))
text_img.paste(ironman, (0,0), mask=ironman)
text_img.save("ball.png", format="png")

给你:

带透明度的粘贴


为了将背景图像和透明图像都居中到新的 text_img 中,你需要根据图像大小计算正确的偏移量:

text_img.paste(bg, ((text_img.width - bg.width) // 2, (text_img.height - bg.height) // 2))
text_img.paste(ironman, ((text_img.width - ironman.width) // 2, (text_img.height - ironman.height) // 2), mask=ironman)

3
可能取决于图片,你能给我提供这张图片的链接吗?你也可以尝试使用 mask=ironman.split()[3] - Martin Evans
1
这里的函数.split()[3]是做什么用的? - pavitran
@CarlosRodrigez,我已经添加了一个简短的解释,以展示如何将两个图像都居中在新图像上。你只需要计算适当的偏移量,而不是使用(0, 0) - Martin Evans
运行时出现以下错误:期望整数参数,但得到了浮点数 - Carlos Rodrigez
2
使用 // 代替 / - Martin Evans
显示剩余6条评论

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