[Image-SIG] PIL resize with aspect ratio?

kevin at cazabon.com kevin at cazabon.com
Fri Jan 6 08:21:39 CET 2006

Here's a quick-and-dirty function to do the same.  The difference is that
Thumbnail modifies the image in place, while this returns a new image.
There is also the "fit" function in the ImageChops module that is a LOT more

def maxSize(image, maxSize, method = 3):
    """ im = maxSize(im, (maxSizeX, maxSizeY), method = Image.BICUBIC)

    Resizes a PIL image to a maximum size specified while maintaining
    the aspect ratio of the image.  Similar to Image.thumbnail(), but allows
    usage of different resizing methods and does NOT modify the image in

    imAspect = float(image.size[0])/float(image.size[1])
    outAspect = float(maxSize[0])/float(maxSize[1])

    if imAspect >= outAspect:
        #set to maxWidth x maxWidth/imAspect
        return image.resize((maxSize[0], int((float(maxSize[0])/imAspect) +
0.5)), method)
        #set to maxHeight*imAspect x maxHeight
        return image.resize((int((float(maxSize[1])*imAspect) + 0.5),
maxSize[1]), method)

----- Original Message ----- 
From: "Count László de Almásy" <calmasy at gmail.com>
To: "Chris Cogdon" <chris at cogdon.org>
Cc: <image-sig at python.org>
Sent: Thursday, January 05, 2006 11:35 PM
Subject: Re: [Image-SIG] PIL resize with aspect ratio?

I'm actually using resize() instead of thumbnail() in the code I'm writing,
but I think the idea is the same, right?

I'm color blind, so it's not as easy for me as most to distinguish such
fine details by eye, but I think I'll use ANTIALIAS.

On 1/5/06, Chris Cogdon <chris at cogdon.org> wrote:
> On Jan 5, 2006, at 14:25, Count László de Almásy wrote:
> > Thanks so much, I had missed the 'quality' attribute.  BTW, is
> > 'ANTIALIAS' the best choice for what I want to do?  I noticed the
> > docs mention the following:
> >
> > "The BILINEAR and BICUBIC filters use a fixed input environment, and
> > are best used for scale-preserving geometric transforms and upsamping"
> >
> > which seems like it suits rescaling while maintaining aspect ratio as
> > I am doing.
> I've found that ANTIALIAS results in much better thumbnails, and will
> probably produce better looking results when scaling down. The others I
> suspect will work well when scaling up.
> Best way... try it out and see :)
> --
>     ("`-/")_.-'"``-._        Chris Cogdon <chris at cogdon.org>
>      . . `; -._    )-;-,_`)
>     (v_,)'  _  )`-.\  ``-'
>    _.- _..-_/ / ((.'
> ((,.-'   ((,/   fL
Image-SIG maillist  -  Image-SIG at python.org

More information about the Image-SIG mailing list