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


Expected result


  • Here's a way to do that:

    #!/usr/bin/env python3
    from PIL import Image
    # Open background and ensure RGBA
    bg ='bg.png').convert('RGBA')
    # Open foreground, ensure RGBA and match to size of background
    fg ='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

    enter image description here