Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

My images:
enter image description here enter image description here

my output image:
enter image description here

How can I have transparent pixels instead of white?

like image 877
pavitran Avatar asked Jul 28 '16 05:07

pavitran


1 Answers

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

Giving you:

paste with transparency


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)
like image 197
Martin Evans Avatar answered Sep 22 '22 09:09

Martin Evans