本文整理汇总了Python中sorl.thumbnail.shortcuts.get_thumbnail函数的典型用法代码示例。如果您正苦于以下问题:Python get_thumbnail函数的具体用法?Python get_thumbnail怎么用?Python get_thumbnail使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_thumbnail函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: render
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)
开发者ID:alexgula,项目名称:django_sites,代码行数:7,代码来源:models.py
示例2: to_native
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}
开发者ID:rollick,项目名称:bluebottle,代码行数:26,代码来源:serializers.py
示例3: to_native
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}
开发者ID:gannetson,项目名称:bluebottle,代码行数:26,代码来源:serializers.py
示例4: upload
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')
开发者ID:ibobriakov,项目名称:solidrock,代码行数:26,代码来源:views.py
示例5: _render
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)
开发者ID:alexgula,项目名称:django_sites,代码行数:9,代码来源:models.py
示例6: _post_to_facebook
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"},
)
开发者ID:jfterpstra,项目名称:bluebottle,代码行数:51,代码来源:tasks.py
示例7: render
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)
开发者ID:BergSoft,项目名称:djbookru,代码行数:15,代码来源:current.py
示例8: render
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)
开发者ID:mariocesar,项目名称:sorl-thumbnail,代码行数:27,代码来源:current.py
示例9: render
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)
开发者ID:rodolfofiuza,项目名称:sorl-thumbnail,代码行数:25,代码来源:current.py
示例10: image_tag
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)
开发者ID:pombredanne,项目名称:bluebottle,代码行数:7,代码来源:admin.py
示例11: get_map
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, }
开发者ID:rogeriofalcone,项目名称:realestate,代码行数:29,代码来源:views.py
示例12: render
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'],
}))
开发者ID:dulaccc,项目名称:django-skel-custom,代码行数:35,代码来源:widget.py
示例13: get_avatar_url
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
开发者ID:yzen,项目名称:OER-Commons,代码行数:25,代码来源:models.py
示例14: admin_thumbnail
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
开发者ID:pavelm2007,项目名称:shop,代码行数:7,代码来源:models.py
示例15: _render
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
开发者ID:AlfiyaZi,项目名称:sorl-thumbnail,代码行数:29,代码来源:thumbnail.py
示例16: get_mapa_propiedades
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, }
开发者ID:squarepegsys,项目名称:realestate,代码行数:29,代码来源:views.py
示例17: get_thumbnail_url
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
开发者ID:dpenezic,项目名称:ServiceInfo,代码行数:8,代码来源:models.py
示例18: gallery
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)
开发者ID:repodevs,项目名称:bluebottle,代码行数:9,代码来源:admin.py
示例19: get_thumb
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
开发者ID:paveltyavin,项目名称:bildvortaro,代码行数:9,代码来源:serializers.py
示例20: jinja_thumbnail
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
开发者ID:JvGinkel,项目名称:openode,代码行数:9,代码来源:extra_filters_jinja.py
注:本文中的sorl.thumbnail.shortcuts.get_thumbnail函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论