如何将具有透明性的PNG图像粘贴到PIL中的另一幅没有白色像素的图像? [英] How to paste a PNG image with transparency to another image in PIL without white pixels?

查看:140
本文介绍了如何将具有透明性的PNG图像粘贴到PIL中的另一幅没有白色像素的图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个图像,一个背景和一个带有透明像素的PNG图像.我正在尝试使用Python-PIL将PNG粘贴到背景上,但是当我粘贴两个图像时,在PNG图像周围有透明像素的地方得到了白色像素.

I have two images, a background and a PNG image with transparent pixels. I am trying to paste the PNG onto the background using Python-PIL but when I paste the two images I get white pixels around the PNG image where there were transparent pixels.

我的代码:

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")

我的图像:

My images:

我的输出图像:

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

How can I have transparent pixels instead of white?

推荐答案

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

You need to specify the image as the mask as follows in the paste function:

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上,您需要根据图像尺寸计算正确的偏移量:

To centre both the background image and the transparent image on the new text_img, you need to calculate the correct offsets based on the images dimensions:

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)

这篇关于如何将具有透明性的PNG图像粘贴到PIL中的另一幅没有白色像素的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