def _build_thumbnail(self, args): # Build the DjangoThumbnail kwargs. kwargs = {} for k, v in args.items(): kwargs[ALL_ARGS[k]] = v # Build the destination filename and return the thumbnail. name_kwargs = {} for key in ['size', 'options', 'quality', 'basedir', 'subdir', 'prefix', 'extension']: name_kwargs[key] = args.get(key) source = getattr(self.instance, self.field.name) rotate = getattr(self,"rotate",None) if rotate: if name_kwargs.get("options"): name_kwargs["options"].update({"rotate":rotate}) else: name_kwargs["options"] = {"rotate":rotate} if kwargs.get("opts"): kwargs["opts"].update({"rotate":rotate}) else: kwargs["opts"] = {"rotate":rotate} dest = build_thumbnail_name(source.name, **name_kwargs) #print source,dest,kwargs return DjangoThumbnail(source, relative_dest=dest, **kwargs)
def photoreport_upload(request, photoreport_pk): if photoreport_pk: photoreport = get_object_or_404(PhotoReport.default_manager, pk=photoreport_pk) else: photoreport = None try: key = request.FILES['file'] if key: upload = PhotoReportUpload(zip_file=request.FILES['file'], photoreport=photoreport, title=photoreport.title) photo = upload.save() f = photo.image thumb = DjangoThumbnail(f, (100, 100)) data = [{ 'name': f.name, 'url': f.url, 'thumbnail_url': thumb.absolute_url, # 'thumbnail_url': settings.MEDIA_URL + "pictures/" + f.name.replace(" ", "_"), 'delete_url': "reverse('upload-delete', args=[self.object.id])", 'delete_type': "DELETE" }] response = JSONResponse(data, {}, response_mimetype(request)) response['Content-Disposition'] = 'inline; filename=files.json' return response except KeyError, E: if settings.DEBUG: raise (E) else: pass
def thumbnail(self): """ Used in list_display """ try: th = DjangoThumbnail(self.image.name, (100, 100)) return '<img src="%s" />' % th.absolute_url except: return ''
def _build_thumbnail(self, args): # Build kwargs kwargs = {} for k, v in args.items(): kwargs[ALL_ARGS[k]] = v # Return thumbnail relative_source_path = getattr(self.instance, self.field.name).name return DjangoThumbnail(relative_source_path, **kwargs)
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: kwargs = {} for key, value in self.kwargs.items(): kwargs[key] = value.resolve(context) opts = dict([(k, v and v.resolve(context)) for k, v in self.opts.items()]) thumbnail = DjangoThumbnail(relative_source, requested_size, opts=opts, processors=PROCESSORS, **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 ''
def wrapper(admin, obj): field = get_field(obj) if field: try: url = DjangoThumbnail(field, size).absolute_url except: url = '' return u'<img src="%s">' % url return u''
def testAlternateExtension(self): basename = RELATIVE_PIC_NAME.replace('.', '_') # Control JPG thumb = DjangoThumbnail(relative_source=RELATIVE_PIC_NAME, requested_size=(240, 120)) expected = os.path.join(settings.MEDIA_ROOT, basename) expected += '_240x120_q85.jpg' expected_jpg = expected self.verify_thumbnail((160, 120), thumb, expected_filename=expected) # Test PNG thumb = DjangoThumbnail(relative_source=RELATIVE_PIC_NAME, requested_size=(240, 120), extension='png') expected = os.path.join(settings.MEDIA_ROOT, basename) expected += '_240x120_q85.png' self.verify_thumbnail((160, 120), thumb, expected_filename=expected) # Compare the file size to make sure it's not just saving as a JPG with # a different extension. self.assertNotEqual(os.path.getsize(expected_jpg), os.path.getsize(expected))
def testUnicodeName(self): unicode_name = 'sorl-thumbnail-ążśź_source.jpg' unicode_path = os.path.join(settings.MEDIA_ROOT, unicode_name) Image.new('RGB', PIC_SIZE).save(unicode_path) self.images_to_delete.add(unicode_path) thumb = DjangoThumbnail(relative_source=unicode_name, requested_size=(240, 120)) base_name = unicode_name.replace('.', '_') expected = os.path.join(settings.MEDIA_ROOT, base_name + '_240x120_q85.jpg') self.verify_thumbnail((160, 120), thumb, expected_filename=expected)
def _get_thumbnail(model_instance, field, attrs): # Build kwargs kwargs = {} for k, v in attrs.items(): kwargs[ALL_ARGS[k]] = v # Build relative source path filename = getattr(model_instance, 'get_%s_filename' % field.name)() media_root_len = len(os.path.normpath(settings.MEDIA_ROOT)) filename = os.path.normpath(filename) filename = filename[media_root_len:].lstrip(os.path.sep) # Return thumbnail return DjangoThumbnail(filename, **kwargs)
def _build_thumbnail(self, args): # Build the DjangoThumbnail kwargs. kwargs = {} for k, v in args.items(): kwargs[ALL_ARGS[k]] = v # Build the destination filename and return the thumbnail. name_kwargs = {} for key in [ 'size', 'options', 'quality', 'basedir', 'subdir', 'prefix', 'extension' ]: name_kwargs[key] = args.get(key) source = getattr(self.instance, self.field.name) dest = build_thumbnail_name(source.name, **name_kwargs) return DjangoThumbnail(source, relative_dest=dest, **kwargs)
def thumbnail(self, object_): relative_source = object_.photo requested_size = (40, 40) opts = [] try: thumbnail = DjangoThumbnail(relative_source, requested_size, opts=opts, processors=thumbnail_processors, **{}) thumbnail_url = thumbnail.absolute_url except: logging.error('grr', exc_info=True) return 'error' return '<img src="%s"/>' % thumbnail_url
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 _nearby_people_escape(person): """return the person like this {'latitude':<latitude>, 'longitude':<longitude>, 'fullname':<full name>, #'username':<username>, 'location_description':<location_description>, 'photo_thumbnail_url':<photo thumnail url>, 'country_iso_code': <country iso code lowercase>, 'clubs':[{'name':<name>, 'url':<url within this site>}, ...], 'styles':[{'name':<name>, 'url':<url within this site>}, ...], } ...escaped for javascript. """ data = dict( latitude=person.latitude, longitude=person.longitude, fullname=unicode(person), #username=person.user.username, user_url=person.get_absolute_url(), location_description=person.location_description, ) if person.photo: thumbnail = DjangoThumbnail(person.photo, (60, 60), opts=['crop'], processors=thumbnail_processors) data['photo_thumbnail_url'] = thumbnail.absolute_url else: data['photo_thumbnail_url'] = staticfile("/img/upload-a-photo-60.png") data['country_iso_code'] = person.country.iso_code.lower() data['clubs'] = [] for club in person.club_membership.all(): data['clubs'].append({ 'name': club.name, 'url': club.get_absolute_url() }) _optimize_nearby_person_keys(data) return simplejson.dumps(data)
def get_all_items(model, sort_by): qs = {'clubs': Club, 'styles': Style, 'people': KungfuPerson, 'photos': Photo, }[model].objects.all() if model == 'people': qs = qs.select_related('user') elif model == 'photos': qs = qs.select_related('country','user') if sort_by == 'date': order_by = {'clubs':'-date_added', 'styles':'-date_added', 'people':'-user__date_joined', 'photos':'-date_added', }[model] else: # by name order_by = {'clubs':'name', 'styles':'name', 'people':('user__first_name', 'user__last_name'), 'photos':('location_description', 'country__name'), }[model] if isinstance(order_by, basestring): order_by = (order_by,) qs = qs.order_by(*order_by) count = qs.count() page_title = u"All %s %s" % (count, model) title = "All %s %s on this site so far" % (count, model) # now, turn this queryset into a list of _ListItems _today = datetime.datetime.today() counts_cache_key = 'all-counts-%s' % model counts = cache.get(counts_cache_key, {}) items = [] for item in qs: if model == 'people': if item.photo: thumbnail = DjangoThumbnail(item.photo, (40,40), opts=['crop'], processors=thumbnail_processors) thumbnail_url = thumbnail.absolute_url else: thumbnail_url = gravatar_thumbnail_url(item.user.email, size=40) #thumbnail_url = staticfile('/img/upload-a-photo-40.png') thumbnail_size = (40, 40) info = 'joined %s ago' % timesince(item.user.date_joined, _today) items.append(_ListItem( item.get_absolute_url(), item.user.get_full_name(), info=info, thumbnail_url=thumbnail_url, thumbnail_size=thumbnail_size, )) elif model == 'photos': if not os.path.isfile(os.path.join(settings.MEDIA_ROOT, item.photo.path)): logging.info("Photo id=%s is missing the photo itself!" %\ item.id) continue thumbnail = DjangoThumbnail(item.photo, (40,40), opts=['crop'], processors=thumbnail_processors) thumbnail_url = thumbnail.absolute_url thumbnail_size = (40,40) if item.description: _title = truncate_words(item.description, 10) else: _title = '' _title = ' %s, %s' % (item.location_description, item.country.name) #if item.description: # title = truncate_words(item.description, 10) #else: # title = '' info = 'Added by <a href="/%s/">%s</a>' % (item.user.username, item.user.get_full_name()) info += ' %s ago' % timesince(item.date_added, _today) items.append(_ListItem( item.get_absolute_url(), _title.strip(), info=info, thumbnail_url=thumbnail_url, thumbnail_size=thumbnail_size, )) elif model in ('clubs','styles'): if item.id in counts: people_count = counts[item.id] else: people_count = item.kungfuperson_set.count() counts[item.id] = people_count if people_count: if people_count > 1: info = '%s people' % people_count else: info = '1 person' else: info = 'added %s ago' % timesince(item.date_added, _today) items.append(_ListItem( item.get_absolute_url(), item.name, info=info, )) cache.set(counts_cache_key, counts, ONE_HOUR) return dict(items=items, page_title=page_title, title=title)
def thumbnail(image_path): t = DjangoThumbnail(relative_source=image_path, requested_size=(80,80)) return u'<img src="%s" alt="%s" />' % (t.absolute_url, image_path)
def file_thumbnail_medium(self): # TODO: subclass DjangoThumbnail to remove UUID from URL if DjangoThumbnail: return DjangoThumbnail(self.file.name, (600, 600))
def file_thumbnail_small(self): # TODO: subclass DjangoThumbnail to remove UUID from URL if DjangoThumbnail: return DjangoThumbnail(self.file.name, (200, 200))