I am taking an image file and thumbnailing and cropping it with the following PIL code:
image = Image.open(filename)
image.thumbnail(size, Image.
I altered the code just a bit to allow for you to specify your own background color, including transparency. The code loads the image specified into a PIL.Image object, generates the thumbnail from the given size, and then pastes the image into another, full sized surface. (Note that the tuple used for color can also be any RGBA value, I have just used white with an alpha/transparency of 0.)
# assuming 'import from PIL *' is preceding
thumbnail = Image.open(filename)
# generating the thumbnail from given size
thumbnail.thumbnail(size, Image.ANTIALIAS)
offset_x = max((size[0] - thumbnail.size[0]) / 2, 0)
offset_y = max((size[1] - thumbnail.size[1]) / 2, 0)
offset_tuple = (offset_x, offset_y) #pack x and y into a tuple
# create the image object to be the final product
final_thumb = Image.new(mode='RGBA',size=size,color=(255,255,255,0))
# paste the thumbnail into the full sized image
final_thumb.paste(thumbnail, offset_tuple)
# save (the PNG format will retain the alpha band unlike JPEG)
final_thumb.save(filename,'PNG')
Its a bit easier to paste
your re-sized thumbnail image onto a new image, that is the colour (and alpha value) you want.
You can create an image, and speicfy its colour in a RGBA
tuple like this:
Image.new('RGBA', size, (255,0,0,255))
Here there is there is no transparency as the alpha band is set to 255. But the background will be red. Using this image to paste onto we can create thumbnails with any colour like this:
If we set the alpha band to 0
, we can paste
onto a transparent image, and get this:
Example code:
import Image
image = Image.open('1_tree_small.jpg')
size=(50,50)
image.thumbnail(size, Image.ANTIALIAS)
# new = Image.new('RGBA', size, (255, 0, 0, 255)) #without alpha, red
new = Image.new('RGBA', size, (255, 255, 255, 0)) #with alpha
new.paste(image,((size[0] - image.size[0]) / 2, (size[1] - image.size[1]) / 2))
new.save('saved4.png')