示例#1
0
    def __init__(self, source, requested_size, opts=None, quality=85,
                 dest=None, convert_path=defaults.CONVERT,
                 wvps_path=defaults.WVPS, processors=None):
        # Paths to external commands
        self.convert_path = convert_path
        self.wvps_path = wvps_path
        # Absolute paths to files
        self.source = source
        self.dest = dest
        self.type = type

        # Thumbnail settings
        self.requested_size = requested_size
        if not 0 < quality <= 100:
            raise TypeError('Thumbnail received invalid value for quality '
                            'argument: %s' % quality)
        self.quality = quality

        # Processors
        if processors is None:
            processors = dynamic_import(defaults.PROCESSORS)
        self.processors = processors

        # Set Thumbnail opt(ion)s
        VALID_OPTIONS = get_valid_options(processors)
        opts = opts or []
        # Check that all options received are valid
        for opt in opts:
            if not opt in VALID_OPTIONS:
                raise TypeError('Thumbnail received an invalid option: %s'
                                % opt)
        self.opts = [opt for opt in VALID_OPTIONS if opt in opts]

        if self.dest is not None:
            self.generate()
示例#2
0
    def __init__(self, relative_source, requested_size, opts=None,
                 quality=None, basedir=None, subdir=None, prefix=None,
                 relative_dest=None, processors=None):
        # Set the absolute filename for the source file
        source = self._absolute_path(relative_source)

        quality = get_thumbnail_setting('QUALITY', quality)
        convert_path = get_thumbnail_setting('CONVERT')
        wvps_path = get_thumbnail_setting('WVPS')
        if processors is None:
            processors = dynamic_import(get_thumbnail_setting('PROCESSORS'))

        # Call super().__init__ now to set the opts attribute. generate() won't
        # get called because we are not setting the dest attribute yet.
        super(DjangoThumbnail, self).__init__(source, requested_size,
            opts=opts, quality=quality, convert_path=convert_path,
            wvps_path=wvps_path, processors=processors)

        # Get the relative filename for the thumbnail image, then set the
        # destination filename
        if relative_dest is None:
            self.relative_dest = \
               self._get_relative_thumbnail(relative_source, basedir=basedir,
                                            subdir=subdir, prefix=prefix)
        else:
            self.relative_dest = relative_dest
        self.dest = self._absolute_path(self.relative_dest)

        # Call generate now that the dest attribute has been set
        self.generate()

        # Set the relative & absolute url to the thumbnail
        self.relative_url = \
            iri_to_uri('/'.join(self.relative_dest.split(os.sep)))
        self.absolute_url = '%s%s' % (settings.MEDIA_URL, self.relative_url)
示例#3
0
    def testFilenameGeneration(self):
        basename = RELATIVE_PIC_NAME.replace('.', '_')
        # Basic filename
        thumb = DjangoThumbnail(relative_source=RELATIVE_PIC_NAME,
                                requested_size=(240, 120))
        expected = os.path.join(settings.MEDIA_ROOT, basename)
        expected += '_240x120_q85.jpg'
        self.verify_thumbnail((160, 120), thumb, expected_filename=expected)

        # Changed quality and cropped
        thumb = DjangoThumbnail(relative_source=RELATIVE_PIC_NAME,
                                requested_size=(240, 120),
                                opts=['crop'],
                                quality=95)
        expected = os.path.join(settings.MEDIA_ROOT, basename)
        expected += '_240x120_crop_q95.jpg'
        self.verify_thumbnail((240, 120), thumb, expected_filename=expected)

        # All options on
        processors = dynamic_import(get_thumbnail_setting('PROCESSORS'))
        valid_options = get_valid_options(processors)

        thumb = DjangoThumbnail(relative_source=RELATIVE_PIC_NAME,
                                requested_size=(240, 120),
                                opts=valid_options)
        expected = (os.path.join(settings.MEDIA_ROOT, basename) + '_240x120_'
                    'autocrop_bw_crop_detail_max_sharpen_upscale_q85.jpg')
        self.verify_thumbnail((240, 120), thumb, expected_filename=expected)

        # Different basedir
        basedir = 'sorl-thumbnail-test-basedir'
        self.change_settings.change({'BASEDIR': basedir})
        thumb = DjangoThumbnail(relative_source=self.pic_subdir,
                                requested_size=(240, 120))
        expected = os.path.join(basedir, self.sub_dir, basename)
        expected += '_240x120_q85.jpg'
        self.verify_thumbnail((160, 120), thumb, expected_filename=expected)
        # Different subdir
        self.change_settings.change({'BASEDIR': '', 'SUBDIR': 'subdir'})
        thumb = DjangoThumbnail(relative_source=self.pic_subdir,
                                requested_size=(240, 120))
        expected = os.path.join(settings.MEDIA_ROOT,
                                os.path.basename(self.sub_dir), 'subdir',
                                basename)
        expected += '_240x120_q85.jpg'
        self.verify_thumbnail((160, 120), thumb, expected_filename=expected)
        # Different prefix
        self.change_settings.change({'SUBDIR': '', 'PREFIX': 'prefix-'})
        thumb = DjangoThumbnail(relative_source=self.pic_subdir,
                                requested_size=(240, 120))
        expected = os.path.join(self.sub_dir, 'prefix-' + basename)
        expected += '_240x120_q85.jpg'
        self.verify_thumbnail((160, 120), thumb, expected_filename=expected)
