Home > OS >  How to alpha_composite() two images with different sizes (Pillow)
How to alpha_composite() two images with different sizes (Pillow)

Time:06-26

As the title says I want to use Image.alpha_composite() to merge two images of different sizes (800x600 and 1280x720). I want to use Image.alpha_composite() because my foreground image has a transparency effect but whenever I try to do this it just says the images do not match (they are a different size). I tried to resize it using resize() but it messes up the aspect ratio. I also tried using paste() to paste the smaller image onto a blank 1280x720 image but pasting the image to a transparent image does not work. Any help is appreciated.

CodePudding user response:

As pointed out in the comments, it is much easier for others to understand your question if you show the code that you attempted (but which didn't yield the desired result).

If I interpret your question correctly, one way to solve this is to pad the smaller image by pasting it onto an empty image that matches the larger one in size:

from PIL import Image, ImageDraw

one = Image.new('RGBA', (128, 72), (255, 255, 255, 0))
ctx = ImageDraw.Draw(one)
ctx.ellipse((10, 10, 128-10, 72-10), (255, 192, 0))

two = Image.new('RGBA', (80, 60), (255, 255, 255, 0))
ctx = ImageDraw.Draw(two)
ctx.rectangle((4, 4, 80-4, 60-4), (192, 0, 0))

two_padded = Image.new('RGBA', one.size, (255, 255, 255, 0))
two_padded.paste(two)

result = Image.alpha_composite(one, two_padded)
result.show()

...show()s me the following result:

enter image description here

  • Related