Python: Image resizing: keep proportion - add white background

前端 未结 3 936
误落风尘
误落风尘 2021-01-02 16:50

I would like to create a Python script to resize images, but not changing its proportions, just by adding a white background

(So, a : 500*700 px im

3条回答
  •  囚心锁ツ
    2021-01-02 17:34

    The other answer didn't work for me, I rewrote it and this worked:

    def resize_with_pad(im, target_width, target_height):
        '''
        Resize PIL image keeping ratio and using white background.
        '''
        target_ratio = target_height / target_width
        im_ratio = im.height / im.width
        if target_ratio > im_ratio:
            # It must be fixed by width
            resize_width = target_width
            resize_height = round(resize_width * im_ratio)
        else:
            # Fixed by height
            resize_height = target_height
            resize_width = round(resize_height / im_ratio)
    
        image_resize = im.resize((resize_width, resize_height), Image.ANTIALIAS)
        background = Image.new('RGBA', (target_width, target_height), (255, 255, 255, 255))
        offset = (round((target_width - resize_width) / 2), round((target_height - resize_height) / 2))
        background.paste(image_resize, offset)
        return background.convert('RGB')
    

提交回复
热议问题