How to resize an image in python, while retaining aspect ratio, given a target size?

后端 未结 2 1530
既然无缘
既然无缘 2021-02-06 09:46

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 an

相关标签:
2条回答
  • 2021-02-06 10:12

    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

    0 讨论(0)
  • 2021-02-06 10:18

    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 = 100 000
    height = sqrt(100 000 / (700/979)) = 373.974
    width = 373.974 * (700/979) = 267.397
    
    0 讨论(0)
提交回复
热议问题