• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python thumbnail.get_thumbnail函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中sorl.thumbnail.get_thumbnail函数的典型用法代码示例。如果您正苦于以下问题:Python get_thumbnail函数的具体用法?Python get_thumbnail怎么用?Python get_thumbnail使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了get_thumbnail函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: save

    def save(self, *args, **kwargs):

        basewidth = 500

        self.collection = get_object_or_404(Coll, slug=self.slugi)

        super(Picture, self).save()

        self.thumb = get_thumbnail(self.filename,'98x98', crop='center', quality=99).url
        self.medium = get_thumbnail(self.filename,'230x270', crop='center', quality=99).url

        super(Picture, self).save()



        # super(Picture, self).save()
        if not self.filename:
            return



        image = Image.open(self.filename)
        #(width, height) = image.size
        wpercent = (basewidth/float(image.size[0]))
        hsize = int((float(image.size[1])*float(wpercent)))
        image = image.resize((basewidth, hsize), Image.ANTIALIAS)
        image.save(self.filename.path)
开发者ID:avkozlov,项目名称:vitrinaburg,代码行数:27,代码来源:models.py


示例2: as_json

 def as_json(self):
   return {
     'name': self.name,
     'url': self.src.url,
     'url_medium': get_thumbnail(self.src,"300x300").url,
     'url_small': get_thumbnail(self.src,"128x128", crop='center').url,
   }
开发者ID:neostoic,项目名称:Localvore,代码行数:7,代码来源:models.py


示例3: test_a_new

 def test_a_new(self):
     slog.start_log()
     get_thumbnail(self.im, '50x50')
     log = slog.stop_log()
     actions = [
         # first see if the file exists
         'exists: test/cache/cc/33/cc33e9e8b2355e7e2a9437319c046ad4.jpg',
         # open the original for thumbnailing
         'open: org.jpg',
         # save the file
         'save: test/cache/cc/33/cc33e9e8b2355e7e2a9437319c046ad4.jpg',
         # check for filename
         'get_available_name: test/cache/cc/33/cc33e9e8b2355e7e2a9437319c046ad4.jpg',
         # called by get_available_name
         'exists: test/cache/cc/33/cc33e9e8b2355e7e2a9437319c046ad4.jpg',
         # save the 1.5 resolution version
         'save: test/cache/cc/33/[email protected]',
         'get_available_name: test/cache/cc/33/[email protected]',
         'exists: test/cache/cc/33/[email protected]',
         # save the 2 resolution version
         'save: test/cache/cc/33/[email protected]',
         'get_available_name: test/cache/cc/33/[email protected]',
         'exists: test/cache/cc/33/[email protected]'
     ]
     self.assertEqual(log, actions)
开发者ID:UKA,项目名称:sorl-thumbnail,代码行数:25,代码来源:tests.py


示例4: dehydrate

 def dehydrate(self, bundle):
     album_cover = bundle.obj.get_album_cover()
     cover_image_thumb = get_thumbnail(album_cover.image, "240x165")
     cover_image_large = get_thumbnail(album_cover.image, "1024x768")
     bundle.data['cover_image_thumb'] = cover_image_thumb.url
     bundle.data['cover_image_large'] = cover_image_large.url
     return bundle 
开发者ID:MechanisM,项目名称:fotochest,代码行数:7,代码来源:api.py


示例5: _get_carousel_data

def _get_carousel_data(project, updates):
    photos = []
    if project.current_image:
        try:
            im = get_thumbnail(project.current_image, '750x400', quality=99)
            photos.append({
                "url": im.url,
                "caption": project.current_image_caption,
                "credit": project.current_image_credit,
                "direct_to_url": '',
            })
        except IOError:
            pass
    for update in updates:
        if update.photo:
            direct_to = reverse('update-main', kwargs={
                'project_id': project.pk,
                'update_id': update.pk
            })
            try:
                im = get_thumbnail(update.photo, '750x400', quality=99)
                photos.append({
                    "url": im.url,
                    "caption": update.photo_caption,
                    "credit": update.photo_credit,
                    "direct_to_url": direct_to,
                })
            except IOError:
                continue
    return {"photos": photos}
开发者ID:RMUCapstone-MIS590,项目名称:akvo-rsr,代码行数:30,代码来源:project.py


示例6: handle

 def handle(self, **options):
     for leaflet_image in tqdm(LeafletImage.objects.all().exclude(image="").order_by('?')):
         try:
             get_thumbnail(leaflet_image.image, '350').url
             get_thumbnail(leaflet_image.image, '100x100', crop='center').url
         except:
             pass
开发者ID:gavinrozzi,项目名称:electionleaflets,代码行数:7,代码来源:cache_images.py


示例7: get_small_thumbnail

 def get_small_thumbnail(self):
     if self.position == "s_bloque":
         return get_thumbnail(self.imagen, "272x100", upscale=False).url
     elif self.position == "p_bloque":
         return get_thumbnail(self.imagen, "272x140", upscale=False).url
     else:
         return get_thumbnail(self.imagen, "594x61", upscale=False).url
开发者ID:carlosds730,项目名称:BuenViaje,代码行数:7,代码来源:models.py


示例8: render_column

    def render_column(self, row, column):

        if column == "id":
            return {'id': row.id,
                    'display': reverse_lazy('parte:detalle', args=[row.id])
            }
        elif column == "fecha":
            return  row.fecha.strftime("%d/%m/%Y")
        elif column == 'grupo':
            return row.get_nombre_grupo_alumno()
        elif column == "fotoalu":
            if row.grupoalumno.cursoalumno.alumno.foto:
                return get_thumbnail(row.grupoalumno.cursoalumno.alumno.foto, '50x40').url
            else:
                return u''
        elif column == "alumno":
            return row.get_nombre_completo_alumno()
        elif column == "fotoprofe":
            if row.cursoprofesor.profesor.foto:
                return get_thumbnail(row.cursoprofesor.profesor.foto, '50x40').url
            else:
                return u''
        elif column == "profesor":
            return row.get_nombre_completo_profesor()
        elif column == "urls":
            return {
                'detalle': reverse_lazy('parte:detalle', args=[row.id]),
                'editar': reverse_lazy('parte:editar', args=[row.id]),
                'eliminar': reverse_lazy('parte:eliminar', args=[row.id])
            }
        else:
            return super(ParteResponsableBaseDatatableView, self).render_column(row, column)
开发者ID:pkom,项目名称:gesiesweb,代码行数:32,代码来源:views.py


示例9: get_user_json

    def get_user_json(user, picture_size='32x32'):
        """
        Return a user in JSON
        
        Args:
        user: The user to serialize in JSON
        picture_size: Profile picture size
        """
        im = None

        # Workaround for the moment : inactive with website url = partner
        if not user.is_active and user.get_profile().website_url:
            profile_link = user.get_profile().website_url
            if user.get_profile().image:
                try:
                    im = get_thumbnail(user.get_profile().image, '90x90', quality=99)
                except IOError:
                    logging.warn('Profile image not found for user {0}'.format(user.id))
        else:
            profile_link = reverse('website.views.profile', kwargs={'user_id': user.username})
            if user.get_profile().image:
                try:
                    im = get_thumbnail(user.get_profile().image, picture_size, crop='center', quality=99)
                except IOError:
                    logging.warn('Profile image not found for user {0}'.format(user.id))
        user_json = { "id" : user.id, "username": user.username, "first_name": user.first_name, "facebook_id" : user.get_profile().facebook_id, "profile_link" : profile_link}
        if 'im' in locals() and im and im.url:
            user_json.update({"picture": im.url})

        return user_json
开发者ID:UniShared,项目名称:unishared,代码行数:30,代码来源:helpers.py


