Search code examples
pythondjangopython-imaging-librarypinax

django-photologue: How to scale image to box and fill background


I´m using django-photologue (with 1pinax) and want to scale images to a box (100px x 100px). Portrait images should be scaled to height 100px and the width should be filled with a color.


Solution

  • You can use PIL with a transformation matrix. For example, the following function resize and crop in a single operation. Personally I prefer to crop rather than fill it with a color, but you can adjust it to your needs.

    def resize_and_crop(im, mask_width=1000, mask_height=1000):
        width, height = im.size
        aspect = 1.0*width/height
        mask_aspect = 1.0*mask_width/mask_height
        if width != mask_width or height != mask_height:
            if aspect > mask_aspect:
                ratio = 1.0*height/mask_height
                imt = im.transform((mask_width, mask_height), 
                                    Image.AFFINE, 
                                   (ratio, 0, (width-mask_width*ratio)/2, 0, ratio, 0),
                                   Image.CUBIC)
            else:
                ratio = 1.0*width/mask_width
                imt = im.transform((mask_width, mask_height), 
                                   Image.AFFINE, 
                                   (ratio, 0, 0, 0, ratio, (height-mask_height*ratio)/2),
                                   Image.CUBIC)
        else:
            imt = im
        return imt