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

前端 未结 1 1271
别跟我提以往
别跟我提以往 2021-01-01 19:23

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

相关标签:
1条回答
  • 2021-01-01 19:49

    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:


    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)
    
    0 讨论(0)
提交回复
热议问题