示例#4
0
文件: main.py 项目: modamania/otdohni
    def __init__(self,
                 relative_source,
                 requested_size,
                 opts=None,
                 quality=None,
                 basedir=None,
                 subdir=None,
                 prefix=None,
                 relative_dest=None,
                 processors=None,
                 extension=None):
        relative_source = force_unicode(relative_source)
        # Set the absolute filename for the source file
        source = self._absolute_path(relative_source)

        quality = get_thumbnail_setting('QUALITY', quality)
        convert_path = get_thumbnail_setting('CONVERT')
        wvps_path = get_thumbnail_setting('WVPS')
        if processors is None:
            processors = dynamic_import(get_thumbnail_setting('PROCESSORS'))

        # Call super().__init__ now to set the opts attribute. generate() won't
        # get called because we are not setting the dest attribute yet.
        super(DjangoThumbnail, self).__init__(source,
                                              requested_size,
                                              opts=opts,
                                              quality=quality,
                                              convert_path=convert_path,
                                              wvps_path=wvps_path,
                                              processors=processors)

        # Get the relative filename for the thumbnail image, then set the
        # destination filename
        if relative_dest is None:
            relative_dest = \
               self._get_relative_thumbnail(relative_source, basedir=basedir,
                                            subdir=subdir, prefix=prefix,
                                            extension=extension)
        filelike = not isinstance(relative_dest, basestring)
        if filelike:
            self.dest = relative_dest
        else:
            self.dest = self._absolute_path(relative_dest)

        # Call generate now that the dest attribute has been set
        self.generate()

        # Set the relative & absolute url to the thumbnail
        if not filelike:
            self.relative_url = \
                iri_to_uri('/'.join(relative_dest.split(os.sep)))
            self.absolute_url = '%s%s' % (settings.MEDIA_URL,
                                          self.relative_url)
示例#5
0
    def __init__(self,
                 source,
                 requested_size,
                 opts=None,
                 quality=85,
                 dest=None,
                 convert_path=defaults.CONVERT,
                 wvps_path=defaults.WVPS,
                 processors=None):
        # Paths to external commands
        self.convert_path = convert_path
        self.wvps_path = wvps_path
        # Absolute paths to files
        self.source = source
        self.dest = dest

        # Thumbnail settings
        try:
            x, y = [int(v) for v in requested_size]
        except (TypeError, ValueError):
            raise TypeError('Thumbnail received invalid value for size '
                            'argument: %s' % repr(requested_size))
        else:
            self.requested_size = (x, y)
        try:
            self.quality = int(quality)
            if not 0 < quality <= 100:
                raise ValueError
        except (TypeError, ValueError):
            raise TypeError('Thumbnail received invalid value for quality '
                            'argument: %r' % quality)

        # Processors
        if processors is None:
            processors = dynamic_import(defaults.PROCESSORS)
        self.processors = processors

        # Handle old list format for opts.
        opts = opts or {}
        if isinstance(opts, (list, tuple)):
            opts = dict([(opt, None) for opt in opts])

        # Set Thumbnail opt(ion)s
        VALID_OPTIONS = get_valid_options(processors)
        for opt in opts:
            if not opt in VALID_OPTIONS:
                raise TypeError('Thumbnail received an invalid option: %s' %
                                opt)
        self.opts = opts

        if self.dest is not None:
            self.generate()
示例#6
0
    def testFilenameGeneration(self):
        basename = RELATIVE_PIC_NAME.replace('.', '_')
        # Basic filename
        thumb = DjangoThumbnail(relative_source=RELATIVE_PIC_NAME,
                                requested_size=(240, 120))
        expected = os.path.join(settings.MEDIA_ROOT, basename)
        expected += '_240x120_q85.jpg'
        self.verify_thumbnail((160, 120), thumb, expected_filename=expected)

        # Changed quality and cropped
        thumb = DjangoThumbnail(relative_source=RELATIVE_PIC_NAME,
                                requested_size=(240, 120), opts=['crop'],
                                quality=95)
        expected = os.path.join(settings.MEDIA_ROOT, basename)
        expected += '_240x120_crop_q95.jpg'
        self.verify_thumbnail((240, 120), thumb, expected_filename=expected)

        # All options on
        processors = dynamic_import(get_thumbnail_setting('PROCESSORS'))
        valid_options = get_valid_options(processors)

        thumb = DjangoThumbnail(relative_source=RELATIVE_PIC_NAME,
                                requested_size=(240, 120), opts=valid_options)
        expected = (os.path.join(settings.MEDIA_ROOT, basename) + '_240x120_'
                    'autocrop_bw_crop_detail_max_sharpen_upscale_q85.jpg')
        self.verify_thumbnail((240, 120), thumb, expected_filename=expected)

        # Different basedir
        basedir = 'sorl-thumbnail-test-basedir'
        self.change_settings.change({'BASEDIR': basedir})
        thumb = DjangoThumbnail(relative_source=self.pic_subdir,
                                requested_size=(240, 120))
        expected = os.path.join(basedir, self.sub_dir, basename)
        expected += '_240x120_q85.jpg'
        self.verify_thumbnail((160, 120), thumb, expected_filename=expected)
        # Different subdir
        self.change_settings.change({'BASEDIR': '', 'SUBDIR': 'subdir'})
        thumb = DjangoThumbnail(relative_source=self.pic_subdir,
                                requested_size=(240, 120))
        expected = os.path.join(settings.MEDIA_ROOT,
                                os.path.basename(self.sub_dir), 'subdir',
                                basename)
        expected += '_240x120_q85.jpg'
        self.verify_thumbnail((160, 120), thumb, expected_filename=expected)
        # Different prefix
        self.change_settings.change({'SUBDIR': '', 'PREFIX': 'prefix-'})
        thumb = DjangoThumbnail(relative_source=self.pic_subdir,
                                requested_size=(240, 120))
        expected = os.path.join(self.sub_dir, 'prefix-' + basename)
        expected += '_240x120_q85.jpg'
        self.verify_thumbnail((160, 120), thumb, expected_filename=expected)
示例#7
0
    def __init__(self, source, requested_size, opts=None, quality=85,
                 dest=None, convert_path=defaults.CONVERT,
                 wvps_path=defaults.WVPS, processors=None):
        # Paths to external commands
        self.convert_path = convert_path
        self.wvps_path = wvps_path
        # Absolute paths to files
        self.source = source
        self.dest = dest

        # Thumbnail settings
        try:
            x, y = [int(v) for v in requested_size]
        except (TypeError, ValueError):
            raise TypeError('Thumbnail received invalid value for size '
                            'argument: %s' % repr(requested_size))
        else:
            self.requested_size = (x, y)
        try:
            self.quality = int(quality)
            if not 0 < quality <= 100:
                raise ValueError
        except (TypeError, ValueError):
            raise TypeError('Thumbnail received invalid value for quality '
                            'argument: %r' % quality)

        # Processors
        if processors is None:
            processors = dynamic_import(defaults.PROCESSORS)
        self.processors = processors

        # Handle old list format for opts.
        opts = opts or {}
        if isinstance(opts, (list, tuple)):
            opts = dict([(opt, None) for opt in opts])

        # Set Thumbnail opt(ion)s
        VALID_OPTIONS = get_valid_options(processors)
        for opt in opts:
            if not opt in VALID_OPTIONS:
                raise TypeError('Thumbnail received an invalid option: %s'
                                % opt)
        self.opts = opts

        if self.dest is not None:
            self.generate()
示例#8
0
    def __init__(self,
                 source,
                 requested_size,
                 opts=None,
                 quality=85,
                 dest=None,
                 convert_path=defaults.CONVERT,
                 wvps_path=defaults.WVPS,
                 processors=None):
        # Paths to external commands
        self.convert_path = convert_path
        self.wvps_path = wvps_path
        # Absolute paths to files
        self.source = source
        self.dest = dest
        self.type = type

        # Thumbnail settings
        self.requested_size = requested_size
        if not 0 < quality <= 100:
            raise TypeError('Thumbnail received invalid value for quality '
                            'argument: %s' % quality)
        self.quality = quality

        # Processors
        if processors is None:
            processors = dynamic_import(defaults.PROCESSORS)
        self.processors = processors

        # Set Thumbnail opt(ion)s
        VALID_OPTIONS = get_valid_options(processors)
        opts = opts or []
        # Check that all options received are valid
        for opt in opts:
            if not opt in VALID_OPTIONS:
                raise TypeError('Thumbnail received an invalid option: %s' %
                                opt)
        self.opts = [opt for opt in VALID_OPTIONS if opt in opts]

        if self.dest is not None:
            self.generate()
示例#9
0
    def __init__(self, relative_source, requested_size, opts=None,
                 quality=None, basedir=None, subdir=None, prefix=None,
                 relative_dest=None, processors=None, extension=None, storage_server=None):
        if not storage_server:
            storage_server = DefaultStorage()
        relative_source = force_unicode(relative_source)
        # Set the absolute filename for the source file
        with self._get_data_as_tempfile(relative_source, storage_server) as source:

            quality = get_thumbnail_setting('QUALITY', quality)
            convert_path = get_thumbnail_setting('CONVERT')
            wvps_path = get_thumbnail_setting('WVPS')
            if processors is None:
                processors = dynamic_import(get_thumbnail_setting('PROCESSORS'))

            # Call super().__init__ now to set the opts attribute. generate() won't
            # get called because we are not setting the dest attribute yet.
            super(DjangoThumbnail, self).__init__(source, requested_size,
                opts=opts, quality=quality, convert_path=convert_path,
                wvps_path=wvps_path, processors=processors)

            # Get the relative filename for the thumbnail image, then set the
            # destination filename
            if relative_dest is None:
                relative_dest = \
                   self._get_relative_thumbnail(relative_source.name, basedir=basedir,
                                                subdir=subdir, prefix=prefix,
                                                extension=extension)
            
            with NamedTemporaryFile() as dest:
                self.dest = dest.name
                
                self.generate()
                dest.seek(0)
                data = dest.read()
                f = StringIO(data)
                f.name = relative_dest
                f.size = len(data)
                self.relative_url = storage_server.save(relative_dest, File(f))
                self.absolute_url = os.path.join(settings.MEDIA_URL, self.relative_url)
示例#10
0
from sorl.thumbnail.main import DjangoThumbnail, get_thumbnail_setting
from sorl.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 = Variable(source_var)
        m = size_pat.match(size_var)
        if m:
示例#11
0
## Various templatetags for misc stuff
##

# python

# django
from django.utils import simplejson
from django import template
from django.conf import settings

from sorl.thumbnail.main import DjangoThumbnail, get_thumbnail_setting
from sorl.thumbnail.processors import dynamic_import, get_valid_options
thumbnail_processors = dynamic_import(get_thumbnail_setting('PROCESSORS'))

try:
    from django_static import slimfile, staticfile
except ImportError:
    from django_static.templatetags.django_static import slimfile, staticfile
    
from djangopeople.utils import uniqify
MAP_KEYS = settings.MAP_KEYS


register = template.Library()

@register.filter()
def uniqify_on(list_, on):
    return uniqify(list_, lambda x: getattr(x, on))

