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

后端 未结 20 1873
-上瘾入骨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 03:07
    from PIL import Image
    
    img = Image.open('/your image path/image.jpg') # image extension *.png,*.jpg
    new_width  = 200
    new_height = 300
    img = img.resize((new_width, new_height), Image.ANTIALIAS)
    img.save('output image name.png') # format may what you want *.png, *jpg, *.gif
    
    0 讨论(0)
  • 2020-11-22 03:07

    A simple method for keeping constrained ratios and passing a max width / height. Not the prettiest but gets the job done and is easy to understand:

    def resize(img_path, max_px_size, output_folder):
        with Image.open(img_path) as img:
            width_0, height_0 = img.size
            out_f_name = os.path.split(img_path)[-1]
            out_f_path = os.path.join(output_folder, out_f_name)
    
            if max((width_0, height_0)) <= max_px_size:
                print('writing {} to disk (no change from original)'.format(out_f_path))
                img.save(out_f_path)
                return
    
            if width_0 > height_0:
                wpercent = max_px_size / float(width_0)
                hsize = int(float(height_0) * float(wpercent))
                img = img.resize((max_px_size, hsize), Image.ANTIALIAS)
                print('writing {} to disk'.format(out_f_path))
                img.save(out_f_path)
                return
    
            if width_0 < height_0:
                hpercent = max_px_size / float(height_0)
                wsize = int(float(width_0) * float(hpercent))
                img = img.resize((max_px_size, wsize), Image.ANTIALIAS)
                print('writing {} to disk'.format(out_f_path))
                img.save(out_f_path)
                return
    

    Here's a python script that uses this function to run batch image resizing.

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