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

后端 未结 20 1891
-上瘾入骨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:56

    I was trying to resize some images for a slideshow video and because of that, I wanted not just one max dimension, but a max width and a max height (the size of the video frame).
    And there was always the possibility of a portrait video...
    The Image.thumbnail method was promising, but I could not make it upscale a smaller image.

    So after I couldn't find an obvious way to do that here (or at some other places), I wrote this function and put it here for the ones to come:

    from PIL import Image
    
    def get_resized_img(img_path, video_size):
        img = Image.open(img_path)
        width, height = video_size  # these are the MAX dimensions
        video_ratio = width / height
        img_ratio = img.size[0] / img.size[1]
        if video_ratio >= 1:  # the video is wide
            if img_ratio <= video_ratio:  # image is not wide enough
                width_new = int(height * img_ratio)
                size_new = width_new, height
            else:  # image is wider than video
                height_new = int(width / img_ratio)
                size_new = width, height_new
        else:  # the video is tall
            if img_ratio >= video_ratio:  # image is not tall enough
                height_new = int(width / img_ratio)
                size_new = width, height_new
            else:  # image is taller than video
                width_new = int(height * img_ratio)
                size_new = width_new, height
        return img.resize(size_new, resample=Image.LANCZOS)
    

提交回复
热议问题