PIL: thumbnail and ends with a square image

Call

image = Image.open(data) image.thumbnail((36,36), Image.NEAREST) 

will maintain aspect ratio. But I need to display the image as follows:

 <img src="/media/image.png" style="height:36px; width:36px" /> 

Can I have a mailbox style with transparent or white color around the image?

+47
python png thumbnails alpha python-imaging-library
Sep 06 '09 at 18:33
source share
4 answers

Insert the image into a transparent image with the desired size as the background

 from PIL import Image size = (36, 36) image = Image.open(data) image.thumbnail(size, Image.ANTIALIAS) background = Image.new('RGBA', size, (255, 255, 255, 0)) background.paste( image, (int((size[0] - image.size[0]) / 2), int((size[1] - image.size[1]) / 2)) ) background.save("output.png") 

EDIT: fixed syntax error

+66
Sep 06 '09 at 18:45
source share

PIL already has a function that does just that:

 from PIL import Image, ImageOps thumb = ImageOps.fit(image, size, Image.ANTIALIAS) 
+131
Dec 12 '11 at 4:25
source share
 from PIL import Image import StringIO def thumbnail_image(): image = Image.open("image.png") image.thumbnail((300, 200)) thumb_buffer = StringIO.StringIO() image.save(thumb_buffer, format=image.format) fp = open("thumbnail.png", "w") fp.write(thumb_buffer.getvalue()) fp.close() 
+2
Jul 28 '16 at 8:30
source share

Or this, maybe ... (sorry spaghetti)

 from PIL import Image def process_image(image, size): if image.size[0] > size[0] or image.size[1] > size[1]: #preserve original thumb = image.copy() thumb.thumbnail(size,Image.ANTIALIAS) img = thumb.copy() img_padded = Image.new("RGBA",size) img_padded.paste(image,(int((size[0]-image.size[0])/2),int((size[1]-image.size[1])/2))) return img_padded 
+1
Jan 31 '15 at 2:26
source share



All Articles