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

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

    My ugly example.

    Function get file like: "pic[0-9a-z].[extension]", resize them to 120x120, moves section to center and save to "ico[0-9a-z].[extension]", works with portrait and landscape:

    def imageResize(filepath):
        from PIL import Image
        file_dir=os.path.split(filepath)
        img = Image.open(filepath)
    
        if img.size[0] > img.size[1]:
            aspect = img.size[1]/120
            new_size = (img.size[0]/aspect, 120)
        else:
            aspect = img.size[0]/120
            new_size = (120, img.size[1]/aspect)
        img.resize(new_size).save(file_dir[0]+'/ico'+file_dir[1][3:])
        img = Image.open(file_dir[0]+'/ico'+file_dir[1][3:])
    
        if img.size[0] > img.size[1]:
            new_img = img.crop( (
                (((img.size[0])-120)/2),
                0,
                120+(((img.size[0])-120)/2),
                120
            ) )
        else:
            new_img = img.crop( (
                0,
                (((img.size[1])-120)/2),
                120,
                120+(((img.size[1])-120)/2)
            ) )
    
        new_img.save(file_dir[0]+'/ico'+file_dir[1][3:])
    

提交回复
热议问题