Resize rectangular image to square, keeping ratio and fill background with black

后端 未结 4 429
伪装坚强ぢ
伪装坚强ぢ 2020-12-13 09:09

I\'m trying to resize a batch of grayscale images that are 256 x N pixels (N varies, but is always ≤256).

My intention is to downscale the images.

The resiz

4条回答
  •  温柔的废话
    2020-12-13 10:02

    You can use Pillow to accomplish that:

    Code:

    from PIL import Image
    
    def make_square(im, min_size=256, fill_color=(0, 0, 0, 0)):
        x, y = im.size
        size = max(min_size, x, y)
        new_im = Image.new('RGBA', (size, size), fill_color)
        new_im.paste(im, (int((size - x) / 2), int((size - y) / 2)))
        return new_im
    

    Test Code:

    test_image = Image.open('hLarp.png')
    new_image = make_square(test_image)
    new_image.show()
    

    For a white background you can do:

    new_image = make_square(test_image, fill_color=(255, 255, 255, 0))
    

    Result:

提交回复
热议问题