App Engine: Calculating the dimensions of thumbnails to be generated by serving thumbnails from the blobstore

I'm currently using the blobstore to generate thumbnails for images, however, I like to store the dimensions of the thumbnail in the img tag, as it is good practise and helps speed up rendering and makes a partially loaded page look a bit nicer.

How would I calculate the dimensions of a thumbnail generated by the blobstore, knowing only the dimensions of the original image?

My previous attempts haven't been very accurate, most of the time being off by a pixel or two (probably due to rounding).

I understand that fetching the thumbnail and than using the images API to check the dimensions would work, but I think that is inefficient.

Here is the code I use to calculate it at the moment, however, it is occasionally off by one pixel, causing the browser to slightly stretch the image, causing resize artefacts as well as being less performant.

from __future__ import division
def resized_size(original_width, original_height, width, height):
    original_ratio = float(original_width) / float(original_height)
    resize_ratio = float(width) / float(height)
    if original_ratio >= resize_ratio:
        return int(width), int(round(float(width) / float(original_ratio)))
    else:
        return int(round(float(original_ratio) * float(height))), int(height)

Accuracy is very important!

5
задан Noah McIlraith 27 February 2011 в 22:04
поделиться