示例10: to_dict

    def to_dict(self):
        dict = {
            'title': self.title,
            'date_created': str(self.date_created),
            'date_saved': str(self.date_saved),
            'market': unicode(self.reference.market),
            'filter_solution': unicode(self.reference.filter_solution),
            'application': self.application,
            'machine': self.machine,
            'machine_type': self.machine_type,
            'filter': self.filter,
            'filter_element': self.filter_element,
            'manufacturer': str(self.reference.manufacturer),
            'problem': self.problem,
            'solution': self.solution,
            'url': reverse('view_reference', args=[self.reference.slug]),
        }

        if self.reference.illustration1:
            dict['list_image'] = get_thumbnail(self.reference.illustration1, "200x200", crop='center').url
        elif self.reference.illustration2:
            dict['list_image'] = get_thumbnail(self.reference.illustration2, "200x200", crop='center').url

        if self.reference.is_customer_public:
            dict['customer'] = self.reference.customer.to_dict()
        return dict
开发者ID:relekang,项目名称:fs-reference,代码行数:26,代码来源:models.py


示例11: get_thumbnails

 def get_thumbnails(self):
     mb = self.image.file.size / (1024*1024)
     print(f'Main image {self.image.name} with size {mb}')
     get_thumbnail(self.image, '1920x1164', crop='center')
     get_thumbnail(self.image, '1024', crop='center')
     for image in self.images.all():
         image.get_thumbnails()
开发者ID:NickRenton,项目名称:sulykarchitects,代码行数:7,代码来源:models.py


示例12: photo

def photo(request, photo_pk):
    """
    Displays a map for the specified photo along with its details.
    """
    photo = get_object_or_404(Photo, pk=photo_pk)
    # Get the EXIF tags that belongs to the current photo
    displayed_exif_tags = [tag.strip() for tag in config.DISPLAYED_EXIF_TAGS.split('\n')]
    exif_tags = photo.exiftag_set.filter(key__in=displayed_exif_tags)
    sorted_exif_tags = [{'key': tag.key, 'value': tag.substituted_value} for tag in (exif_tags.filter(key=tag)[0] for tag in displayed_exif_tags if exif_tags.filter(key=tag).count() > 0)]
    context = RequestContext(request)
    context.update({
                    'accuracy': photo.get_location_accuracy_display(),
                    'accuracy_value': Photo.LOCATION_ACCURACY_IN_METERS[photo.location_accuracy],
                    'date_taken': photo.date_taken,
                    'elevation': photo.get_elevation(),
                    'exif_tags': json.dumps(sorted_exif_tags),
                    'latitude': photo.latitude,
                    'large_thumbnail_url': get_thumbnail(photo.file, settings.PHOTO_LARGE_SIZE, crop='noop').url,
                    'location': photo.get_location(),
                    'longitude': photo.longitude,
                    'map_url': reverse('robinson_app.views.map'),
                    'name': unicode(photo),
                    'search_url': urllib.urlencode({ 'q': photo.get_location() }),
                    'small_thumbnail_url':  get_thumbnail(photo.file, settings.PHOTO_SMALL_SIZE, crop='noop').url,
                    'GA_ID': config.GA_ID
    })
    return render_to_response('photo.html', context)
开发者ID:flebel,项目名称:robinson_app,代码行数:27,代码来源:views.py


示例13: test_retina

    def test_retina(self):
        get_thumbnail(self.im, '50x50')

        actions = [
            # save regular resolution, same as in StorageTestCase
            'open: retina.jpg',
            'save: test/cache/19/10/1910dc350bbe9ee55fd9d8d3d5e38e19.jpg',
            'get_available_name: test/cache/19/10/1910dc350bbe9ee55fd9d8d3d5e38e19.jpg',
            'exists: test/cache/19/10/1910dc350bbe9ee55fd9d8d3d5e38e19.jpg',

            # save the 1.5x resolution version
            'save: test/cache/19/10/[email protected]',
            'get_available_name: test/cache/19/10/[email protected]',
            'exists: test/cache/19/10/[email protected]',

            # save the 2x resolution version
            'save: test/cache/19/10/[email protected]',
            'get_available_name: test/cache/19/10/[email protected]',
            'exists: test/cache/19/10/[email protected]'
        ]
        self.assertEqual(self.log, actions)

        with open(pjoin(settings.MEDIA_ROOT, 'test/cache/19/10/[email protected]')) as fp:
            engine = PILEngine()
            self.assertEqual(engine.get_image_size(engine.get_image(ImageFile(file_=fp))), (75, 75))
