A simple python function to downsize an image and calculate the new dimensions while keeping aspect ratio.

I needed this functionality for a web application. There are some variations found on the net from which I constructed this simple but effective python function to get ‘the other’ value.

Based on the original image dimensions “i_…” it figures out whether the image is portrait or landscape and calculates either the width or height.

def calculate_image_resize(i_width, i_height, max=0):

    i_width = float(i_width)
    i_height = float(i_height)
    ratio = i_width / i_height

    print 'w:', i_width, 'h:', i_height, 'r:', ratio

    if i_width < i_height:
        print 'portrait'
        c_height = max
        c_width = max * ratio
    else:
        print 'landscape'
        c_width = max
        c_height = max / ratio

    c_width = int(c_width)
    c_height = int(c_height)

    return c_width, c_height

Dropping the function in a python shell and calling it results in this output:

In [2]: calculate_image_resize(1700, 330, max=150)
w: 1700.0 h: 330.0 r: 5.15151515152
landscape
Out[2]: (150, 29)

In [3]: calculate_image_resize(170, 330, max=150)
w: 170.0 h: 330.0 r: 0.515151515152
portrait
Out[3]: (77, 150)

I deliberately left in the obvious 150 so you know instantly which dimension was calculated “c_…”.

Hope this saves people the trouble to figure it out by them selves.

GrtzG