1

So I am trying to paste a transparent image on top of a normal image. But for some reason, the transparency is gone.

Is there a way to keep the transparency of the second image (the transparent one) on top of the first image (the normal one) without losing the transparency of the second image?

(I am new to PIL by the way)

BG = Image.open("BGImage.png") # normal image, size is 1920x1080
BG = BG.convert("RGBA")
overlay = Image.open("OverlayImage.png") # transparent image, size is 1920x1080
overlay = overlay.convert("RGBA")

BG = Image.alpha_composite(BG, overlay) # I tried doing this but it didn't work

BG.save("NewImage.png")

Background Image: Background

Overlay Image: Overlay

What I got: What I got

What I wanted (slight change in color): What I wanted

Zeperox
  • 196
  • 2
  • 13

1 Answers1

0

Use paste like this - after ensuring your image is not palettised:

from PIL import Image

# Open background and foreground ensuring they are not palette images
bg = Image.open('bg.png').convert('RGB')
fg = Image.open('fg.png')

# Paste foreground onto background and save
bg.paste(fg,mask=fg)
bg.save('result.png')

enter image description here

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432