PIL: Thumbnail and end up with a square image

前端 未结 7 719
一个人的身影
一个人的身影 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:01

    PIL already has a function to do exactly that:

    from PIL import Image, ImageOps
    thumb = ImageOps.fit(image, size, Image.ANTIALIAS)
    
    0 讨论(0)
  • 2020-12-22 23:06

    you can wrap Nadia's answer in this function, which gives you control over size and background.

    def make_square(im, min_size=36, fill_color=(255, 255, 255, 0)):
        x, y = im.size
        size = min(min_size, x, y)
        new_im = Image.new('RGBA', (size, size), fill_color)
        im.thumbnail((256, 256))
        new_im.paste(im, (int((x - size) / 2), int((y -size) / 2))
        return new_im
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-22 23:16

    Or this, maybe... (forgive spaghetti)

    from PIL import Image
    
    def process_image(image, size):
        if image.size[0] > size[0] or image.size[1] > size[1]:
            #preserve original
            thumb = image.copy()
            thumb.thumbnail(size,Image.ANTIALIAS)
            img = thumb.copy()
        img_padded = Image.new("RGBA",size)
        img_padded.paste(image,(int((size[0]-image.size[0])/2),int((size[1]-image.size[1])/2)))
        return img_padded
    
    0 讨论(0)
  • 2020-12-22 23:19
    from PIL import Image
    
    import StringIO
    
    def thumbnail_image():
        image = Image.open("image.png")
        image.thumbnail((300, 200))
        thumb_buffer = StringIO.StringIO()
        image.save(thumb_buffer, format=image.format)
        fp = open("thumbnail.png", "w")
        fp.write(thumb_buffer.getvalue())
        fp.close()
    
    0 讨论(0)
  • 2020-12-22 23:19

    Why not simply use the resize method ?

    from PIL import Image
    image = Image.open('/path/to/img.png')
    image = image.resize((36,36), Image.ANTIALIAS)
    

    See recommendations for image resizing in this release note: https://pillow.readthedocs.io/en/stable/releasenotes/5.3.0.html

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