Commits

Anonymous committed f84f961

All working for me now

  • Participants
  • Parent commits c6cd0d9
  • Branches smiley-refactor

Comments (0)

Files changed (2)

thumbnail/base.py

-from os.path import isfile, getmtime
+from os import makedirs
+from os.path import isfile, isdir, getmtime, dirname
 
 from PIL import Image, ImageFilter
 
 class ThumbnailException(Exception):
     pass
 
-class Thumbnail:
-    def __init__(self, source_path, thumbnail_path, size, quality=85, **kwargs):
+class Thumbnail(object):
+    def __init__(self, source_path, thumbnail_path, size, quality=85,
+                 generate_thumbnail=True, **kwargs):
         # Full file paths
         self.source_path = source_path
         self.thumbnail_path = thumbnail_path
             if k not in options:
                 raise TypeError('Thumbnail received an invalid keyword argument: %s' % k)
             options[k] = v
-        for k, v in options:
-            setattr(k, bool(v))
+        for k, v in options.items():
+            setattr(self, k, bool(v))
 
         if not isfile(self.source_path):
             raise ThumbnailException('Source image file does not exist')
+        if generate_thumbnail:
+            self.generate_thumbnail()
 
+    def generate_thumbnail(self):
         if not isfile(self.thumbnail_path) or \
                 getmtime(self.source_path) > getmtime(self.thumbnail_path):
             self.make_thumbnail()
+            return True
+        return False
 
     def _get_thumbnail(self):
         if hasattr(self, '_thumbnail'):
         if self.sharpen:
             im = im.filter(ImageFilter.SHARPEN)
 
+        # Ensure the directory exists.
+        directory = dirname(self.thumbnail_path)
+        if not isdir(directory):
+            makedirs(directory)
+
         try:
             im.save(self.thumbnail_path, "JPEG", quality=self.quality,
                     optimize=1)

thumbnail/main.py

 
 from django.conf import settings
 from django.utils.encoding import iri_to_uri
+from django.utils.safestring import mark_safe
+from django.utils.html import urlquote
 
-from main import Thumbnail, OPTIONS
+from base import Thumbnail, OPTIONS
 
 class DjangoThumbnail(Thumbnail):
     # filename_format is passed the following string options:
     #   `quality`   -- the quality of the image
     #   `options`   -- a list of any non-default settings, each starting with an
     #                  underscore
-    filename_format = '%s(directory)s/%(basename)s%(options)s_q%(quality)s.jpg'
+    filename_format = '%(directory)s/%(basename)s_%(x)sx%(y)s%(options)s_q%(quality)s.jpg'
     root = settings.MEDIA_ROOT
     base_url = settings.MEDIA_URL
 
     def __init__(self, relative_source_path, *args, **kwargs):
         self.relative_source_path = relative_source_path
-        source_path = self._absolute_path(source_path)
-        thumbnail_path = self._absolute_path(self.relative_thumbnail_path)
-        super(DjangoThumbnail, self).__init__(source_path, thumbnail_path,
+        source_path = self._absolute_path(relative_source_path)
+        super(DjangoThumbnail, self).__init__(source_path, '',
+                                              generate_thumbnail=False,
                                               *args, **kwargs)
+        # Bit of a work-around here. The dynamic thumbnail name needs to be
+        # generated after the super __init__ so that the options are 
+        self.thumbnail_path = self._absolute_path(self.relative_thumbnail_path)
+        self.generate_thumbnail()
 
     def _absolute_path(self, path):
-        return os.path.join(self.root, source_path).encode('utf-8')
+        return os.path.join(self.root, path).encode(settings.FILE_CHARSET)
 
-    def _get_relative_thumbnail_path(self, source_path):
+    def _get_relative_thumbnail_path(self):
         if hasattr(self, '_relative_thumbnail_path'):
             return self._relative_thumbnail_path
-        source_dir, source_filename = os.path.split(source_path)
+        source_dir, source_filename = os.path.split(self.relative_source_path)
         base, ext = os.path.splitext(source_filename)
         if ext.lower() == '.jpg':
             basename = base
         else:
             basename = source_filename
-        thumbs_dir = os.path.join(self.root, filehead, self.subdir)
-        if not os.path.isdir(thumbs_dir):
-            os.mkdir(thumbs_dir)
 
-        options = ['_%s' % option for option in OPTIONS if getattr(self, m)]
+        options = ['_%s' % option for option in OPTIONS if getattr(self, option)]
         filename_opts = dict(
             filename=source_filename,
             basename=basename,
             quality=self.quality,
             options=''.join(options)
         )
-
         self._relative_thumbnail_path = self.filename_format % filename_opts
         return self._relative_thumbnail_path
     relative_thumbnail_path = property(_get_relative_thumbnail_path)
         bits = self.relative_thumbnail_path.split(os.path.sep)
         return iri_to_uri('%s%s' % (self.base_url, '/'.join(bits)))
     url = property(_get_url)
+
+    def __unicode__(self):
+        return urlquote(self.url)
+
+    def img_tag(self):
+        html = '<img src="%s" width="%s" height="%s" alt="" />'
+        size = self.thumbnail.size
+        return mark_safe(html % (urlquote(self.url), size[0], size[1]))