How to create a circular thumbnail using python pillow and overlap on background image

后端 未结 1 1697
天涯浪人
天涯浪人 2020-12-18 05:33

avatar.jpg

\"\"

back.jpg

\"\"

How

相关标签:
1条回答
  • 2020-12-18 05:45

    Here's an example using your images. Dimensions are hardcoded in the example, but you can easily replace them with calculations. avatar.jpg and background.jpg are images in your post saved as is.

    Here's a link to github repo for this example : python_pillow_circular_thumbnail

    from PIL import Image, ImageOps, ImageDraw
    
    im = Image.open('avatar.jpg')
    im = im.resize((120, 120));
    bigsize = (im.size[0] * 3, im.size[1] * 3)
    mask = Image.new('L', bigsize, 0)
    draw = ImageDraw.Draw(mask) 
    draw.ellipse((0, 0) + bigsize, fill=255)
    mask = mask.resize(im.size, Image.ANTIALIAS)
    im.putalpha(mask)
    
    output = ImageOps.fit(im, mask.size, centering=(0.5, 0.5))
    output.putalpha(mask)
    output.save('output.png')
    
    background = Image.open('back.jpg')
    background.paste(im, (150, 10), im)
    background.save('overlap.png')
    

    output.png:

    overlap.png:

    Crop part of this code is borrowed form this answer.

    Hope it helps!

    0 讨论(0)
提交回复
热议问题