Search code examples
image-processingpython-imaging-libraryimage-masking

How to paste an image on top of another, the empty pixels of the background remain empty Python PIL


I want to paste the first image (which is a simple vertical gradient, from transparent to black), at the bottom of the background. The empty pixels in the background need to remain empty, and the rounded corners must be preserved. I know I need to use some combination of alpha_composite, paste and masking but really could not figure it out. How can I achieve this using python pillow library?

Paste image

Background

Expected result


Solution

  • Here's a way to do that:

    #!/usr/bin/env python3
    
    from PIL import Image
    
    # Open background and ensure RGBA
    bg = Image.open('bg.png').convert('RGBA')
    
    # Open foreground, ensure RGBA and match to size of background
    fg = Image.open('fg.png').convert('RGBA').resize(bg.size)
    
    # Put aside background alpha channel
    bgA = bg.getchannel('A')
    
    # Paste foreground over background with alpha
    bg.paste(fg, mask=fg)
    
    # Reapply transparent cut-outs from original background
    bg.putalpha(bgA)
    
    bg.save('result.png')
    

    enter image description here