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

27,291

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)
Share:
27,291

Related videos on Youtube

pavitran
Author by

pavitran

BY DAY: Ask questions on stackoverflow. BY NIGHT: Search answers on stackoverflow. FOR FUN: write crazy "About me" on stackoverflow. "if you didn't find your answer by now,stackoverflow has it."-how would i know who wrote this ask stackoverflow

Updated on November 17, 2020

Comments

  • pavitran
    pavitran over 2 years

    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?

Related