Search code examples
pythonimage-scaling

Scale an image by a single dimension (x OR y) given minimum dimensions


I know I could do this with a bunch of nested if statements, however I can't help feel like there's a more elegant way. It's really just a maths issue I guess, but I'm interested in pythonic answers if indeed there are any.

I have an image which can be ANY dimensions / aspect ratio.

It must be scaled up OR down so that it covers a minumum of 55w x 168h

The complication here is that it needs to be scaled by a function that takes only a single value which specifies the length of a side of a square which the image it will fit inside.

For instance, say we have an image of size 1000w x 500h and we scale it to 200, then the resulting image must fit inside a square the with a side of 200, meaning the resulting image would be 200w x 100h.

Conversely if our image is 200x1000 and we scale to to 200, we'll end up with 40x200.

So to scale an image of 1000x500 to cover 55x168, we'd need to scale it to 336, giving a size of 336x168 since that's the largest image which can fit inside a 336x336 sided square.

And to scale an image of 200x1000 to cover 55x168, we'd need to scale it to 275 and end up with 55x275.

Hopefully this is clearer than mud! Thanks for any ideas.

Justification: For those who are interested in why I'm scaling via a value of a square side, this is the way Picasa scales images via URL injection. For instance take the following 2 URLs:

Notice both have the URL component s150, however one image is 150x112 and the other is 112x150. 150 is the value of the square these images will both fit in.


Solution

  • def name_of_function(img_x, img_y):  # for lack of a better name
        image_dimensions = (img_x, img_y)
        min_dimensions = (55.0, 168.0)
        scale = min(image_dimensions[i]/min_dimensions[i] for i in range(2))
        return max(i/scale for i in image_dimensions)
    
    name_of_function(1000, 500)
    # 336.0
    name_of_function(200, 1000)
    # 275.0
    

    Pretty sure this is what you're looking for.