import json
 import logging
 import os
+import StringIO
 
 from tornado.web import RequestHandler, HTTPError, asynchronous
+from PIL import Image
 
 import config
 import mediafiles
         
         else:
             content = mediafiles.get_media_content(camera_config, filename)
-            
-            # TODO add support for ?width=, ?height=
-        
             self.set_header('Content-Type', 'image/jpeg')
-            self.finish(content)
+            
+            width = self.get_argument('width', None)
+            height = self.get_argument('height', None)
+            
+            if width is None and height is None:
+                return self.finish(content)
+            
+            sio = StringIO.StringIO(content)
+            image = Image.open(sio)
+            
+            width = width and int(width) or image.size[0]
+            height = height and int(height) or image.size[1]
+
+            image.thumbnail((width, height), Image.ANTIALIAS)
+
+            image.save(self, format='JPEG')
+            self.finish()
 
 
 class MovieHandler(BaseHandler):
 
         var keys = Object.keys(groups);
         keys.sort();
         
+        /* add a temporary div to compute 3em in px */
+        var tempDiv = $('<div style="width: 3em; height: 3em;"></div>');
+        $('div.modal-container').append(tempDiv);
+        var height = tempDiv.height();
+        tempDiv.remove();
+        
         keys.forEach(function (key) {
             if (key) {
                 var groupDiv = $('<div class="media-list-group-title">' + key + '</div>');
             entries.forEach(function (entry, pos) {
                 var entryDiv = $('<div class="media-list-entry"></div>');
                 
-                var previewImg = $('<img class="media-list-preview" src="/' + mediaType + '/' + cameraId + '/preview' + entry.path + '"/>');
+                var previewImg = $('<img class="media-list-preview" src="/' + mediaType + '/' + cameraId + '/preview' + entry.path + '?height=' + height + '"/>');
                 entryDiv.append(previewImg);
                 
                 var downloadButton = $('<div class="media-list-download-button button">download</div>');