@register.filter()
def country_flag_src(iso_code):
示例#12
0
from sorl.thumbnail.main import DjangoThumbnail, get_thumbnail_setting
from sorl.thumbnail.processors import dynamic_import, get_valid_options
from sorl.thumbnail.utils import split_args

register = Library()

size_pat = re.compile(r'(\d+)x(\d+)$')

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 = []
TAG_SETTINGS = ['quality']


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
示例#13
0
# python
import logging

# django
from django.contrib import admin
from django.utils.translation import get_date_formats
from django.utils import dateformat

from sorl.thumbnail.main import DjangoThumbnail, get_thumbnail_setting
from sorl.thumbnail.processors import dynamic_import, get_valid_options
thumbnail_processors = dynamic_import(get_thumbnail_setting('PROCESSORS'))

# app
from models import KungfuPerson, Club, DiaryEntry, Style, Photo

(date_format, datetime_format, time_format) = get_date_formats()


class KungfuPersonAdmin(admin.ModelAdmin):
    list_display = ('user', 'join_date', 'full_name', 'email', 'profile_views',
                    'mugshot')

    def join_date(self, obj):
        return dateformat.format(obj.user.date_joined, datetime_format)

    def full_name(self, object_):
        return "%s %s" % (object_.user.first_name, object_.user.last_name)

    def email(self, object_):
        return object_.user.email
示例#14
0
size_pat = re.compile(r"(\d+)x(\d+)$")

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 = []
TAG_SETTINGS = ["quality"]


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
示例#15
0
def thumbnail(url, size='200x200',):
  """
  Given a URL (local or remote) to an image, creates a thumbnailed version of the image, saving
  it locally and then returning the URL to the new, smaller version. If the argument passed is a 
  single integer, like "200", will output a version of the image no larger than 200px wide. If the
  argument passed is two integers, like, "200x300", will output a cropped version of the image that
  is exactly 200px wide by 300px tall (cropped from the center).
  
    {{ story.get_leadphoto_url|thumbnail:"200" }}
    {{ story.get_leadphoto_url|thumbnail:"300x150" }}
  
  This filter is a wrapper around sorl-thumbnail that provides the remote image fetching, as well as
  backwards-compatibility with the previous Savoy thumbnail filter syntax.
  """
  import Image
  import os
  import urllib
  
  if not url == '':
    if not url.startswith(settings.MEDIA_URL):
      # If it's a remote image, download it and save it locally. This expects a
      # directory called img/thumbnailed in your MEDIA_ROOT
      download_filename = url.rsplit('/', 1)[1]                                               # Filename of image
      full_image_path = '%simg/thumbnailed/%s' % (settings.MEDIA_ROOT, download_filename)     # Local filesystem path where image should be saved
      relative_image_path = 'img/thumbnailed/%s' % (download_filename)                        # Path relative to MEDIA_ROOT
      local_image_url = '%simg/thumbnailed/%s' % (settings.MEDIA_URL, download_filename)      # Full URL to local copy of image
      if not os.path.exists(full_image_path):
        unsized_image = urllib.urlretrieve(url)                                               # Fetch original image
        insized_image = os.rename(unsized_image[0], full_image_path)                          # Move the image to the corect path.
      url = local_image_url
    else:
      full_image_path = _get_path_from_url(url)
      relative_image_path = full_image_path[len(settings.MEDIA_ROOT):]

    # Parse the size argument into tuples.
    try:
      # See if both height and width exist (i.e. "200x100")
      desired_width, desired_height = [int(x) for x in size.split('x')]
      new_size = (desired_width, desired_height)
      # Flag this image for cropping, since we want an explicit width AND height.
      crop = True
    except:
      # If only one exists ( i.e. "200"), use the value as the desired width. To do
      # this math, we need the original height of the image, so we must open the image.
      image = Image.open(_get_path_from_url(url))
      desired_width = int(size)
      new_size = (desired_width, image.size[1])
      crop = False
    DEBUG = get_thumbnail_setting('DEBUG')
    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 = []
    try:
      if crop:
        opts = ['crop']
      else:
        opts = None
      thumbnail = DjangoThumbnail(relative_image_path, new_size, opts=opts, processors=PROCESSORS, **{})
      return thumbnail.absolute_url
    except:
      if DEBUG:
        raise
      else:
        return ''
  else:
    return ''