def _post_to_facebook(instance, tenant=None): """ Post a Wallpost to users Facebook page using Celery """ logger.info("FB post for:") logger.info("{0} with id {1} and tenant {2}".format(instance.__class__, instance.id, tenant.client_name)) if not tenant: return with LocalTenant(tenant, clear_tenant=True): social = instance.author.social_auth.get(provider='facebook') authorization_header = 'Bearer {token}'.format( token=social.extra_data['access_token'] ) graph_url = 'https://graph.facebook.com/v2.4/me/feed' base_url = 'https://{domain}'.format( domain=tenant.domain_url) link = instance.content_object.get_absolute_url() image = None # This code is executed via Celery, we assume the MediaWallpostPhoto # is saved and available on the instance. If the user uploaded # photos with the MediaWallpost we take the first one and include it # in the Facebook post. Otherwise we fallback to the project image. if isinstance(instance, MediaWallpost) and instance.photos.count() > 0: image = urljoin(base_url, get_thumbnail(instance.photos.all()[0].photo, "600x400").url ) else: if hasattr(instance.content_object, 'image') and instance.content_object.image: image = urljoin( base_url, get_thumbnail(instance.content_object.image, "600x400").url ) description = getattr( instance.content_object, 'pitch', instance.content_object.description ) data = { 'link': link, 'name': instance.content_object.title, 'description': description, 'message': instance.text, 'picture': image, 'caption': tenant_url() } # TODO: log failed requests requests.post( graph_url, data=json.dumps(data), headers={ 'Authorization': authorization_header, 'Content-Type': 'application/json'} )
def to_native(self, value): if not value: return None # The get_thumbnail() helper doesn't respect the THUMBNAIL_DEBUG setting # so we need to deal with exceptions like is done in the template tag. thumbnail = "" try: large = settings.MEDIA_URL + unicode(get_thumbnail(value, "800x450", crop=self.crop)) full = settings.MEDIA_URL + unicode(get_thumbnail(value, "800x600")) small = settings.MEDIA_URL + unicode(get_thumbnail(value, "120x120", crop=self.crop)) square = settings.MEDIA_URL + unicode(get_thumbnail(value, "120x120", crop=self.crop, colorspace="GRAY")) except Exception: if getattr(settings, "THUMBNAIL_DEBUG", None): raise logger.error("Thumbnail failed:", exc_info=sys.exc_info()) return None request = self.context.get("request") if request: return { "full": request.build_absolute_uri(full), "large": request.build_absolute_uri(large), "small": request.build_absolute_uri(small), "square": request.build_absolute_uri(square), } return {"full": full, "large": large, "small": small, "square": square}
def render(self, **kwargs): thumb = get_thumbnail(self.image, settings.THUMBNAIL_SETTINGS['CONTENT_PICTURE_NEWS'], upscale=False, crop='center') image = get_thumbnail(self.image, settings.THUMBNAIL_SETTINGS['FULLSCREEN_SIZE'], upscale=False) tag = render_to_string("content/image_content.html", dict( image=image, thumb=thumb, caption=self.caption, url=self.url, text=self.text)) return mark_safe(tag)
def to_representation(self, value): if not value: return None # The get_thumbnail() helper doesn't respect the THUMBNAIL_DEBUG setting # so we need to deal with exceptions like is done in the template tag. if not isfile(value.path): return None try: large = settings.MEDIA_URL + unicode( get_thumbnail(value, '800x450', crop=self.crop)) full = settings.MEDIA_URL + unicode( get_thumbnail(value, '1200x900')) small = settings.MEDIA_URL + unicode( get_thumbnail(value, '400x300', crop=self.crop)) square = settings.MEDIA_URL + unicode( get_thumbnail(value, '600x600', crop=self.crop)) except Exception: if getattr(settings, 'THUMBNAIL_DEBUG', None): raise logger.error('Thumbnail failed:', exc_info=sys.exc_info()) return None request = self.context.get('request') if request: return { 'full': request.build_absolute_uri(full), 'large': request.build_absolute_uri(large), 'small': request.build_absolute_uri(small), 'square': request.build_absolute_uri(square), } return {'full': full, 'large': large, 'small': small, 'square': square}
def to_native(self, value): if not value: return None # The get_thumbnail() helper doesn't respect the THUMBNAIL_DEBUG setting # so we need to deal with exceptions like is done in the template tag. thumbnail = "" try: large = settings.MEDIA_URL + unicode(get_thumbnail(value, '800x450', crop=self.crop)) full = settings.MEDIA_URL + unicode(get_thumbnail(value, '1200x900')) small = settings.MEDIA_URL + unicode(get_thumbnail(value, '400x380', crop=self.crop)) square = settings.MEDIA_URL + unicode(get_thumbnail(value, '120x120', crop=self.crop, colorspace="GRAY")) except Exception: if getattr(settings, 'THUMBNAIL_DEBUG', None): raise logger.error('Thumbnail failed:', exc_info=sys.exc_info()) return None request = self.context.get('request') if request: return { 'full': request.build_absolute_uri(full), 'large': request.build_absolute_uri(large), 'small': request.build_absolute_uri(small), 'square': request.build_absolute_uri(square), } return {'full': full, 'large': large, 'small': small, 'square': square}
def upload(request, purpose, pk=None): if purpose == 'job_seeker_photo': job_seeker_information = request.user.profile.personal_information job_seeker_information.photo = request.FILES['files[]'] job_seeker_information.save() url = get_thumbnail(job_seeker_information.photo, '203x203', crop="center").url elif purpose == 'employer_company_logo': employer_profile = request.user.profile employer_profile.logo = request.FILES['files[]'] employer_profile.save() url = get_thumbnail(employer_profile.logo, '203x203', crop="center").url elif purpose in ('job_support_document', 'job_full_position_document'): job = get_object_or_404(Job, pk=pk, owner=request.user) document_type = get_document_type(purpose) if purpose == 'job_full_position_document': if JobUploadDocument.objects.filter(job=job, document_type=document_type).count(): return HttpResponseBadRequest(json.dumps({'errors': {'job_full_position_document': 'Already exists.'}})) upload_document = JobUploadDocument() upload_document.job = job upload_document.document_type = document_type upload_document.document = request.FILES['files[]'] upload_document.save() return redirect('api_dispatch_detail', 'v1', 'job_upload_document', upload_document.pk) else: raise Http404 return HttpResponse(json.dumps({'url': url}), mimetype='application/json')
def _render(self, thumb_conf_name, full_conf_name): conf = settings.THUMBNAIL_SETTINGS thumb_conf = conf[thumb_conf_name] full_conf = conf[full_conf_name] thumb = get_thumbnail(self.image, thumb_conf[0], **thumb_conf[1]) image = get_thumbnail(self.image, full_conf[0], **full_conf[1]) div_caption = IMAGE_CAPTION_TEMPLATE.format(caption=self.caption) if self.caption else u"" tag = IMAGE_TEMPLATE.format(image=image, thumb=thumb, position=self.position, caption=self.caption, div_caption=div_caption) return mark_safe(tag)
def _post_to_facebook(instance, tenant=None): """ Post a Wallpost to users Facebook page using Celery """ logger.info("FB post for:") logger.info("{0} with id {1} and tenant {2}".format(instance.__class__, instance.id, tenant.client_name)) if not tenant: return from tenant_schemas.utils import get_tenant_model from django.db import connection db_tenant = get_tenant_model().objects.get(client_name=tenant.client_name) connection.set_tenant(db_tenant) with LocalTenant(tenant, clear_tenant=True): social = instance.author.social_auth.get(provider="facebook") authorization_header = "Bearer {token}".format(token=social.extra_data["access_token"]) graph_url = "https://graph.facebook.com/v2.4/me/feed" base_url = "https://{domain}".format(domain=tenant.domain_url) link = instance.content_object.get_absolute_url() image = None # This code is executed via Celery, we assume the MediaWallpostPhoto # is saved and available on the instance. If the user uploaded # photos with the MediaWallpost we take the first one and include it # in the Facebook post. Otherwise we fallback to the project image. if isinstance(instance, MediaWallpost) and instance.photos.count() > 0: image = urljoin(base_url, get_thumbnail(instance.photos.all()[0].photo, "600x400").url) else: if hasattr(instance.content_object, "image") and instance.content_object.image: image = urljoin(base_url, get_thumbnail(instance.content_object.image, "600x400").url) description = getattr(instance.content_object, "pitch", instance.content_object.description) data = { "link": link, "name": instance.content_object.title, "description": description, "message": instance.text, "picture": image, "caption": tenant_url(), } # TODO: log failed requests requests.post( graph_url, data=json.dumps(data), headers={"Authorization": authorization_header, "Content-Type": "application/json"}, )
def render(self, name, value, attrs=None): output = super(AdminImageWidget, self).render(name, value, attrs) get_thumbnail(value, 'x80', upscale=False) if value and hasattr(value, 'url'): try: mini = get_thumbnail(value, 'x80', upscale=False) except Exception: pass else: output = ( u'<div style="float:left">' u'<a style="width:%spx;display:block;margin:0 0 10px" class="thumbnail" target="_blank" href="%s">' u'<img src="%s"></a>%s</div>' ) % (mini.width, value.url, mini.url, output) return mark_safe(output)
def render(self, name, value, attrs=None): output = super(AdminImageWidget, self).render(name, value, attrs) get_thumbnail(value, 'x80', upscale=False) if value and hasattr(value, 'url'): try: mini = get_thumbnail(value, 'x80', upscale=False) except Exception: pass else: output = ( u'<div style="float:left">' u'<a style="width:%spx;display:block;margin:0 0 10px" class="thumbnail" target="_blank" href="%s">' u'<img src="%s"></a>%s</div>') % (mini.width, value.url, mini.url, output) return mark_safe(output)
def render(self, name, value, attrs=None, **kwargs): output = super(AdminImageWidget, self).render(name, value, attrs, **kwargs) if value and hasattr(value, "url"): ext = "JPEG" try: aux_ext = str(value).split(".") if aux_ext[len(aux_ext) - 1].lower() == "png": ext = "PNG" elif aux_ext[len(aux_ext) - 1].lower() == "gif": ext = "GIF" except Exception: pass try: mini = get_thumbnail(value, "x80", upscale=False, format=ext) except Exception as e: logger.warning("Unable to get the thumbnail", exc_info=e) else: try: output = ( '<div style="float:left">' '<a style="display:block;margin:0 0 10px" class="thumbnail" ' 'target="_blank" href="%s">' '<img src="%s"></a>%s</div>') % (value.url, mini.url, output) except (AttributeError, TypeError): pass return mark_safe(output)
def get_avatar_url(self): if self.hide_avatar: return settings.DEFAULT_AVATAR if self.avatar: thumbnail = get_thumbnail(self.avatar, "%(size)ix%(size)i" % dict(size=settings.AVATAR_SIZE), crop="center") return thumbnail.url elif self.user.email: try: default = "http://%s%s" % (Site.objects.get_current().domain, settings.DEFAULT_AVATAR) url = "%s/%s.jpg?%s" % (settings.GRAVATAR_BASE, hashlib.md5(self.user.email).hexdigest(), urllib.urlencode({ 'size': str(settings.AVATAR_SIZE), 'rating': "g", 'default': default, })) except: import traceback print traceback.format_exc() raise return url return settings.DEFAULT_AVATAR
def render(self, name, value, attrs=None, **kwargs): output = super(AdminImageWidget, self).render(name, value, attrs, **kwargs) if value and hasattr(value, 'url'): ext = 'JPEG' try: aux_ext = str(value).split('.') if aux_ext[len(aux_ext) - 1].lower() == 'png': ext = 'PNG' elif aux_ext[len(aux_ext) - 1].lower() == 'gif': ext = 'GIF' except Exception: pass try: mini = get_thumbnail(value, 'x80', upscale=False, format=ext) except Exception as e: logger.warning("Unable to get the thumbnail", exc_info=e) else: try: output = ( '<div style="float:left">' '<a style="width:%spx;display:block;margin:0 0 10px" class="thumbnail" ' 'target="_blank" href="%s">' '<img src="%s"></a>%s</div>' ) % (mini.width, value.url, mini.url, output) except (AttributeError, TypeError): pass return mark_safe(output)
def small_image(self): if self.image: f = get_thumbnail(self.image, '30x20', crop='center', quality=99) html = '<a href="%s"><img src="%s" title="%s" /></a>' return html % (self.image.url, f.url, self.title) else: return _("No image")
def render(self, name, value, attrs=None): output = super(AdminImageWidget, self).render(name, value, attrs) if value and hasattr(value, 'url'): ext = 'JPEG' try: aux_ext = str(value).split('.') if aux_ext[len(aux_ext) - 1].lower() == 'png': ext = 'PNG' except: pass try: mini = get_thumbnail(value, 'x80', upscale=False, format=ext) except Exception as e: logger.warn("Unable to get the thumbnail", exc_info=e) else: try: output = ( '<div style="float:left">' '<a style="width:%spx;display:block;margin:0 0 10px" class="thumbnail" ' 'target="_blank" href="%s">' '<img src="%s"></a>%s</div>') % (mini.width, value.url, mini.url, output) except AttributeError: pass return mark_safe(output)
def admin_thumbnail(self): try: return '<img src="%s">' % get_thumbnail(self.image, '200x100', crop='center').url except IOError: return 'IOError' except ThumbnailError, ex: return 'ThumbnailError, %s' % ex.message
def get_ajax(self, request, *args, **kwargs): from realestate.listing.templatetags.extra_functions import currency listings = [] for listing in Listing.objects.active(): #changed pos = listing.coords.get() lat = pos.position.latitute lng = pos.position.longitude try: im = get_thumbnail(listing.main_image.imagen, '135x90', crop='center', quality=99).url except (ValueError, AttributeError): im = '' listings.append({ 'id': listing.id, 'url': listing.get_absolute_url(), 'street': '%s' % listing.get_address(), 'title': listing.title, 'lat': lat, 'lng': lng, 'price': currency(listing.price), 'img': im, }) return self.render_json_response({ 'listings': listings, })
def render(self, name, value, attrs=None): output = super(AdminImageWidget, self).render(name, value, attrs) if value and hasattr(value, "url"): ext = "JPEG" try: aux_ext = str(value).split(".") if aux_ext[len(aux_ext) - 1].lower() == "png": ext = "PNG" except: pass try: mini = get_thumbnail(value, "x80", upscale=False, format=ext) except Exception as e: logger.warn("Unable to get the thumbnail", exc_info=e) else: try: output = ( '<div style="float:left">' '<a style="width:%spx;display:block;margin:0 0 10px" class="thumbnail" ' 'target="_blank" href="%s">' '<img src="%s"></a>%s</div>' ) % (mini.width, value.url, mini.url, output) except AttributeError: pass return mark_safe(output)
def get_default_photo_thumbnail(obj): default_photo = obj.get_default_photo() url = get_thumbnail( default_photo.file, '100x100', crop='center', quality=99 ).url if default_photo is not None else obj.get_no_photo_image() return mark_safe("<img width=\"100px\" height=\"auto\" src=\"%s\">" % url)
def get_mapa_propiedades(request): from realestate.propiedad.templatetags.extra_functions import currency listado_propiedades = [] for propiedad in Propiedad.objects.activas(): lat, lng = propiedad.coordenadas.split(',') try: im = get_thumbnail(propiedad.imagen_principal.imagen, '135x90', crop='center', quality=99).url except (ValueError, AttributeError): im = '' try: url = propiedad.get_absolute_url() except: url = '' listado_propiedades.append({ 'id': propiedad.id, 'url': url, 'street': propiedad.get_address(), 'title': propiedad.titulo, 'lat': lat, 'lng': lng, 'price': currency(propiedad.precio), 'img': im, }) return {'propiedades': listado_propiedades, }
def get_map(request): from realestate.listing.templatetags.extra_functions import currency listings = [] for listing in Listing.objects.active(): lat, lng = listing.coordenadas.split(',') try: im = get_thumbnail(listing.main_image.imagen, '135x90', crop='center', quality=99).url except (ValueError, AttributeError): im = '' try: url = listing.get_absolute_url() except: url = '' listings.append({ 'id': listing.id, 'url': url, 'street': listing.get_address(), 'title': listing.title, 'lat': lat, 'lng': lng, 'price': currency(listing.price), 'img': im, }) return {'listings': listings, }
def thumbnail(self, obj): data = {} if obj.video_url: data['video_url'] = obj.video_url if 'youtube.com' in obj.video_url: try: urlparts = urllib.parse.urlparse(obj.video_url) data['youtubeid'] = urllib.parse.parse_qs( urlparts.query)['v'][0] except (KeyError, ValueError, IndexError): pass photos = MediaWallpostPhoto.objects.filter(mediawallpost=obj) data['count'] = len(photos) data['remains'] = max(0, data['count'] - 1) if len(photos): if photos[0].photo: data['firstimage'] = get_thumbnail(photos[0].photo, "120x120", crop="center").url data['firstimage_url'] = photos[0].photo.url return mark_safe( render_to_string("admin/wallposts/preview_thumbnail.html", data))
def to_native(self, value): if not value: return "" if not value.name: return "" if not os.path.exists(value.path): return "" # The get_thumbnail() helper doesn't respect the THUMBNAIL_DEBUG setting # so we need to deal with exceptions like is done in the template tag. thumbnail = "" try: thumbnail = unicode(get_thumbnail(value, self.geometry_string, crop=self.crop, colorspace=self.colorspace)) except Exception: if getattr(settings, "THUMBNAIL_DEBUG", None): raise logger.error("Thumbnail failed:", exc_info=sys.exc_info()) return "" request = self.context.get("request") relative_url = settings.MEDIA_URL + thumbnail if request: return request.build_absolute_uri(relative_url) return relative_url
def to_representation(self, value): if not value: return "" if not value.name: return "" if not os.path.exists(value.path): return "" _, ext = os.path.splitext(value.path) if ext == '.svg': return value.url if ext == '.png': self.sorl_options['format'] = 'PNG' # The get_thumbnail() helper doesn't respect the THUMBNAIL_DEBUG setting # so we need to deal with exceptions like is done in the template tag. try: thumbnail = get_thumbnail(value, self.geometry_string, **self.sorl_options) except IOError: return "" except Exception: if getattr(settings, 'THUMBNAIL_DEBUG', None): raise logger.error('Thumbnail failed:', exc_info=sys.exc_info()) return "" relative_url = settings.MEDIA_URL + thumbnail.name return relative_url
def image_tag(self, obj): data = {} if obj.photo: data['image_full_url'] = obj.photo.url data['image_thumb_url'] = get_thumbnail(obj.photo, "120x120", crop="center").url return render_to_string("admin/wallposts/mediawallpost_photoinline.html", data)
def _render(self, context): file_ = self.file_.resolve(context) geometry = self.geometry.resolve(context) options = {} for key, expr in self.options: noresolve = {'True': True, 'False': False, 'None': None} value = noresolve.get(text_type(expr), expr.resolve(context)) if key == 'options': options.update(value) else: options[key] = value thumbnail = get_thumbnail(file_, geometry, **options) if not thumbnail or (isinstance(thumbnail, DummyImageFile) and self.nodelist_empty): if self.nodelist_empty: return self.nodelist_empty.render(context) else: return '' if self.as_var: context.push() context[self.as_var] = thumbnail output = self.nodelist_file.render(context) context.pop() else: output = thumbnail.url return output
def render(self, name, value, attrs=None): """ Render the ``input`` field based on the defined ``template_name``. The image URL is take from *value* and is provided to the template as ``image_url`` context variable relative to ``MEDIA_URL``. Further attributes for the ``input`` element are provide in ``input_attrs`` and contain parameters specified in *attrs* and *name*. If *value* contains no valid image URL an empty string will be provided in the context. """ if value is None: value = '' final_attrs = self.build_attrs(attrs, type=self.input_type, name=name) if value != '': # Only add the 'value' attribute if a value is non-empty. final_attrs['value'] = force_unicode(self._format_value(value)) image_url = final_attrs.get('value', '') image_original_url = None image_thumb = None if image_url: image_original_url = os.path.join(settings.MEDIA_URL, image_url) try: image_thumb = get_thumbnail(image_url, '100x100', crop='center', upscale=True) except IOError as inst: logger.error(inst) return render_to_string(self.template_name, Context({ 'image_thumb': image_thumb, 'input_attrs': flatatt(final_attrs), 'image_url': image_url, 'image_original_url': image_original_url, 'image_id': "%s-image" % final_attrs['id'], }))
def get_thumbnail_url(self, width=100, height=100): """Shortcut to get the URL for an image thumbnail.""" if self.image and hasattr(self.image, 'url'): frmt = "PNG" if self.image.path.lower().endswith('.png') else "JPEG" size = "{}x{}".format(width, height) thumbnail = get_thumbnail(self.image, size, upscale=False, format=frmt, crop='center') return thumbnail.url return None
def get_order_image_admin(self, obj): html = u'<img src="/media/img/no_image_min.png" title="%s" />' % obj.product.title if obj.product.image: try: f = get_thumbnail(obj.product.image, '130x130', quality=99, format='PNG') html = '<a href="%s" target="_blank"><img src="%s" title="%s" /></a>' % (obj.product.image.url, f.url, obj.product.title) except:pass return u'%s' % html
def thumb(self): try: im = get_thumbnail(self.image, '50x50', crop='center') t = Template('<img src="{{ image.url }}" alt="{{ alt }}" />') c = Context({"image": im, 'alt': self.page, }) thum = t.render(c) except ThumbnailError: thum = _('No image') return thum
def jinja_thumbnail(file_, geometry_string, **options): """ @return: image thumbnail object """ try: img = get_thumbnail(file_, geometry_string, **options) except IOError: img = None return img
def gallery(self, obj): data = {} data['images'] = [dict(full=p.photo.url, thumb=get_thumbnail(p.photo, "120x120", crop="center").url) for p in obj.photos.all()] return render_to_string("admin/wallposts/mediawallpost_gallery.html", data)
def dehydrate(self, bundle): bundle = super(ImageResource, self).dehydrate(bundle) if self.thumb_params: thumb = get_thumbnail(bundle.obj.image, **self.thumb_params) bundle.data.update({ 'thumb': thumb.url, 'full_image': bundle.obj.image.url }) return bundle
def get_thumb(self, obj): if obj.image: t = get_thumbnail(obj.image, size, **default_thumb_options) request = self.context.get('request', None) if request is not None: return request.build_absolute_uri(t.url) return t.url else: return None
def get_thumbnail_image(self, obj): if obj.file: f = get_thumbnail(obj.file, '50x50', crop='center', quality=99, format='PNG') return '<img src="%s" />' % f.url return '<img src="/media/img/no_image_50x50.png" />'
def render(self, name, value, attrs=None): output = [] image = get_thumbnail(object.imagen, '75x50', crop='center', quality=99) output.append( '<a target="_blank" href="%s"><img src="%s"/></a><br />%s ' % ( image.picture, image.url, _('Change:'))) output.append(super(AdminFileWidget, self).render(name, value, attrs)) return mark_safe(u''.join(output))
def thumbnail(self, width=264, height=64): if self.image: thumbnail = get_thumbnail(self.image, str(width) + 'x' + str(height)) img_resize_url = unicode(thumbnail.url) html = '<a style="height:%spx; display:block" class="image-picker" href="%s">' \ '<img src="%s" alt="%s" width="%s" height="%s" />' \ '</a>' return html % (height, self.image.url, img_resize_url, self.name, thumbnail.width, thumbnail.height) return '<img src="http://placehold.it/264x64" alt="False">'
def small_image(self): if self.image: f = get_thumbnail(self.image, '80x60', crop='center', quality=99, format='PNG') html = '<a href="%s"><img src="%s" title="%s" /></a>' return html % (self.image.url, f.url, self.title) return u'<img src="/media/img/no_image_min.png" title="%s" />' % self.title
def render(self, name, value, attrs=None): output = super(ImageWidget, self).render(name, value, attrs) if value and hasattr(value, 'url'): try: mini = get_thumbnail(value, '172x172', upscale=False) except Exception: pass else: output = u'<div class="portrait clearfix"><img src="%s">%s</div>' % (mini.url, output) return mark_safe(output)
def get_redirect_url(self, **kwargs): image = get_object_or_404(Image, pk=self.kwargs.get('pk')) geometry = self.kwargs.get('geometry') if not geometry: self.url = image.image.url else: self.url = get_thumbnail(image.image, geometry).url return super(RenderThumbnail, self).get_redirect_url(**kwargs)
def img_post(self, obj): if obj.image: return "<img src='%s' />" % ( get_thumbnail( obj.image, '100x66', crop='center' ).url, )
def render(self): if not self.value: return '' width = self.data.get('width', '') height = self.data.get('height', '') if not width and not height: return default_storage.url(self.value) else: size = '%sx%s' % (width, height) image = get_thumbnail(self.value, size, crop='center') return image.url
def miniatura(self, model_instance): return ( "<img src='%s' />" % ( get_thumbnail( model_instance.imagen_principal, '180x100', crop='center' ).url, ) )
def thumbnail(image_file, geometry_string, **options): """ calls the get_thumbnail from sorl """ options.setdefault('format', 'PNG') try: im = get_thumbnail(image_file, geometry_string, **options) except ThumbnailError: # @TODO default image im = None return im
def get_image(request, id): dajax = Dajax() try: image = Image.objects.only('image').get(pk=int(id)).image mini = get_thumbnail(image, 'x80', upscale=False) output = ('<a style="width:%spx;display:block;margin:0 0 10px" class="thumbnail" target="_blank" href="%s">' '<img src="%s"></a>' % (mini.width, image.url, mini.url)) dajax.assign('#admin_related_image', 'innerHTML', output) except Exception as e: print("Unable to get the thumbnail", e) return dajax.json()
def gallery(self, obj): data = {} data['images'] = [ dict(full=p.photo.url, thumb=get_thumbnail(p.photo, "120x120", crop="center").url) for p in obj.photos.all() ] return mark_safe( render_to_string("admin/wallposts/mediawallpost_gallery.html", data))
def image_tag(self, obj): data = {} if obj.photo: data['image_full_url'] = obj.photo.url data['image_thumb_url'] = get_thumbnail(obj.photo, "120x120", crop="center").url return mark_safe( render_to_string("admin/wallposts/mediawallpost_photoinline.html", data))
def small_image(self): if self.image: f = get_thumbnail(self.image, '100', crop='center', quality=99, format='PNG') html = '<a href="%s"><img src="%s" title="%s" /></a>' return html % (self.image.url, f.url, self.title) else: return u"Нет изображения"
def get_photo(self, obj): try: # ancho x alto return "%s%s" % (settings.WEBSITE_BASE_URL, get_thumbnail(obj.photo, '500x550', crop='center', upscale=True, quality=99).url) except Exception, e: return ""
def get_logo(self, obj): try: return "%s%s" % (settings.WEBSITE_BASE_URL, get_thumbnail(obj.logo, '250x150', crop='center', upscale=True, quality=99).url) except Exception, e: return ""
def thumbnail_static(file_, geometry, **options): from sorl.thumbnail.shortcuts import get_thumbnail from sorl.thumbnail.images import ImageFile, DummyImageFile storage = SafeStaticFilesStorage() absolute_path = finders.find(file_) try: file_ = ImageFile(staticfiles_storage.open(file_)) except: file_ = ImageFile(open(absolute_path)) file_.storage = storage return get_thumbnail(file_, geometry, **options)
def to_representation(self, value): if not value: return None # The get_thumbnail() helper doesn't respect the THUMBNAIL_DEBUG setting # so we need to deal with exceptions like is done in the template tag. try: full = settings.MEDIA_URL + get_thumbnail(value, '800x600').name small = settings.MEDIA_URL + get_thumbnail( value, '120x120', crop=self.crop).name except Exception: if getattr(settings, 'THUMBNAIL_DEBUG', None): raise logger.error('Thumbnail failed:', exc_info=sys.exc_info()) return None request = self.context.get('request') if request: return { 'full': request.build_absolute_uri(full), 'small': request.build_absolute_uri(small), } return {'full': full, 'small': small}
def get_thumbnail_url(self, width=100, height=100): """Shortcut to get the URL for an image thumbnail.""" if self.image and hasattr(self.image, 'url'): frmt = "PNG" if self.image.path.lower().endswith( '.png') else "JPEG" size = "{}x{}".format(width, height) thumbnail = get_thumbnail(self.image, size, upscale=False, format=frmt, crop='center') return thumbnail.url return None
def item_enclosures(self, item): """ See: https://stackoverflow.com/questions/60227116/django-rss-feed-add-image-to-description """ images = [] for image in item.event.images.all(): thumbnail = get_thumbnail(image.image, "800x800", quality=90) images.append( feedgenerator.Enclosure( self.get_image_url(thumbnail.url), str(image.image.size), "image/{}".format(thumbnail.name.split(".")[-1]), )) return images
def handle(self, *args, **options): geom = options.get('geom') pk = options.get('doc') docs = Document.objects.all() if pk: docs = docs.filter(pk=pk) for doc in docs: if doc.doc: with engine(doc.doc.name): logger.info('Processing document %s', doc) im=get_thumbnail(doc.doc, geom) if im is None: logger.error('failed') else: logger.info(im)
def text_filter(regex_base, value): """ Helper method to regex replace images with captions in different markups """ regex = regex_base % { 're_cap': u'[a-zA-Z0-9\.\,:;/_ \(\)\-\!\?\"]+', 're_img': u'[a-zA-Z0-9\.:/_\-\% ]+' } images = re.findall(regex, value) for i in images: image = i[1] im = get_thumbnail(image, str(settings.THUMBNAIL_FILTER_WIDTH)) value = value.replace(image, im.url) return value
def twitter_card(self, instance): source = ImageFile(instance.twitter_card_image) path = thumb_storage.backend._get_thumbnail_filename(source, "300x200", {'format': 'PNG'}) full_path = os.path.join(settings.MEDIA_ROOT, path) if os.path.exists(full_path): os.unlink(full_path) thumbnail = get_thumbnail(instance.twitter_card_image, "300x200", format="PNG") settings.THUMBNAIL_FORCE_OVERWRITE = False html = """<a href="{url}" target="_blank"><img src="{img}"></a>""".format( url=instance.twitter_card_image.url, img=thumbnail.url ) return mark_safe(html)