def setUp(self): super(FilesTest, self).setUp() self.storage = test.TemporaryStorage() self.remote_storage = test.FakeRemoteStorage() # Save a test image in both storages. filename = self.create_image(self.storage, 'test.jpg') self.thumbnailer = files.get_thumbnailer(self.storage, filename) self.thumbnailer.thumbnail_storage = self.storage filename = self.create_image(self.remote_storage, 'test.jpg') self.remote_thumbnailer = files.get_thumbnailer(self.remote_storage, filename) self.remote_thumbnailer.thumbnail_storage = self.remote_storage # Create another thumbnailer for extension test. self.ext_thumbnailer = files.get_thumbnailer(self.storage, filename) self.ext_thumbnailer.thumbnail_storage = self.storage # Generate test transparent images. filename = self.create_image(self.storage, 'transparent.png', image_mode='RGBA', image_format='PNG') self.transparent_thumbnailer = files.get_thumbnailer(self.storage, filename) self.transparent_thumbnailer.thumbnail_storage = self.storage filename = self.create_image(self.storage, 'transparent-greyscale.png', image_mode='LA', image_format='PNG') self.transparent_greyscale_thumbnailer = files.get_thumbnailer( self.storage, filename) self.transparent_greyscale_thumbnailer.thumbnail_storage = self.storage
def photo_thumb(self): if settings.RUNNING_DEVSERVER: return '<img src="http://192.168.56.101:5000/%s">' % get_thumbnailer(self.photo)['medium'].url img = '<img src="http://conserte.me/%s">' % get_thumbnailer(self.photo)['medium'].url img += '<img src="http://alphastage.conserte.me/%s">' % get_thumbnailer(self.photo)['medium'].url return img
def get_comic_panels(request, comic_id, direction, hdpi_enabled): """Ajaxtastic catacombs browsing magic.""" comic = Comic.objects.get(pk=comic_id) size = 'midsize_hd' if hdpi_enabled else 'midsize' if comic: comic_obj = { 'panel1' : get_thumbnailer(comic.panel1)[size].url, 'panel2' : get_thumbnailer(comic.panel2)[size].url, 'panel3' : get_thumbnailer(comic.panel3)[size].url, 'comic_id' : comic.id, 'first_name' : comic.artist.first_name, 'last_name' : comic.artist.last_name, 'name' : comic.artist.name, 'url' : comic.artist.url, } else: comic_obj = {} # store comic_id for /contribute/ request.session['last_comic_id'] = comic_id return simplejson.dumps({ 'direction' : direction, 'comic' : comic_obj })
def save(self, *args, **kwargs): imagenes = ProductoImagen.objects.filter(producto=self.producto).count() if not self.orden: if not imagenes == 0: self.orden = imagenes self.thum = get_thumbnailer(self.foto)['prod_thum'].url self.thum_small = get_thumbnailer(self.foto)['prod_small'].url self.thum_medio = get_thumbnailer(self.foto)['prod_medio'].url super(ProductoImagen, self).save(*args, **kwargs)
def render(self, name, value, attrs=None, renderer=None): final_attrs = self.build_attrs(attrs) element_id = final_attrs.get('id') kwargs = {'upload_to': self.upload_to, 'max_width': self.max_width, 'max_height': self.max_height, 'crop': self.crop} upload_url = reverse('ajaximage', kwargs=kwargs) # NB convert to string and do not rely on value.url # value.url fails when rendering form with validation errors because # form value is not a FieldFile. Use storage.url and file_path - works # with FieldFile instances and string formdata #file_path = str(value) if value else '' #file_url = default_storage.url(file_path) if value else '' #file_name = os.path.basename(file_url) #output = self.html.format(upload_url=upload_url, # file_url=file_url, # file_name=file_name, # file_path=file_path, # element_id=element_id, # name=name) #INICIO thumbs para fields ajaximage# #modificado também self.html# file_path = str(value) if value else '' file_url = hasattr(value, 'url') and value.url or value or '' file_name = os.path.basename(file_url) if value and self.upload_to == 'fotos': thumb_url = static(get_thumbnailer(value)['admin_imovel_fieldsets'].url) foto_url = static(get_thumbnailer(value)['imovel_fotos'].url) if value and self.upload_to == 'slides': thumb_url = static(get_thumbnailer(value)['admin_slides_thumb'].url) foto_url = static(file_url) output = self.html.format( upload_url=upload_url, file_url=file_url and thumb_url or file_url, file_name=file_name and foto_url or file_url, file_path=file_path, element_id=element_id, name=name) #FIM# return mark_safe(output)
def test_get_existing(self): options = settings.THUMBNAIL_ALIASES[""]["small"] # Pregenerate the thumbnail. get_thumbnailer(self.storage, self.filename).get_thumbnail(options) src = "{% with t=filename|thumbnailer_passive %}" "{{ t.small.url }}{% endwith %}" output = self.render_template(src) expected = self.verify_thumbnail((20, 20), options) expected_url = "".join((settings.MEDIA_URL, expected)) self.assertEqual(output, expected_url)
def _avatar_thumbnail(self, size, crop='0,0'): """Return a String, containing a path to a thumbnail-image.""" if self.uploaded_image: thumbnailer = get_thumbnailer(self.uploaded_image) thumbnail = thumbnailer.get_thumbnail({'quality': 90, 'size': (size[0], 0)}) else: file_name = self.uploaded_image or self.image or 'avatar/default.png' thumbnailer = get_thumbnailer(self.avatar_storage, file_name) thumbnail = thumbnailer.get_thumbnail({'size': size, 'quality': 90, 'crop': crop}) return os.path.join(settings.MEDIA_URL, thumbnail.url)
def square_thumbnail(self, source): from django.db.models.fields.files import FieldFile from easy_thumbnails.files import get_thumbnailer if isinstance(source, FieldFile): nailer = get_thumbnailer(source) # caches the thumbnail else: # should be a File-like object at least. No caching. nailer = get_thumbnailer(source, relative_name=source.name) return nailer.get_thumbnail(self.thumbnail_options)
def images(self, instance): images = [] domain = Site.objects.get_current().domain # main image (select in admin) if instance.main_image: main_image = [] sized_image = {} for k in IMAGE_BASE_SIZES: v = IMAGE_BASE_SIZES[k] # print k, v opt = dict(size=(v, v), crop=True, bw=False, quality=80) image = get_thumbnailer(instance.main_image).get_thumbnail(opt) sized_image[k] = 'http://' + domain + image.url images.append(sized_image) # images from objects 'picture' folder if instance.folder: folder = instance.get_folder('pictures') folder_images = folder.files.instance_of(Image) for folder_image in folder_images: main_image = [] sized_image = {} for k in IMAGE_BASE_SIZES: v = IMAGE_BASE_SIZES[k] # print k, v opt = dict(size=(v, v), crop=True, bw=False, quality=80) image = get_thumbnailer(folder_image).get_thumbnail(opt) if image is not instance.main_image: sized_image[k] = 'http://' + domain + image.url images.append(sized_image) if len(images) < 1: return False return images
def as_dict(self): d = super(File, self).as_dict() d.update({ 'file': self.file.url, 'thumbnails': { 'x-small': get_thumbnailer(self.file)['x-small'].url, 'small': get_thumbnailer(self.file)['small'].url, 'medium': get_thumbnailer(self.file)['medium'].url, 'large': get_thumbnailer(self.file)['large'].url } }) return d
def getdict_safe(self): adict = {'fields': {}, 'pk': self.id} adict['fields']['pk'] = self.id adict['fields']['is_safe'] = True adict['fields']['item_type'] = self.item_type adict['fields']['item_type_display'] = self.item_type_display adict['fields']['interests'] = [ob.id for ob in self.interests.all()] adict['fields']['title'] = self.title adict['fields']['pub_date'] = str(self.pub_date) adict['fields']['owner'] = [self.owner.username] adict['fields']['ownerid'] = [self.owner.id] adict['fields']['url'] = self.url adict['fields']['commentcount'] = self.commentcount adict['fields']['collaboratorcount'] = self.collaboratorcount adict['fields']['hidden'] = False adict['fields']['stick'] = False adict['fields']['avatar'] = False adict['fields']['hasEdit'] = False adict['fields']['close_url'] = "" adict['fields']['unpublish_url'] = "" adict['fields']['edit_url'] = "" adict['fields']['report_url'] = "" adict['fields']['attributes_url'] = "" adict['fields']['translate_language_url'] = "" adict['fields']['tweet_permission'] = self.tweet_permission if hasattr(self, 'image_url') and self.image_url is not None: try: thumbnailer = get_thumbnailer(self.image_url) adict['fields']['image_url'] = thumbnailer.get_thumbnail({'size': (66, 66), 'upscale': True, 'crop': '0, 0', 'background': '#FFFFFF'}).url except Exception as ex: _logger.exception(ex) adict['fields']['image_url'] = False elif self.item_type == MarketItem.TYPE_CHOICES.NEWS: if hasattr(self, 'marketnewsitemdata') and self.marketnewsitemdata.image_field: try: thumb = get_thumbnailer(self.marketnewsitemdata.image_field) adict['fields']['image_url'] = thumb.get_thumbnail({'size': (66, 66), 'upscale': True, 'crop': '0, 0', 'background': '#FFFFFF'}).url except Exception as ex: _logger.exception(ex) adict['fields']['image_url'] = False else: adict['fields']['image_url'] = False else: adict['fields']['image_url'] = False return adict
def getDoubleBackProjectCover(inVal,imageVersion): maxRang = len(inVal) a = 0 out = [] while a < maxRang: inVal[a].cover_image_link = get_thumbnailer(inVal[a].cover_image.image)[imageVersion].url a += 1 if(a<maxRang): inVal[a].cover_image_link = get_thumbnailer(inVal[a].cover_image.image)[imageVersion].url out.append((inVal[a-1],inVal[a])) else: out.append((inVal[a-1],None)) a += 1 return out
def dehydrate(self, bundle): bundle.data['edit_url'] = bundle.obj.get_edit_url() bundle.data['item_count'] = bundle.obj.items.count() # somehow needed to get data as json... bundle.data['broadcast_status_messages'] = bundle.obj.broadcast_status_messages # a bit hackish maybe, provide uuids of all items in playlist items = bundle.obj.get_items() item_uuids = [] for item in items: item_uuids.append(item.content_object.uuid) bundle.data['item_uuids'] = item_uuids bundle.data['main_image'] = None try: opt = THUMBNAIL_OPT main_image = get_thumbnailer(bundle.obj.main_image).get_thumbnail(opt) bundle.data['main_image'] = main_image.url except: pass #bundle.data['reorder_url'] = bundle.obj.get_reorder_url(); return bundle
def get_box_bg_cropped(self): """ Returns the box bg with proper size """ return make_absolute_url( get_thumbnailer(self.box_bg).get_thumbnail({ 'size': (585, 618), 'crop': True}).url)
def test_change_avatar_removes_the_old_one(client): url = reverse('users-change-avatar') user = f.UserFactory() with NamedTemporaryFile(delete=False) as avatar: avatar.write(DUMMY_BMP_DATA) avatar.seek(0) user.photo = File(avatar) user.save() generate_all_aliases(user.photo, include_global=True) with NamedTemporaryFile(delete=False) as avatar: thumbnailer = get_thumbnailer(user.photo) original_photo_paths = [user.photo.path] original_photo_paths += [th.path for th in thumbnailer.get_thumbnails()] assert all(list(map(os.path.exists, original_photo_paths))) client.login(user) avatar.write(DUMMY_BMP_DATA) avatar.seek(0) post_data = {'avatar': avatar} response = client.post(url, post_data) assert response.status_code == 200 assert not any(list(map(os.path.exists, original_photo_paths)))
def get_featured_picture_cropped(self): """ Returns the box bg with proper size """ return make_absolute_url( get_thumbnailer(self.featured_picture).get_thumbnail({ 'size': (1280, 512), 'crop': True}).url)
def admin_thumb(obj, photo): output = [ u'<style>', u'.field-admin_thumbnail a{display: block; text-align: center}', u'.field-admin_thumbnail a img{display: inline-block;}', u'</style>', ] if obj.admin_thumb: output.append(u'<img src="%s" />' % obj.admin_thumb.url) return u''.join(output) else: if photo: try: # an image Image.open(photo) thumbnailer = get_thumbnailer(photo) thumbnailer_options = ({'size': (100, 100), 'crop': False}) thumb_file = thumbnailer.get_thumbnail(thumbnailer_options) # save resulting thumb to admin thumb # self.admin_thumb = thumb_file obj.admin_thumb.save(thumb_file.name, thumb_file) obj.save() output.append(u'<img src="%s" />' % thumb_file.url) return u''.join(output) except IOError: # not image return 'not an image' else: return 'нет изображения'
def get_photo_thumb(self): return get_thumbnailer(self.photo).get_thumbnail({ 'size': (65, 65), 'box': self.photo_thumb, 'crop': True, 'detail': True, }).url
def img_src(self): # we want the external picture to take priority by design # please open a ticket if you disagree for an open discussion if self.external_picture: return self.external_picture # picture can be empty, for example when the image is removed from filer # in this case we want to return an empty string to avoid #69 elif not self.picture: return '' # return the original, unmodified picture elif self.use_no_cropping: return self.picture.url picture_options = self.get_size( width=self.width or 0, height=self.height or 0, ) thumbnail_options = { 'size': picture_options['size'], 'crop': picture_options['crop'], 'upscale': picture_options['upscale'], 'subject_location': self.picture.subject_location, } thumbnailer = get_thumbnailer(self.picture) return thumbnailer.get_thumbnail(thumbnail_options).url
def get_photo_url(photo): """Get a photo absolute url and the photo automatically cropped.""" try: url = get_thumbnailer(photo)['avatar'].url return get_absolute_url(url) except InvalidImageFormatError as e: return None
def test_update_project_logo(client): user = f.UserFactory.create(is_superuser=True) project = f.create_project() url = reverse("projects-change-logo", args=(project.id,)) with NamedTemporaryFile(delete=False) as logo: logo.write(DUMMY_BMP_DATA) logo.seek(0) project.logo = File(logo) project.save() generate_all_aliases(project.logo, include_global=True) thumbnailer = get_thumbnailer(project.logo) original_photo_paths = [project.logo.path] original_photo_paths += [th.path for th in thumbnailer.get_thumbnails()] assert all(list(map(os.path.exists, original_photo_paths))) with NamedTemporaryFile(delete=False) as logo: logo.write(DUMMY_BMP_DATA) logo.seek(0) client.login(user) post_data = {'logo': logo} response = client.post(url, post_data) assert response.status_code == 200 assert not any(list(map(os.path.exists, original_photo_paths)))
def get_banner(self): options = {'size': (1030, 410), } try: thumbnail = get_thumbnailer(self.banner).get_thumbnail(options) return thumbnail.url except InvalidImageFormatError: return '' # we could return a nice grey image
def get_big_photo_url(photo): """Get a big photo absolute url and the photo automatically cropped.""" try: url = get_thumbnailer(photo)[settings.THN_AVATAR_BIG].url return get_absolute_url(url) except InvalidImageFormatError as e: return None
def dehydrate(self, bundle): if(bundle.obj.station and bundle.obj.station.main_image): opt = dict(size=(70, 70), crop=True, bw=False, quality=80) try: main_image = get_thumbnailer(bundle.obj.station.main_image).get_thumbnail(opt) bundle.data['main_image'] = main_image.url except: bundle.data['main_image'] = None else: bundle.data['main_image'] = None """ Generate stream settings """ stream = { 'file': 'lala', 'rtmp_app': 'lala', 'rtmp_host': 'lala', #'uri': 'http://pypo:8000/obp-dev-256.mp3', 'uri': bundle.obj.get_stream_url(), 'uuid': bundle.obj.uuid, } bundle.data['stream'] = stream bundle.data['stream_url'] = bundle.obj.get_stream_url() bundle.data['images'] = [] bundle.data['media'] = None return bundle
def get_logo_thumbnail(self): options = {'size': (180, 100), } try: thumbnail = get_thumbnailer(self.logo).get_thumbnail(options) return thumbnail.url except InvalidImageFormatError: return '' # we could return a nice grey image
def get_thumbnail_url(self, image: str, option_key: str) -> str: """ Images can be either very large images or even pdf files. Create an optimized thumbnail and return its url. """ if not image: return '' # full name is required to prevent a SuspiciousOperation error full_name = '{root}/{image}'.format( root=settings.MEDIA_ROOT, image=image[len(settings.MEDIA_URL):] ) try: thumbnail = get_thumbnailer(full_name).get_thumbnail( settings.THUMBNAIL_ALIASES['summary'][self.quality][option_key], silent_template_exception=True ) except InvalidImageFormatError: return '' # Use 'abspath' to remove '..' from path. media_path = os.path.abspath(settings.MEDIA_ROOT) # Strip away the media folder info - only the last part is required for the url. file_path = thumbnail.url[thumbnail.url.find(media_path) + len(media_path):] return f'{self.base_url.rstrip("/")}{settings.MEDIA_URL}{file_path}'
def photos_set(self, obj): pics = ["<ul>", "</ul>"] size = settings.THUMB_MEDIUM for photo in obj.photos: thumb = get_thumbnailer(photo.photo)[size].url pics.insert(-1, '<li class="horizontal">' '<img src="{}"></li>'.format(thumb)) return "".join(pics)
def autocomplete_dehydrate(self, bundle, q): bundle.data['name'] = bundle.obj.name bundle.data['id'] = bundle.obj.pk bundle.data['target_duration'] = bundle.obj.target_duration bundle.data['tags'] = bundle.obj.d_tags bundle.data['ct'] = 'playlist' bundle.data['get_absolute_url'] = bundle.obj.get_absolute_url() bundle.data['resource_uri'] = bundle.obj.get_api_url() bundle.data['type'] = bundle.obj.get_type_display() bundle.data['status'] = bundle.obj.get_status_display() try: bundle.data['user'] = bundle.obj.user.get_ful__l_name() except: bundle.data['user'] = bundle.obj.user.username bundle.data['main_image'] = None try: opt = THUMBNAIL_OPT main_image = get_thumbnailer(bundle.obj.main_image).get_thumbnail(opt) bundle.data['main_image'] = main_image.url except: pass media_list = [] try: for item in bundle.obj.items.all(): media_list.append({'name': item.content_object.name, 'artist': item.content_object.artist.name}) except Exception, e: print e
def _get_thumb(self, image, size=(300, 300)): thumbnailer = get_thumbnailer(image) thumb = thumbnailer.get_thumbnail({ 'crop': True, 'size': size }) return thumb
def read(self, request, item_pk=None): p = get_object_or_404(Product.objects.select_related(), pk=item_pk) stockitems = StockItem.objects.filter(product=p).order_by('sale_price', 'price') product = { 'title': p.title, 'description': p.description, 'sizes': [], 'category': p.category.name, } if p.images.count() > 0: if p.thumbnail.image_file: thumbnail_file = p.thumbnail.image_file thumbnail_options = dict(size=(ITEM_THUMBNAIL_MAX_WIDTH, ITEM_THUMBNAIL_MAX_HEIGHT)) thumbnail = get_thumbnailer(thumbnail_file).get_thumbnail(thumbnail_options) product['image'] = thumbnail.url else: product['image'] = None else: product['image'] = None items = list(stockitems) for item in items: if item.on_sale: price = item.sale_price else: price = item.price product['sizes'].append((item.id, "%s, $%s" % (item.package_title, price))) return product
def hotspot_thumbnail(self, request, instance_pk): thumb = error = None image_field = request.GET['image_field'] instance_pk = int(instance_pk) instance = get_object_or_404(self.model, pk=instance_pk) if bool(request.GET.get('inline', u'false')): # strip off first fk _, image_field = image_field.split('__', 1) field = instance try: for field_name in image_field.split('__'): if field: field = getattr(field, field_name) if field is None: error = u'Please set an image (%s) in %s.' % (image_field, self.model) break except AttributeError: logger.error("Could not resolve ImageField %s for %s(pk=%d)." % (image_field, unicode(self.model), instance_pk)) raise Http404() if field: if not isinstance(field, ImageFieldFile): logger.error("%s is not an ImageField." % (image_field)) raise Http404() thumbnailer = get_thumbnailer(field) thumbnail_options = { 'detail': True, 'size': getattr(settings, 'HOTSPOT_THUMB_SIZE', (300, 300)), } thumb = thumbnailer.get_thumbnail(thumbnail_options) return render_to_response('hotspots/thumbnail.html', { 'thumbnail': thumb, 'error': error, }, context_instance=RequestContext(request))
def _get_thumb(self, image, size=(300, 300)): """ Returns the thumbnail of the media file base on the size privoded Parameter --------- image : Image The image to be thumbnailed size : tuple Width and height of the thumbnail, defaults to 300 by 300 Returns ------- Image The thumbnail """ thumbnailer = get_thumbnailer(image) thumb = thumbnailer.get_thumbnail({'crop': True, 'size': size}) return thumb
def verify_thumbnail(self, expected_size, options, source_filename=None, transparent=False): if source_filename is None: source_filename = self.filename self.assertTrue(isinstance(options, dict)) # Verify that the thumbnail file exists thumbnailer = get_thumbnailer(self.storage, source_filename) expected_filename = thumbnailer.get_thumbnail_name( options, transparent=transparent) self.assertTrue( self.storage.exists(expected_filename), 'Thumbnail file %r not found' % expected_filename) # Verify the thumbnail has the expected dimensions image = Image.open(self.storage.open(expected_filename)) self.assertEqual(image.size, expected_size) return expected_filename
def image_tag(self): if self.pk is None: return "" # May be empty inline. if not hasattr(self, "ext") or not hasattr(self, "doc"): raise Exception("Property ext or doc is not defined") if self.ext not in self.IMAGE_EXTENSIONS: return "" options = {"size": (100, 100), "crop": True} try: thumb_url = get_thumbnailer(self.doc) \ .get_thumbnail(options).url except InvalidImageFormatError: return "" return "<img src='{path}'/>".format(path=thumb_url)
def render(self, context, instance, placeholder): context['instance'] = instance tmp_projects = Project.objects.filter( is_active=True).order_by('position') projects = [] for pro in tmp_projects: thumbnail = get_thumbnailer(pro.image)['project'].url p = { 'name': pro.name, 'description': pro.description, 'url': pro.url, 'image': pro.image, 'thumbnail': thumbnail } projects.append(p) context['projects'] = projects return context
def preview(cls, file_obj): from easy_thumbnails.files import get_thumbnailer from easy_thumbnails.templatetags.thumbnail import data_uri available_name = cls.storage.get_available_name(file_obj.name) temp_name = cls.storage.save(available_name, file_obj) thumbnailer = get_thumbnailer(cls.storage.path(temp_name), relative_name=available_name) thumbnail = thumbnailer.generate_thumbnail( app_settings.THUMBNAIL_OPTIONS) return { 'url': 'url({})'.format(data_uri(thumbnail)), 'temp_name': cls.signer.sign(temp_name), 'file_name': file_obj.name, 'file_size': file_obj.size, 'charset': file_obj.charset, 'content_type': file_obj.content_type, 'content_type_extra': file_obj.content_type_extra, }
def get_points(items): result = {} result['type'] = 'FeatureCollection' feature_list = [] for item in items: image_url = '' comment_count = '' positive_rating_count = '' negative_rating_count = '' if hasattr(item, 'image') and item.image: image = get_thumbnailer(item.image)['map_thumbnail'] image_url = image.url if hasattr(item, 'comment_count'): comment_count = item.comment_count if hasattr(item, 'positive_rating_count'): positive_rating_count = item.positive_rating_count if hasattr(item, 'negative_rating_count'): negative_rating_count = item.negative_rating_count if hasattr(item, 'category') and getattr(item.category, 'icon', None): category_icon = get_category_pin_url(item.category.icon) else: category_icon = '' properties = { 'name': item.name, 'slug': item.slug, 'image': image_url, 'comments_count': comment_count, 'positive_rating_count': positive_rating_count, 'negative_rating_count': negative_rating_count, 'url': item.get_absolute_url(), 'category_icon': category_icon } point_dict = item.point point_dict['properties'] = properties feature_list.append(point_dict) result['features'] = feature_list return json.dumps(result)
def autocomplete_name_dehydrate(self, bundle, q): bundle.data['name'] = bundle.obj.name bundle.data['id'] = bundle.obj.pk bundle.data['ct'] = 'release' bundle.data['releasedate'] = bundle.obj.releasedate bundle.data['artist'] = bundle.obj.get_artists() bundle.data['media_count'] = bundle.obj.media_release.count() bundle.data['get_absolute_url'] = bundle.obj.get_absolute_url() bundle.data['resource_uri'] = bundle.obj.get_api_url() bundle.data['main_image'] = None try: opt = THUMBNAIL_OPT main_image = get_thumbnailer( bundle.obj.main_image).get_thumbnail(opt) bundle.data['main_image'] = main_image.url except: pass return bundle
def _relativise(value, activity, constraint=None): new_start = 0 result = '' for m in re.finditer(r'<img src="(.*?)".*?>', value): new_src = activity.attachment_url(m.group(1)) if constraint: media_root = settings.MEDIA_ROOT if media_root[:-1] != '/': media_root += '/' path = new_src.replace(settings.MEDIA_URL, media_root) thumbnailer = get_thumbnailer(path) resized = thumbnailer.get_thumbnail(contraint) new_src = resized.url result += value[new_start:m.start()] + '<img src="%s"/>' % new_src new_start = m.end() result += value[new_start:] result = mark_safe(result) return result
def test_article_detail_show_featured_image(self): author = self.create_person() with open(FEATURED_IMAGE_PATH, 'rb') as f: file_obj = DjangoFile(f, name='featured_image.jpg') image = Image.objects.create( owner=author.user, original_filename='featured_image.jpg', file=file_obj, subject_location='fooobar') article = self.create_article(author=author, featured_image=image) response = self.client.get(article.get_absolute_url()) image_url = get_thumbnailer(article.featured_image).get_thumbnail({ 'size': (800, 450), 'crop': True, 'subject_location': article.featured_image.subject_location }).url self.assertContains(response, image_url)
def image_thumbnail(image, size): """ Returns the thumbnail to a given image field in the required size, or None if no image is provided @param size: Tuple of sizes, e.g. (80, 80) """ if not image: return None thumbnailer = get_thumbnailer(image) try: thumbnail = thumbnailer.get_thumbnail({ 'crop': True, 'upscale': True, 'size': size, }) return thumbnail except InvalidImageFormatError: if settings.DEBUG: raise return None
def search(request): ''' Searches for exercises. This format is currently used by the exercise search autocompleter ''' q = request.GET.get('term', None) results = [] json_response = {} if q: languages = load_item_languages(LanguageConfig.SHOW_ITEM_EXERCISES, language_code=request.GET.get( 'language', None)) exercises = (Exercise.objects.filter(name__icontains=q).filter( language__in=languages).filter( status=Exercise.STATUS_ACCEPTED).order_by( 'category__name', 'name').distinct()) for exercise in exercises: if exercise.main_image: image_obj = exercise.main_image image = image_obj.image.url t = get_thumbnailer(image_obj.image) thumbnail = t.get_thumbnail(aliases.get('micro_cropped')).url else: image = None thumbnail = None exercise_json = { 'value': exercise.name, 'data': { 'id': exercise.id, 'name': exercise.name, 'category': _(exercise.category.name), 'image': image, 'image_thumbnail': thumbnail } } results.append(exercise_json) json_response['suggestions'] = results return Response(json_response)
def avatar_img_for_user(user, size=None, *args, **kwargs): context = avatar_for_user(user, size, *args, **kwargs) if context["profile"]: try: thumbnailer = get_thumbnailer(context["profile"].mugshot) except InvalidImageFormatError: return gravatar_img_for_user(user, size) thumbnail_options = {'size': (context["width"], context["height"])} thumbnail = thumbnailer.get_thumbnail(thumbnail_options) context.update({ "thumbnail_url": thumbnail.url, "username": user.username, }) html = """<img src="{thumbnail_url}" title="Avatar for {username}" alt="Avatar for {username}" height="{height}" width="{width}">""".format(**context) return html else: return gravatar_img_for_user(user, size)
def render(self, name, value, attrs=None): """Renders a thumbnail of the image with controls to clear/change it. If no image exists just an image upload widget is rendered. If an image has already been uploaded a thumbnail will be shown. The thumbnail's width and/or height are defined by the size kwarg given to the constructor. In addition a checkbox to delete the image is added. """ substitutions = { 'initial_text': self.initial_text, 'input_text': self.input_text, 'clear_template': '', 'clear_checkbox_label': self.clear_checkbox_label, } template = u'%(input)s' substitutions['input'] = super(forms.ClearableFileInput, self).render(name, value, attrs) if value and hasattr(value, 'url'): template = self.template_with_initial initial = u'<a href="%(url)s"><img src="%(img_url)s" alt="%(alt)s" /></a>' thumbnail = get_thumbnailer(value).get_thumbnail( {'size': self.size}) initial_substitutions = { 'url': escape(value.url), 'img_url': u'%s/%s' % (settings.MEDIA_URL, escape(thumbnail)), 'alt': _(u'avatar') } substitutions['initial'] = initial % initial_substitutions if not self.is_required: checkbox_name = self.clear_checkbox_name(name) checkbox_id = self.clear_checkbox_id(checkbox_name) substitutions['clear_checkbox_name'] = conditional_escape( checkbox_name) substitutions['clear_checkbox_id'] = conditional_escape( checkbox_id) substitutions['clear'] = forms.CheckboxInput().render( checkbox_name, False, attrs={'id': checkbox_id}) substitutions[ 'clear_template'] = self.template_with_clear % substitutions return mark_safe(template % substitutions)
def dehydrate(self, bundle): if bundle.obj.station and bundle.obj.station.main_image: opt = dict(size=(70, 70), crop=True, bw=False, quality=80) try: main_image = get_thumbnailer( bundle.obj.station.main_image).get_thumbnail(opt) bundle.data['main_image'] = main_image.url except: bundle.data['main_image'] = None else: bundle.data['main_image'] = None on_air = bundle.obj.get_on_air() bundle.data['on_air'] = on_air """ generate stream settings """ if (bundle.obj.rtmp_app and bundle.obj.rtmp_path) or bundle.obj.stream_url: stream = { 'file': '%s.stream' % bundle.obj.rtmp_path, 'rtmp_app': '%s' % bundle.obj.rtmp_app, 'rtmp_host': 'rtmp://%s:%s/' % (settings.RTMP_HOST, settings.RTMP_PORT), # 'uri': 'http://pypo:8000/obp-dev-256.mp3', 'uri': bundle.obj.stream_url, 'uuid': bundle.obj.uuid, } else: stream = {'error': _('stream data not defined')} bundle.data['stream'] = stream bundle.data['stream_url'] = bundle.obj.stream_url bundle.data['images'] = [] bundle.data['media'] = None return bundle
def save(self, *args, **kwargs): """ We want to do dimension checks and/or resizing BEFORE the original image is saved. Note that if we can't get image dimensions, it's considered an invalid image and we return without saving. If the image has changed, sets self.thumb to None, triggering post_save thumbnailer. """ img = self.image # Check if this is an already existing photo try: old_self = self.__class__.objects.get(id=self.id) except: old_self = None # Run on new and changed images: if self.id is None or self.thumb is None or (old_self.image != img): try: height = img.height width = img.width except Exception, inst: # We aren't dealing with a reliable image, so.... print "Error saving... Unable to get image height or width: %s" % inst return # If image is vertical or square (treated as vertical)... if height >= width: self.vertical = True if width > 900 or height > 1200: """ The image is larger than we want. We're going to downsize it BEFORE it is saved, using PIL on the InMemoryUploadedFile. """ image = Image.open(img) image.resize((900, 1200), Image.ANTIALIAS) image.save(img.path) try: ezthumb_field = get_thumbnailer(self.image) self.thumb = ezthumb_field.get_thumbnail({ 'size': (80, 80), 'crop': ',-10' }).url.replace("\\", "/") except Exception, inst: print "Error thumbnailing %s: %s" % (self.id, inst)
def form_valid(self, form): # Save the image self.content_object = form.save() f = self.request.FILES.get(self.field_name) image = getattr(self.content_object, self.field_name) size = getattr(settings, 'USER_MEDIA_THUMB_SIZE_LARGE', (150, 150)) # Generate and get the thumbnail of the uploaded image thumbnailer = get_thumbnailer(image.name) thumb = thumbnailer.get_thumbnail({ 'crop': True, 'upscale': True, 'size': size, }) # Prepare context for the list item html context_data = { 'image': image, 'mode': 'single', 'size': (self.request.POST.get('size') or u'{}x{}'.format(size[0], size[1])), } context = RequestContext(self.request, context_data) # Prepare the json response data = { 'files': [{ 'name': f.name, 'url': image.url, 'thumbnail_url': thumb.url, 'list_item_html': render_to_string(self.template_name, context), }] } response = HttpResponse(dumps(data), content_type='application/json') response['Content-Disposition'] = 'inline; filename=files.json' return response
def politician_view(request, politician_id): politician = get_object_or_404( Politician.objects.filter(statistic__id__gt=0).distinct(), pk=politician_id) answers = (Answer.objects.filter( politician=politician).order_by('question__question_number')) links = (Link.objects.filter(politician=politician)) cookie = get_cookie(request, 'answers', {}) answer_obs = [] for a in answers: answer_obs.append({ 'own_ans': cookie.get('question_%s' % a.question.id, None), 'politician_ans': a }) embed_url_reverse = reverse('politician_statistic_spider_embed', kwargs={'politician_id': politician_id}) embed_url_absolute = request.build_absolute_uri(embed_url_reverse) meta = Meta( title=u'{0} {1}'.format(politician.first_name, politician.last_name), image=get_thumbnailer(politician.image)['large'].url if politician.image else None, description=_("%(first_name)s %(last_name)s on Freedomvote") % { 'first_name': politician.first_name, 'last_name': politician.last_name }, url=request.build_absolute_uri( reverse('politician', kwargs={'politician_id': politician.id}))) return render( request, 'core/profile/index.html', { 'politician': politician, 'answers': answer_obs, 'links': links, 'embed_url': embed_url_absolute, 'meta': meta, 'base_url': settings.BASE_URL })
def prepare_image(image): """ Helper to display the main image, with a focus point as set in the form. Args: image: dict Returns: dict """ # The aspect ratio is optimized for nn screens. This should be set to match # the box with the default screen resolution (according to piwik). size = (1800, 900) if image.get('absolute_path') and image.get('target'): # Create a thumbnailer instance (file-like object) and create its # thumbnail according to the options. # Return the thumbnails url and overwrite the interchange-dict. try: thumbnailer = get_thumbnailer( image['absolute_path']).get_thumbnail({ 'size': size, 'crop': size, 'upscale': True, 'target': image['target'] }) url = get_url_by_file_name(thumbnailer.name.rsplit('/')[-1]) interchange = list(replace_large(image.get('interchange'), url)) except InvalidImageFormatError: interchange = image.get('interchange') url = image.get('image') else: interchange = image.get('interchange') url = image.get('image') return { 'interchange': ','.join(interchange) if isinstance(interchange, list) else interchange, 'src': url }
def to_representation(self, img): if img: data = {'uri': img.url} try: data['size'] = (img.width, img.height) except FileNotFoundError: logger.warning('File not found: %s' % img.path) data['size'] = None else: if self.thumbnails: data['thumbnails'] = {} thbn = get_thumbnailer(img) for alias in self.thumbnails: try: data['thumbnails'][alias] = thbn.get_thumbnail( settings.THUMBNAIL_ALIASES[''][alias], generate=False).url except AttributeError: pass return data
def get_thumbnail(self, size): try: thumbnailer = get_thumbnailer(self.thumbnail) # The thumbnail sizes were defined to have the same ratio in # all formats: width/height = 1.648 sizes = { 'very-big': (1030, 625), 'big': (570, 346), 'primary': (570, 346), 'secondary': (275, 167), 'facebook': (600, 364) } thumbnail_options = { 'crop': 'smart', 'size': sizes[size], 'upscale': True } return thumbnailer.get_thumbnail(thumbnail_options) except InvalidImageFormatError: return '' ## todo: generic image
def serializable_pictures(self): serialized = [] for picture in self.pictures: thumbnailer = get_thumbnailer(picture.attachment_file) try: thdetail = thumbnailer.get_thumbnail(aliases.get('medium')) thurl = os.path.join(settings.MEDIA_URL, thdetail.name) except InvalidImageFormatError: thurl = None logger.error( _("Image %s invalid or missing from disk.") % picture.attachment_file) pass serialized.append({ 'author': picture.author, 'title': picture.title, 'legend': picture.legend, 'url': thurl }) return serialized
def resize(path, size=None, crop=None): thumbnail_opts = {} if size: if SIZE_RE.match(size): thumbnail_opts['size'] = tuple(map(int, size.split(','))) if crop: thumbnail_opts['crop'] = crop else: return default_storage.url(path) else: return default_storage.url(path) try: thumbnailer = get_thumbnailer(default_storage, path) thumbnail = thumbnailer.get_thumbnail(thumbnail_opts) return thumbnail.url #return HttpResponsePermanentRedirect(thumbnail.url) except IOError: return False except InvalidImageFormatError: return False
def img_src(self): if self.external_picture: return self.external_picture elif self.use_no_cropping: return self.picture.url picture_options = self.get_size( width=float(self.width or 0), height=float(self.height or 0), ) thumbnail_options = { 'size': picture_options['size'], 'crop': picture_options['crop'], 'upscale': picture_options['upscale'], 'subject_location': self.picture.subject_location, } thumbnailer = get_thumbnailer(self.picture) return thumbnailer.get_thumbnail(thumbnail_options).url
def dehydrate_image(self, bundle): try: image_size = bundle.request.GET['image_size'] except: image_size = "medium" try: thumbnail = get_thumbnailer(bundle.obj.image)[image_size] image = ({ 'url': thumbnail.url, 'width': thumbnail.width, 'height': thumbnail.height, 'original': bundle.obj.image.url, }) return image except Exception: image = ({}) return image
def crop(self): # delete old picture self.__getattribute__(self.crop_field).delete() # crop picture cropped = get_thumbnailer( self.__getattribute__(self.crop_connect_field)).get_thumbnail({ 'size': self.get_cropped_dimensions(), 'box': getattr(self, self.cropping_field), 'crop': True, 'detail': True, }) # save cropped picture setattr(self, self.crop_field, cropped.name) self.save()
def image_thumb(self): image = getattr(self, self.image_field) if image and not isinstance(image, ImageFieldFile): return '<img src="%s" alt="" style="max-width:%spx;height:%spx;">' % ( image.url, self.image_size[0], self.image_size[1]) else: try: return format_html( '<img src="%s" alt="" />' % get_thumbnailer(getattr(self, self.image_field) ).get_thumbnail({ 'size': self.image_size, 'detail': True, }).url if image else '<img src="%simages/blank.gif" alt="" ' 'style="max-width:%spx;max-height:%spx;" />' % (settings.STATIC_URL, self.image_size[0], self.image_size[1])) except (OSError, EasyThumbnailsError): return ''
def img_srcset_data(self): if not self.is_responsive_image: return None srcset = [] thumbnailer = get_thumbnailer(self.picture) picture_options = self.get_size(self.width, self.height) picture_width = picture_options['size'][0] thumbnail_options = {'crop': picture_options['crop']} breakpoints = getattr( settings, 'DJANGOCMS_PICTURE_RESPONSIVE_IMAGES_VIEWPORT_BREAKPOINTS', [576, 768, 992], ) for size in filter(lambda x: x < picture_width, breakpoints): thumbnail_options['size'] = (size, size) srcset.append((size, thumbnailer.get_thumbnail(thumbnail_options))) return srcset
def dump(self, kennel): plain_data = dict() plain_data['id'] = kennel.id plain_data['title'] = kennel.title plain_data['type'] = kennel.type plain_data['slug'] = kennel.slug plain_data['about'] = kennel.about plain_data[ 'cover'] = kennel.cover.url if kennel.cover else KENNEL_COVER options = {'size': (800, 800), 'quality': 99} plain_data['mini_cover'] = get_thumbnailer(kennel.cover).get_thumbnail(options).url if kennel.cover else \ KENNEL_COVER # plain_data['litters'] = self.litter_handler.get_dump_litters_by_kennel(kennel, user) # plain_data['news'] = self.get_kennel_news(kennel) plain_data['facebook'] = kennel.facebook plain_data['twitter'] = kennel.twitter plain_data['skype'] = kennel.skype plain_data['site'] = kennel.site plain_data['address'] = kennel.address plain_data['kennel_url'] = reverse('kennels:kennel_page', kwargs={'slug': kennel.slug}) # if kennel.coordinates: # plain_data['longitude'] = float(kennel.coordinates.get_x()) # plain_data['latitude'] = float(kennel.coordinates.get_y()) if kennel.country_club: plain_data['country_club'] = kennel.country_club.id plain_data['country_club_title'] = kennel.country_club.title plain_data['country_club_url'] = kennel.country_club.url if kennel.country_club.club_association: plain_data[ 'club_as'] = kennel.country_club.club_association.title plain_data[ 'contacts'] = self.contacts_handler.dump_get_contact_by_type_source( self.contacts_handler.model_instance.TYPE_KENNEL, kennel.id) # data = dict(source_id=kennel.id, type=self.news_handler.model_instance.TYPE_KENNEL) # plain_data['news'] = self.news_handler.get_news_by_params(data) return plain_data
def cartInfoJson(basket, basketline, currentproduct, parentproduct, stockrecord, qty, image): color, size = get_single_variant(currentproduct) return { 'Id': basketline.id, 'product_id': currentproduct.id, 'title': currentproduct.title, 'description': strip_tags(parentproduct.description), 'price': convert_to_currency(stockrecord.price_excl_tax), 'subtotal': convert_to_currency(stockrecord.price_excl_tax * qty), 'image': str( get_thumbnailer(image[0].original).get_thumbnail({ 'size': (400, 400), 'box': image[0].cropping, 'crop': True, 'detail': True, })), 'qty': qty, 'color': color, 'size': size, 'currentStock': stockrecord.num_in_stock, 'total': convert_to_currency(basket.total_excl_tax), 'shop': currentproduct.shop.name, 'shopSlug': currentproduct.shop.slug, 'msg': '' }