Commits

Christian Scholz committed e335add

added support for converting image to different filesizes

  • Participants
  • Parent commits ebd8ac4

Comments (0)

Files changed (1)

File adhocracy/lib/images.py

+import types
+import tempfile
+import os
+
+import quantumcore.media
+
+
+try:
+    import cStringIO as StringIO
+except ImportError:
+    import StringIO 
+
+class ImageSizer(object):
+    """this class holds functions for different sizes of images"""
+    
+    # default variants, valid keys are width, height and square.
+    default_variantdefs = {
+        "16" : dict(square=16),
+        "32" : dict(square=32),
+        "64" : dict(square=64),
+        "128" : dict(square=128),
+        "256" : dict(square=256),
+    }
+    
+    def __init__(self, filestore, variantdefs=None):
+        """initialize the class with the filestore object and an optional
+        dictionary with different image variants specifications. 
+        
+        """
+        self.filestore = filestore
+        if variantdefs is not None:
+            self.variantdefs = variantdefs
+        else:
+            self.variantdefs = self.default_variantdefs
+
+    def process(self, image, filename):
+        """process an image and create the sizes. Based on the filenames it
+        will create derivative filenames. E.g. filename ``user`` will become
+        ``user_thumb``, ``user_small`` etc.
+        """
+
+        # convert to file type if necessary
+        if type(image) in (types.StringType, types.UnicodeType):
+            image = StringIO.StringIO(image)
+
+        filename = unicode(filename) 
+        img = quantumcore.media.image.Image(image)
+
+        for name, spec in self.variantdefs.items():
+            if spec.has_key("square"):
+                x = spec['square']
+                img2 = img.fit(x,x).sharpen()
+            else:
+                img2 = img.scale(**spec)
+                
+            fno, tmpfilename = tempfile.mkstemp()
+            new_filename = u"%s_%s.png" %(filename, name)
+            
+            # now save the file and store it in the file store
+            # unfortunately PIL does not give us an fp (I think)
+            img2.image.save(tmpfilename, "PNG")
+            fp = open(tmpfilename, "rb")
+            self.filestore.delete(new_filename)
+            tfilename = self.filestore.add(fp, new_filename)
+            fp.close()
+            os.close(fno)
+            os.remove(tmpfilename)
+