PIL: Thumbnail and end up with a square image

前端 未结 7 770
一个人的身影
一个人的身影 2020-12-22 22:33

Calling

image = Image.open(data)
image.thumbnail((36,36), Image.NEAREST)

will maintain the aspect ratio. But I need to end up displaying th

7条回答
  •  一个人的身影
    2020-12-22 23:09

    Paste the image into a transparent image with the right size as a background

    from PIL import Image
    size = (36, 36)
    image = Image.open(data)
    image.thumbnail(size, Image.ANTIALIAS)
    background = Image.new('RGBA', size, (255, 255, 255, 0))
    background.paste(
        image, (int((size[0] - image.size[0]) / 2), int((size[1] - image.size[1]) / 2))
    )
    background.save("output.png")
    

    EDIT: fixed syntax error

提交回复
热议问题