B1ueDev
B1ueDev

Reputation: 96

PIL: Paste image with resized aspect ratio

I have 2 images (icon.png and background.png). In the background.png image, there is a blank area which will be the place for the icon.png to be pasted using PIL (Python). However, the icon.png is a little bit bigger compared to the blank frame in the background.png. How can I paste and make the icon.png smaller so it can fit with the frame?

My code so far:

icon = Image.open("./icon.png")
background = Image.open("./background.png")

mask = Image.new("L", icon.size, 0)
draw = ImageDraw.Draw(mask)
draw.ellipse((0, 0) + icon.size, fill=255)


back_im = background.copy()
back_im.paste(icon, (200, 100), mask=mask)
back_im.save("./back_im.png")

Upvotes: 0

Views: 2090

Answers (1)

Alfredo Maussa
Alfredo Maussa

Reputation: 545

Use resize after read the icon image to fit the desired size:

from PIL import Image, ImageDraw

iconSize=(200,100)
icon = Image.open("./icon.png")
icon=icon.resize(iconSize)
background = Image.open("./background.png")

mask = Image.new("L", icon.size, 0)
draw = ImageDraw.Draw(mask)
draw.ellipse((0, 0) + icon.size, fill=255)


back_im = background.copy()
# back_im.paste(icon, iconSize, mask=mask)
back_im.paste(icon, icon.size, mask=mask)
back_im.save("./back_im.png")

Upvotes: 1

Related Questions