Daily archive for 19th May 2010
1905/2010
PIL Image Handling
at 8:39 p.m. Be the first to comment.
Just playing around with Tornado Web Server and trying to make a twitter clone with realtime updates. I wanna share the ImageHandling snippet which requires Python Imaging Library module to resize images. BTW for PIL installation there are many valuable resources available on the web.
I will get the image from the form and the imghdr module is used to sniff the content type of the file. In this case, jpeg and png are the accepted file types. Here comes the interesting part, Instead of writing the image to the disk I am using StringIO module which reads the image from the memory. By this we are simulating a file object as expected by Image.open.
I want the image to be in three different sizes.
1. avatar_square the largest square of the uploaded image.
2. thumbnail size (48*48).
3. mininail size (24*24) to show the followers on the side as twitter.
class ImageHandler(BaseHandler): @tornado.web.authenticated def get(self): return self.render("image.html") @tornado.web.authenticated def post(self): user_id=self.current_user username = self.db.get("SELECT username from user WHERE id=%s", user_id) uploaded_image=self.request.files if imghdr.what('ignore', uploaded_image['avatar'][0]['body']) in ['jpeg','png']: avatar = Image.open(StringIO.StringIO(uploaded_image['avatar'][0]['body'])) width, height = avatar.size if width > height: delta = width - height left = int(delta/2) upper = 0 right = height + left lower = height else: delta = height - width left = int(delta)/2 upper = 0 right = width lower = width + upper avatar_square = avatar.crop((left, upper, right, lower)) avatar_mini = copy.copy(avatar_square) avatar_square.thumbnail((48,48)) avatar_mini.thumbnail((24,24)) return self.write("Successfully uploaded the image") else: return self.write("file format is not accepted")