PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 29, 2022

[FIXED] How to alpha_composite() two images with different sizes (Pillow)

 July 29, 2022     image, python, python-imaging-library     No comments   

Issue

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.


Solution

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



Answered By - Vytas
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing