Skip to content
Advertisement

How to fit an image into a larger image? Python, pillow

I have an image that I want to fit into another bigger image, so the smaller image is as big as possible. Is there a possible way to do that? It’s like resizing without deforming the ratio.

I have tried this code:

image = Image.open(input_path)

x, y = image.size

offset_x = math.floor((512 - x) / 2)
offset_y = math.ceil((512 - y) / 2)

output_image = Image.new(image.mode, (512, 512), (255, 255, 255, 0))
output_image.paste(image, (offset_x, offset_y))


output_image.save(output_path)

but it doesn’t really work. (note that 512 and 512 are the result sizes)

Advertisement

Answer

Ok, so the answer is the ImageOps.pad() function. I didn’t know it existed, so yeah.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement