Example #1
0
def thumbnails_for_file(relative_source_path, root=None, basedir=None,
                        subdir=None, prefix=None):
    """
    Return a list of dictionaries, one for each thumbnail belonging to the
    source image.

    The following list explains each key of the dictionary:

      `filename`  -- absolute thumbnail path
      `x` and `y` -- the size of the thumbnail
      `options`   -- list of options for this thumbnail
      `quality`   -- quality setting for this thumbnail
    """
    # Fall back to using thumbnail settings. These are local imports so that
    # there is no requirement of Django to use the utils module.
    if root is None:
        from django.conf import settings
        root = settings.MEDIA_ROOT
    if prefix is None:
        from populous.thumbnail.main import get_thumbnail_setting
        prefix = get_thumbnail_setting('PREFIX')
    if subdir is None:
        from populous.thumbnail.main import get_thumbnail_setting
        subdir = get_thumbnail_setting('SUBDIR')
    if basedir is None:
        from populous.thumbnail.main import get_thumbnail_setting
        basedir = get_thumbnail_setting('BASEDIR')
    source_dir, filename = os.path.split(relative_source_path)
    thumbs_path = os.path.join(root, basedir, source_dir, subdir)
    if not os.path.isdir(thumbs_path):
        return []
    files = all_thumbnails(thumbs_path, recursive=False, prefix=prefix,
                           subdir='')
    return files.get(filename, [])
Example #2
0
def all_thumbnails(path, recursive=True, prefix=None, subdir=None):
    """
    Return a dictionary referencing all files which match the thumbnail format.

    Each key is a source image filename, relative to path.
    Each value is a list of dictionaries as explained in `thumbnails_for_file`.
    """
    # Fall back to using thumbnail settings. These are local imports so that
    # there is no requirement of Django to use the utils module.
    if prefix is None:
        from populous.thumbnail.main import get_thumbnail_setting
        prefix = get_thumbnail_setting('PREFIX')
    if subdir is None:
        from populous.thumbnail.main import get_thumbnail_setting
        subdir = get_thumbnail_setting('SUBDIR')
    thumbnail_files = {}
    if not path.endswith('/'):
        path = '%s/' % path
    len_path = len(path)
    if recursive:
        all = os.walk(path)
    else:
        files = []
        for file in os.listdir(path):
            if os.path.isfile(os.path.join(path, file)):
                files.append(file)
        all = [(path, [], files)]
    for dir_, subdirs, files in all:
        rel_dir = dir_[len_path:]
        for file in files:
            thumb = re_thumbnail_file.match(file)
            if not thumb:
                continue
            d = thumb.groupdict()
            source_filename = d.pop('source_filename')
            if prefix:
                source_path, source_filename = os.path.split(source_filename)
                if not source_filename.startswith(prefix):
                    continue
                source_filename = os.path.join(source_path,
                    source_filename[len(prefix):])
            d['options'] = d['options'] and d['options'].split('_') or []
            if subdir and rel_dir.endswith(subdir):
                rel_dir = rel_dir[:-len(subdir)]
            # Corner-case bug: if the filename didn't have an extension but did
            # have an underscore, the last underscore will get converted to a
            # '.'.
            m = re.match(r'(.*)_(.*)', source_filename)
            if m:
                 source_filename = '%s.%s' % m.groups()
            filename = os.path.join(rel_dir, source_filename)
            thumbnail_file = thumbnail_files.setdefault(filename, [])
            d['filename'] = os.path.join(dir_, file)
            thumbnail_file.append(d)
    return thumbnail_files
Example #3
0
 def render(self, context):
     # Note that this isn't a global constant because we need to change the
     # value for tests.
     DEBUG = get_thumbnail_setting('DEBUG')
     try:
         # A file object will be allowed in DjangoThumbnail class
         relative_source = self.source_var.resolve(context)
     except VariableDoesNotExist:
         if DEBUG:
             raise VariableDoesNotExist("Variable '%s' does not exist." %
                     self.source_var)
         else:
             relative_source = None
     try:
         requested_size = self.size_var.resolve(context)
     except VariableDoesNotExist:
         if DEBUG:
             raise TemplateSyntaxError("Size argument '%s' is not a"
                     " valid size nor a valid variable." % self.size_var)
         else:
             requested_size = None
     # Size variable can be either a tuple/list of two integers or a valid
     # string, only the string is checked.
     else:
         if isinstance(requested_size, basestring):
             m = size_pat.match(requested_size)
             if m:
                 requested_size = (int(m.group(1)), int(m.group(2)))
             elif DEBUG:
                 raise TemplateSyntaxError("Variable '%s' was resolved but "
                         "'%s' is not a valid size." %
                         (self.size_var, requested_size))
             else:
                 requested_size = None
     if relative_source is None or requested_size is None:
         thumbnail = ''
     else:
         try:
             thumbnail = DjangoThumbnail(relative_source, requested_size,
                     opts=self.opts, processors=PROCESSORS, **self.kwargs)
         except:
             if DEBUG:
                 raise
             else:
                 thumbnail = ''
     # Return the thumbnail class, or put it on the context
     if self.context_name is None:
         return thumbnail
     # We need to get here so we don't have old values in the context
     # variable.
     context[self.context_name] = thumbnail
     return ''
