When I used Pillow to overlay PNG images of different sizes with ʻimg.paste`, the phenomenon that the transparency of the upper layer penetrated to the lower layer and the background was partially lost occurred, so a memo of how to deal with it.
Python 3.8.2 Pillow 7.2 Ubuntu 20.04 on WSL2
Background (bg_cloudy.png)
Image you want to overlay (cloudy.png)
However, if you try to overlap ʻimg with
bg.paste`, it will expire.
from PIL import Image
bg = Image.open('bg_cloudy.png').convert('RGBA')
img = Image.open('cloudy.png').convert('RGBA')
bg.paste(img, (232, 412))
bg.save('a.png')
The background is also transparent in the transparent part of the cloud icon
This can be avoided by using ʻImage.alpha_composite (bg, img)`. However, since the size of the image of the first argument and the image of the second argument must match, paste it at the specified position on the transparent image with nothing that has the same size as the background, and then overlay it. To do.
from PIL import Image
bg = Image.open('bg_cloudy.png').convert('RGBA')
img = Image.open('cloudy.png').convert('RGBA')
#Generate a transparent image the same size as the background
img_clear = Image.new("RGBA", bg.size, (255, 255, 255, 0))
#Paste on top of transparent image
img_clear.paste(img, (232, 412))
#Overlay
bg = Image.alpha_composite(bg, img_clear)
bg.save('a.png')
I was able to synthesize as intended without any problems in the transparent part.
Image of clouds in the background https://www.priga.jp/ Icon cloud image https://github.com/twitter/twemoji
Recommended Posts