如何将具有透明度的PNG图像粘贴到PIL中没有白色像素的另一个图像?

How to paste a PNG image with transparency to another image in PIL without white pixels?

我有两张图片,一张背景和一张透明像素的 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")

我的图片:

我的输出图像:

我怎样才能拥有透明像素而不是白色像素?

您需要在粘贴函数中指定图片作为遮罩如下:

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)