Python/PIL Resize all images in a folder

后端 未结 8 1245
感动是毒
感动是毒 2020-12-08 00:31

I have the following code that I thought would resize the images in the specified path But when I run it, nothing works and yet python doesn\'t throw any error so I don\'t

8条回答
  •  無奈伤痛
    2020-12-08 01:23

    In case you want to keep the same aspect ratio of the image you can use this script.

    from PIL import Image
    import os, sys
    
    path = "/path/images/"
    dirs = os.listdir( path )
    final_size = 244;
    
    def resize_aspect_fit():
        for item in dirs:
             if item == '.DS_Store':
                 continue
             if os.path.isfile(path+item):
                 im = Image.open(path+item)
                 f, e = os.path.splitext(path+item)
                 size = im.size
                 ratio = float(final_size) / max(size)
                 new_image_size = tuple([int(x*ratio) for x in size])
                 im = im.resize(new_image_size, Image.ANTIALIAS)
                 new_im = Image.new("RGB", (final_size, final_size))
                 new_im.paste(im, ((final_size-new_image_size[0])//2, (final_size-new_image_size[1])//2))
                 new_im.save(f + 'resized.jpg', 'JPEG', quality=90)
    resize_aspect_fit()
    

提交回复
热议问题