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

pav*_*ran 12 python python-imaging-library

我有两个图像,一个背景和一个透明像素的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")
Run Code Online (Sandbox Code Playgroud)

我的图片:
在此输入图像描述 在此输入图像描述

我的输出图片:
在此输入图像描述

如何才能使用透明像素而不是白色?

Mar*_*ans 25

您需要在粘贴功能中将图像指定为掩码,如下所示:

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")
Run Code Online (Sandbox Code Playgroud)

给你:

粘贴透明度


要将背景图像和透明图像居中放在新图像上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)
Run Code Online (Sandbox Code Playgroud)

  • 它可能取决于图像,您能给我一个链接到图像吗?您还可以尝试`mask = ironman.split()[3]` (2认同)
  • 使用`//`代替`/` (2认同)