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.
My code:
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")
How can I have transparent pixels instead of white?
Best Answer
You need to specify the image as the mask as follows in the paste function:
Giving you:
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: