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

后端 未结 4 425
伪装坚强ぢ
伪装坚强ぢ 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 09:51

    PIL has the thumbnail method which will scale keeping the aspect ratio. From there you just need to paste it centered onto your black background rectangle.

    from PIL import Image
    
    def black_background_thumbnail(path_to_image, thumbnail_size=(200,200)):
        background = Image.new('RGBA', thumbnail_size, "black")    
        source_image = Image.open(path_to_image).convert("RGBA")
        source_image.thumbnail(thumbnail_size)
        (w, h) = source_image.size
        background.paste(source_image, ((thumbnail_size[0] - w) / 2, (thumbnail_size[1] - h) / 2 ))
        return background
    
    if __name__ == '__main__':
        img = black_background_thumbnail('hLARP.png')
        img.save('tmp.jpg')
        img.show()
    

提交回复
热议问题