Source

cmsplugin-nivoslider / cmsplugin_nivoslider / thumbnail_processors.py

# Solution found there:
# http://stackoverflow.com/questions/11960079/padded-fit-with-easy-thumbnails

import Image

def pad_image(image, **kwargs):
    'Pad an image to make it the same aspect ratio of the desired thumbnail.'

    img_size = image.size
    des_size = kwargs['size']
    fit = [float(img_size[i])/des_size[i] for i in xrange(0, 2)]

    if fit[0] > fit[1]:
        new_image = image.resize((image.size[0],
                                  int(round(des_size[1] * fit[0]))))
        top = int((new_image.size[1] - image.size[1])/2)
        left = 0
    elif fit[0] < fit[1]:
        new_image = image.resize((int(round(des_size[0] * fit[1])),
                                  image.size[1]))
        top = 0
        left = int((new_image.size[0] - image.size[0]) / 2)
    else:
        return image

    # For transparent
    #mask=Image.new('L', new_image.size, color=0)
    #new_image.putalpha(mask)

    # For black
    new_image.paste((0, 0, 0, 0))

    new_image.paste(image, (left, top))
    return new_image