在PIL中的特定位置创建圆形缩略图

时间:2018-12-04 04:20:17

标签: python python-3.x python-imaging-library

我一直在研究一个python文件,该文件根据用户的个人资料图片和姓名打招呼。我设法将他们的名字放在了必填区域,但是在给定位置粘贴圆形个人资料图片时遇到了问题。

这是它的外观

input.png

输入   个人资料图片

profilepicture.png

输出

output.png

1 个答案:

答案 0 :(得分:0)

这里的关键是Image.paste的'mask'参数-https://pillow.readthedocs.io/en/5.3.x/reference/Image.html#PIL.Image.Image.paste-'如果指定了遮罩,则此方法仅更新由遮罩指示的区域。'

因此,我们可以创建一个圆形图像,仅粘贴个人资料图片的相关部分。

from PIL import Image, ImageDraw

background = Image.open('input.jpg')
im = Image.open('profilepicture.png')

# Scale the image to be the size of the circle
im = im.resize((1024, 1024), Image.ANTIALIAS)

# Create the circle mask
mask = Image.new('L', im.size)
draw = ImageDraw.Draw(mask)
draw.ellipse((0, 0) + im.size, fill=255)

background.paste(im, (410, 1104), mask)
background.save('output.png')