开发者ID:aalebedev,项目名称:sorl-thumbnail,代码行数:25,代码来源:tests.py


示例14: _get_thumbnail

 def _get_thumbnail(self, *args, **kwargs):
     try:
         return get_thumbnail(*args, **kwargs)
     except (IOError, IndexError, TypeError):
         i = Picture.objects.get(id=2072)
         self.file = i.file
         return get_thumbnail(self, "400")
开发者ID:psimonkey,项目名称:starandshadow,代码行数:7,代码来源:models.py


示例15: image_rotator

def image_rotator(request):
    logger.info('Rotate image called by user='+str(request.user)+', ip='+str(request.META['REMOTE_ADDR']))
    if request.method=='POST':
        try:
            direction = request.POST["direction"]
            pk = request.POST["pk"]
        except KeyError:
            logger.error('Rotator: No image PK or direction of rotation given!')
            return HttpResponseBadRequest('No image PK or direction given!')
        else: pass
        image = get_object_or_404(Image, pk=pk)
        if (request.user.is_superuser) or (image.user==request.user):
            im = PilImage.open(image.image)
            if direction=='right':
                rotated_image = im.rotate(270)
            elif direction=='left':
                rotated_image = im.rotate(90)
            else: return HttpResponseBadRequest('Incorrect direction!')
            thumbnails_delete(image.image, delete_file=False)
            rotated_image.save(image.image.file.name, owerwrite=True)
            new_image_width=rotated_image.size[0]
            new_image_height=rotated_image.size[1]
            if (new_image_width >= new_image_height):
                thumbnail=get_thumbnail(image.image.file.name, "795x594", crop="10px 10px")
            else:
                thumbnail=get_thumbnail(image.image.file.name, "795x1094", crop="10px 10px")
            return HttpResponse(thumbnail.url)
            
        else: return HttpResponseBadRequest('You have no permission to rotate images!')
    else: return HttpResponseBadRequest('Only POST accepted!')
开发者ID:garmoncheg,项目名称:gphblog,代码行数:30,代码来源:views.py


示例16: test_retina

    def test_retina(self):
        get_thumbnail(self.image, '50x50')

        actions = [
            'exists: test/cache/91/bb/91bb06cf9169e4c52132bb113f2d4c0d.jpg',

            # save regular resolution, same as in StorageTestCase
            'open: retina.jpg',
            'save: test/cache/91/bb/91bb06cf9169e4c52132bb113f2d4c0d.jpg',
            'get_available_name: test/cache/91/bb/91bb06cf9169e4c52132bb113f2d4c0d.jpg',
            'exists: test/cache/91/bb/91bb06cf9169e4c52132bb113f2d4c0d.jpg',

            # save the 1.5x resolution version
            'save: test/cache/91/bb/[email protected]',
            'get_available_name: test/cache/91/bb/[email protected]',
            'exists: test/cache/91/bb/[email protected]',

            # save the 2x resolution version
            'save: test/cache/91/bb/[email protected]',
            'get_available_name: test/cache/91/bb/[email protected]',
            'exists: test/cache/91/bb/[email protected]'
        ]
        self.assertEqual(self.log, actions)

        path = os.path.join(settings.MEDIA_ROOT,
                            'test/cache/91/bb/[email protected]')

        with open(path) as fp:
            engine = PILEngine()
            self.assertEqual(engine.get_image_size(engine.get_image(ImageFile(file_=fp))), (75, 75))
开发者ID:DeadWisdom,项目名称:sorl-thumbnail,代码行数:30,代码来源:test_alternative_resolutions.py


示例17: preview

    def preview(self, user):
        from django.core.files.storage import default_storage as storage

        fh = storage.open(self.file.name, "w")

        # file_path = self.file.url

        result = {
            "id": self.pk,
            "type": self.type,
            "xLit": get_thumbnail(fh, "80x80", crop='center', quality=90).url,
            "xBig": get_thumbnail(fh, "1080x1080", crop='center').url,
            "xFull": self.file.url,
            "uploader_id": self.uploader.id
        }

        # from django.core.files import File
        # img_file = self.file
        # if self.type == Media.TYPE_IMAGE:
        #     img_file = File(open(self.file.path))
        # else:
        #     img_file = File(open(self.file.path.replace(".webm", ".png")))

        # result["x128"] = get_thumbnail(img_file, "128x128", crop='center', quality=80).url

        return result
