How do I resize an image using PIL and maintain its aspect ratio?

后端 未结 20 1874
-上瘾入骨i
-上瘾入骨i 2020-11-22 02:30

Is there an obvious way to do this that I\'m missing? I\'m just trying to make thumbnails.

相关标签:
20条回答
  • 2020-11-22 02:58

    PIL already has the option to crop an image

    img = ImageOps.fit(img, size, Image.ANTIALIAS)
    
    0 讨论(0)
  • 2020-11-22 02:58

    If you don't want / don't have a need to open image with Pillow, use this:

    from PIL import Image
    
    new_img_arr = numpy.array(Image.fromarray(img_arr).resize((new_width, new_height), Image.ANTIALIAS))
    
    0 讨论(0)
  • 2020-11-22 03:00

    Based in @tomvon, I finished using the following (pick your case):

    a) Resizing height (I know the new width, so I need the new height)

    new_width  = 680
    new_height = new_width * height / width 
    

    b) Resizing width (I know the new height, so I need the new width)

    new_height = 680
    new_width  = new_height * width / height
    

    Then just:

    img = img.resize((new_width, new_height), Image.ANTIALIAS)
    
    0 讨论(0)
  • 2020-11-22 03:02

    Just updating this question with a more modern wrapper This library wraps Pillow (a fork of PIL) https://pypi.org/project/python-resize-image/

    Allowing you to do something like this :-

    from PIL import Image
    from resizeimage import resizeimage
    
    fd_img = open('test-image.jpeg', 'r')
    img = Image.open(fd_img)
    img = resizeimage.resize_width(img, 200)
    img.save('test-image-width.jpeg', img.format)
    fd_img.close()
    

    Heaps more examples in the above link.

    0 讨论(0)
  • 2020-11-22 03:05

    I also recommend using PIL's thumbnail method, because it removes all the ratio hassles from you.

    One important hint, though: Replace

    im.thumbnail(size)
    

    with

    im.thumbnail(size,Image.ANTIALIAS)
    

    by default, PIL uses the Image.NEAREST filter for resizing which results in good performance, but poor quality.

    0 讨论(0)
  • 2020-11-22 03:06

    Have updated the answer above by "tomvon"

    from PIL import Image
    
    img = Image.open(image_path)
    
    width, height = img.size[:2]
    
    if height > width:
        baseheight = 64
        hpercent = (baseheight/float(img.size[1]))
        wsize = int((float(img.size[0])*float(hpercent)))
        img = img.resize((wsize, baseheight), Image.ANTIALIAS)
        img.save('resized.jpg')
    else:
        basewidth = 64
        wpercent = (basewidth/float(img.size[0]))
        hsize = int((float(img.size[1])*float(wpercent)))
        img = img.resize((basewidth,hsize), Image.ANTIALIAS)
        img.save('resized.jpg')
    
    0 讨论(0)
提交回复
热议问题