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()
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)
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()
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: self.requested_size = (int(m.group(1)), int(m.group(2)))
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 self.opts = opts
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 ''