Skip to content Skip to sidebar Skip to footer

How To Resize An Image In Python, While Retaining Aspect Ratio, Given A Target Size?

First off part of me feels like this is a stupid question, sorry about that. Currently the most accurate way I've found of calculating the optimum scaling factor (best width and he

Solution 1:

Here is my approach,

aspectRatio = currentWidth / currentHeight
heigth * width = area

So,

height * (height * aspectRatio) = area
height² = area / aspectRatio
height = sqrt(area / aspectRatio)

At that point we know the target height, and width = height * aspectRatio.

Ex:

area = 100000height = sqrt(100000 / (700/979)) = 373.974width = 373.974 * (700/979) = 267.397

Solution 2:

I think the fastest and cleaner way is:

from PIL import Image
from math import sqrt

img=Image.open(PATH)
img.thumbnails([round(sqrt(TARGET_PIXEL_AREA))]*2)

I hope it will help

Post a Comment for "How To Resize An Image In Python, While Retaining Aspect Ratio, Given A Target Size?"