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
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()