开发者

Need to create thumbnail, how to ensure proportions and set fixed width?

开发者 https://www.devze.com 2023-01-10 10:35 出处:网络
I want to create 开发者_如何学Pythona thumbnail, and the width has to be either fixed or no bigger than 200 pixels wide (the length can be anything).

I want to create 开发者_如何学Pythona 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.


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)


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消