PIL: Paste image over a transparent image without destroying background pixels

Viewed 117

I'm trying to use PIL to combine two images with a heart image in the middle, but it always removes pixels from behind itself and replaces them with complete transparency, destroying the images below it. How do I paste/overlay an image to a specific spot on the image without doing this?

Current code:

heart = Image.open("Heart.png")
shrimp = Image.open("Shrimp_Jackson.jpg")
bg = Image.open("bg.png").resize((400,250))

bg.paste(shrimp, (0,0))
bg.paste(shrimp, (200,0))
bg.paste(heart, (60, 0))
bg.save("Output.png")

The result: This happens

1 Answers

You heart probably doesn't have a transparent background, it has only white colored background.

Download ImageMagick, then convert white non-transparent background that you have to transparent one using magick command:

magick convert heart.png -transparent white heart2.png

Then use this heart2.png in your code as @HansHirse suggested bg.paste(heart, (60, 0), mask=heart).

Related