tags:

views:

45

answers:

3

I want to create a thumbnail, and the width has to be either fixed or no bigger than 200 pixels wide (the length can be anything).

The images are either .jpg or .png or .gif

I am using python.

The reason it has to be fixed is so that it fits inside a html table cell.

+3  A: 

Look at PyMagick, the python interface for the ImageMagick libraries. It's fairly simple to resize an image, retaining proportion, while limiting the longest side.

edit: when I say fairly simple, I mean you can describe your resize in terms of the longest acceptable values for each side, and ImageMagick will preserve the proportions automatically.

Seamus Campbell
PyMagick was last updated in 2002 and by all reports (I didn't try to build it myself) is broken. I expect you meant the Python Imaging Library http://www.pythonware.com/products/pil/
msw
PythonMagick is what I meant, but that seems also to have fallen out of circulation. Very odd. Looks like @msw is correct and PIL is the way to go.
Seamus Campbell
+4  A: 

To keep proportions the same, you need to multiply both the width and the height by the same scaling factor. Calculate each independently to fit inside your space, then choose the smallest of the two. You say you don't care about the height, but you might want to set a bound on it anyway in case someone feeds you a really skinny image.

In the code below, I've added two additional constraints: the resulting thumbnail width or height will always be >= 1, and the scaling factor will will always be <= 1 (so that the thumbnail isn't larger than the original).

scale_x = max_width / image_width
scale_y = max_height / image_height
scale = min(scale_x, scale_y, 1)
thumb_width = max(round(image_width * scale), 1)
thumb_height = max(round(image_height * scale), 1)
Mark Ransom
+1  A: 

Support suggestion of using PIL. However, the calculation is actually much simpler:

from PIL import Image as PILImage

imageObj = PILImage.open(image_filename,'r')
iwidth, iheight = imageObj.size # pixels
size_proportion = iheight / iwidth # make sure your "limiter" is the denominator
newheight = size_proportion * 200
# resize the image to (newheight, 200) and save it

Alternatively, just call out to subprocess and use ImageMagic or GraphicsMagic (i use latter) These libs give you very good scaling algorithms, are written in lower level language and are very much optimized. One extra nice thing IM and GM do is mass processing of images. Another nice thing is that in some modes you don't need to give GraphicsMagic the needed size, just give maximums, and it will scale the picture down based on whichever constraint exceeds your given maximums. Check it out.

ddotsenko