Example #4
0
from populous.thumbnail.main import DjangoThumbnail, get_thumbnail_setting
from populous.thumbnail.processors import dynamic_import, get_valid_options

register = Library()

size_pat = re.compile(r'(\d+)x(\d+)$')
quality_pat = re.compile(r'quality=([1-9]\d?|100)$')

filesize_formats = ['k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']
filesize_long_formats = {
    'k': 'kilo', 'M': 'mega', 'G': 'giga', 'T': 'tera', 'P': 'peta',
    'E': 'exa', 'Z': 'zetta', 'Y': 'yotta'
}

try:
    PROCESSORS = dynamic_import(get_thumbnail_setting('PROCESSORS'))
    VALID_OPTIONS = get_valid_options(PROCESSORS)
except:
    if get_thumbnail_setting('DEBUG'):
        raise
    else:
        PROCESSORS = []
        VALID_OPTIONS = []

class ThumbnailNode(Node):
    def __init__(self, source_var, size_var, opts=None,
                 context_name=None, **kwargs):
        self.source_var = source_var
        self.size_var = size_var
        self.opts = opts
        self.context_name = context_name
Example #5
0
def get_thumbnail_path(path):
    basedir = get_thumbnail_setting('BASEDIR')
    subdir = get_thumbnail_setting('SUBDIR')
    return os.path.join(basedir, path, subdir)
Example #6
0
"""

import sys
import os
import re
from django.db import models
from django.conf import settings
from populous.thumbnail.main import get_thumbnail_setting

try:
    set
except NameError:
    from sets import Set as set     # For Python 2.3

THUMB_RE = re.compile(r'^%s(.*)_\d{1,}x\d{1,}_[-\w]*q([1-9]\d?|100)\.jpg' % 
                      get_thumbnail_setting('PREFIX'))

def get_thumbnail_path(path):
    basedir = get_thumbnail_setting('BASEDIR')
    subdir = get_thumbnail_setting('SUBDIR')
    return os.path.join(basedir, path, subdir)


def clean_up():
    paths = set()
    for app in models.get_apps():
        app_name = app.__name__.split('.')[-2]
        model_list = models.get_models(app)
        for model in model_list:
            for field in model._meta.fields:
                if isinstance(field, models.ImageField):
Example #7
0
import unittest
import os
import time

from PIL import Image
from django.conf import settings

from populous.thumbnail.base import Thumbnail
from populous.thumbnail.main import DjangoThumbnail, get_thumbnail_setting
from populous.thumbnail.processors import dynamic_import, get_valid_options
from populous.thumbnail.tests.base import BaseTest, RELATIVE_PIC_NAME, PIC_NAME, THUMB_NAME, PIC_SIZE


PROCESSORS = dynamic_import(get_thumbnail_setting("PROCESSORS"))
VALID_OPTIONS = get_valid_options(PROCESSORS)


class ThumbnailTest(BaseTest):
    def testThumbnails(self):
        # Thumbnail
        thumb = Thumbnail(source=PIC_NAME, dest=THUMB_NAME % 1, requested_size=(240, 240))
        self.verify_thumbnail((240, 180), thumb)

        # Cropped thumbnail
        thumb = Thumbnail(source=PIC_NAME, dest=THUMB_NAME % 2, requested_size=(240, 240), opts=["crop"])
        self.verify_thumbnail((240, 240), thumb)

        # Thumbnail with altered JPEG quality
        thumb = Thumbnail(source=PIC_NAME, dest=THUMB_NAME % 3, requested_size=(240, 240), quality=95)
        self.verify_thumbnail((240, 180), thumb)