开发者ID:maxrevilo,项目名称:barachiel-server,代码行数:26,代码来源:models.py


示例18: prepare_json_list

def prepare_json_list(pins):
	"""
	Return list of dictionaries describing pins. This should be used when returning pins in JSON.
	"""
	pin_list = []
	for p in pins:
		if hasattr(p, 'is_advertisment'):
			data = {'content': p.get_advertisment()}
		else:
			try:
				image = get_thumbnail(p.get_image(), '266', crop='center')
				im = {'url': image.url, 'width': image.width, 'height': image.height}
			except ThumbnailError:
				continue
			comments = []
			for c in p.comments:
				if c.user:
					try:
						c_image = get_thumbnail(c.user.get_profile().image, '30x30', crop='center')
						c_im = {'url': c_image.url, 'width': c_image.width, 'height': c_image.height}
					except ThumbnailError:
						continue
				comments.append({'im': c_im,'comment': truncate_words(c.comment, 5)})
			data = {'pk': p.pk, 'absolute_url': p.get_absolute_url(),'popup_url': p.get_popup_url(), 'number_of_repins': p.get_number_of_repins(), 
			'number_of_likes': p.get_number_of_likes(), 'thumbnail': im ,
				'description': truncate_words(p.description, 15), 'comments': comments}
		pin_list.append(data)

	return pin_list
开发者ID:cheetos007,项目名称:owantsbeta_git,代码行数:29,代码来源:helpers.py


示例19: tag

    def tag(self):
        klasses = [
            'img-thumbnail',
            'inline-image-base',
            'inline-image-%s' % self.size,
        ]

        if self.size == 'headline':
            thumbnail = get_thumbnail(self.image.image.file,
                                      '960x200',
                                      crop='center')
        else:
            klasses.append('inline-image-align-%s' % self.align)

            if self.size == 'medium':
                thumbnail = get_thumbnail(self.image.image.file, '260x260')
            elif self.size == 'small':
                thumbnail = get_thumbnail(self.image.image.file, '174x174')
            elif self.size == 'full':
                thumbnail = self.image.image

        return ('<img src="%s" alt="%s" class="%s" '
                'height="%spx" width="%spx" />' % (
                    thumbnail.url,
                    self.alt,
                    ' '.join(klasses),
                    thumbnail.height,
                    thumbnail.width,
                ))
开发者ID:dominicrodger,项目名称:kanisa,代码行数:29,代码来源:kanisa_markup.py


示例20: thumbnail

def thumbnail(source, *args, **kwargs):
    """
    Wraps sorl thumbnail with an additional 'default' keyword
    https://github.com/mozilla/mozillians/blob/master/apps/common/helpers.py
    """

    # Templates should never return an exception
    try:
        # We set path either from the filesystem or from a url
        if hasattr(source, 'path'):
            if not source.path:
                source = kwargs.get('default')
            path = source.path
        elif hasattr(source, 'url'):
            path = urlparse(source.url).path
        else:
            raise NotImplementedError('Unknown storage backend')

        # Handle PNG images a little more gracefully
        # Make sure thumbnail call doesn't specifically set format
        if not 'format' in kwargs:
            filetype = path.split('.')[-1]
            # If we have a PNG, don't default convert to JPG
            if filetype.lower() == 'png':
                kwargs['format'] = 'PNG'

        return get_thumbnail(source, *args, **kwargs).url
    except Exception as e:
        logger.error('Thumbnail had Exception: %s' % (e,))
        source = getattr(settings, 'DEFAULT_IMAGE_SRC')
        return get_thumbnail(source, *args, **kwargs).url
开发者ID:zararah,项目名称:source,代码行数:31,代码来源:helpers.py



注:本文中的sorl.thumbnail.get_thumbnail函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python pil_engine.Engine类代码示例发布时间:2022-05-27
下一篇:
Python thumbnail.delete函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap