Profile image for Mirat Bayrak mcbayrak
PIL's image thumbnailing function is keeping ratio. That is forcing images to be given size. Written by Emre Yılmaz.
Language
Python
Tags
pil python
Favorited By
Profile image for Joshua Canfield Profile image for emre  yılmaz Profile image for Ian Lewis Profile image for Carly Ho Profile image for Christian Schulze Profile image for eriko koide

Thumbnail function thats force images to be given size

1 import glob 2 from PIL import Image 3 4 class SmartThumbnail: 5 # file (string) , target (string), maxSizes (tuple) 6 def __init__(self, file, target, maxSizes): 7 self.file = file 8 self.target = target 9 self.maxSizes = maxSizes 10 11 def createThumb(self): 12 self.im = Image.open(self.file) 13 14 # birtakim hesaplamalar 15 orig_width, orig_height = self.im.size 16 if orig_width > maxSizes[0] and orig_height > maxSizes[1]: 17 thumb_width, thumb_height = self.maxSizes 18 orig_ratio, thumb_ratio = float(orig_width) / float(orig_height), float(thumb_width) / float(thumb_height) 19 20 if thumb_ratio < orig_ratio: 21 crop_height = orig_height 22 crop_width = crop_height * thumb_ratio 23 x_offset = float(orig_width - crop_width) / 2 24 y_offset = 0 25 else: 26 crop_width = orig_width 27 crop_height = crop_width / thumb_ratio 28 x_offset = 0 29 y_offset = float(orig_height - crop_height) / 3 30 31 # crop it 32 self.im = self.im.crop((x_offset, y_offset, x_offset+int(crop_width), y_offset+int(crop_height))) 33 self.im = self.im.resize((thumb_width, thumb_height), Image.ANTIALIAS) 34 self.im.save(self.target) 35 36 return self.im 37 else: 38 pass 39 40 images = glob.glob("*.jpg") 41 for image in images: 42 th = SmartThumbnail(image, image, (800, 600)) 43 th.createThumb()

Comments