[Image-SIG] PIL resize with aspect ratio?

Steve Holden steve at holdenweb.com
Fri Jan 6 08:25:03 CET 2006


Count László de Almásy wrote:
> Wonderful, thank-you, I adapted this to work for me.
> 
> On 1/5/06, Steve Holden <steve at holdenweb.com> wrote:
> 
>>Count László de Almásy wrote:
>>
>>>Thanks.  How about setting the JPEG compression setting?
>>>
>>>Conceptually what I'm trying to do is the following:
>>>
>>>Take an image file of arbitrary size and of arbitrary width and height,
>>>and rescale it to a width of exactly 500 and a height of whatever,
>>>as long as the aspect ratio is preserved.  Additionally, the rescaled
>>>image must be < 100kb in size, but I want to preserve as much
>>>quality as possible.  My thought was that if I could specify the
>>>JPEG compression ratio as I can with ImageMagick, I could start
>>>at a high value and iteratively go lower and lower until a rescaled
>>>image file is produced that is just under 100kb size.
>>>
>>
>>The scaling is relatively easy; here's a piece of code I use to ensure
>>that an image is at most 120 pixels wide:
>>
>>             im = Image.open(c)
>>             w, h = im.size
>>             if w > 120:
>>                 sf = 120.0/w
>>                 newsize = (120, int(h*sf))
>>                 im = im.resize(newsize)
>>
>>you can see I compute a scaling factor that will reduce the width to 120
>>pixels, and apply the same factor to both dimensions. Your code can be
>>similar.
>>
>>As far as the jpeg compression goes, you can use a "quality" keyword
>>argument to the image.save() operation to specify othe compression
>>ratio. I believe it can take values from 1 (worst) to 100 (best) and
>>defaults to 75. Hope this gives you enough to play with.
>>
>>regards
>>  Steve

Glad it worked out for you. Sorry I replied to you rather than the list.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC                     www.holdenweb.com
PyCon TX 2006                  www.python.org/pycon/


More information about the Image-SIG mailing list