Search code examples
pythondjangopython-2.7sorl-thumbnail

Python generate thumbnail with transparancy and fixed width


So i am trying to generate thumbnails using Python/Django sorl-thumbnail library and i was asked to generate a 150x150 image, something like this (in case you can't see there are some transparent margins on top and on the bottom:

Image to generate

I tried to do:

get_thumbnail(
            original_image, '150x150', quality=99, format='PNG'
        )

Can i do that with sorl-thumbnail?? i mean add the transparencies on the top and on the bottom and keeping the full image size at 150x150? If not how can i achieve this with another python package?

thanks


Solution

  • I am not sure about sorl-thumbnail but you can do it with Image. You basically need to create a transparent 150x150 image and put your thumbnail on top of it.

    #!/usr/bin/python
    
    from PIL import Image
    
    margin=20
    X=150
    Y=150
    in_path="flower.jpg"
    out_path="thumbnail.png"
    
    #creates a transparent background, RGBA mode, and size 150 by 150.
    background = Image.new('RGBA', (X,Y))
    
    
    # opening an image and converting to RGBA:
    img = Image.open(in_path).convert('RGBA')
    
    # Resizing the image
    
    img = img.resize((X, Y-margin*2), Image.ANTIALIAS)
    
    # Putting thumbnail on background
    
    background.paste(img, (0, margin), img)
    background.save(out_path)
    

    The output with transparent stripes at the top and bottom:

    enter image description here