当前位置: 首页>>代码示例>>Python>>正文


Python images.ImageFile类代码示例

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


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

示例1: get_thumbnail

 def get_thumbnail(self, file_, geometry_string, **options):
     """
     Returns thumbnail as an ImageFile instance for file with geometry and
     options given. First it will try to get it from the key value store,
     secondly it will create it.
     """
     source = ImageFile(file_)
     for key, value in self.default_options.iteritems():
         options.setdefault(key, value)
     name = self._get_thumbnail_filename(source, geometry_string, options)
     thumbnail = ImageFile(name, default.storage)
     cached = default.kvstore.get(thumbnail)
     if cached:
         return cached
     if not thumbnail.exists():
         # We have to check exists() because the Storage backend does not
         # overwrite in some implementations.
         source_image = default.engine.get_image(source)
         # We might as well set the size since we have the image in memory
         size = default.engine.get_image_size(source_image)
         source.set_size(size)
         self._create_thumbnail(source_image, geometry_string, options,
                                thumbnail)
     # If the thumbnail exists we don't create it, the other option is
     # to delete and write but this could lead to race conditions so I
     # will just leave that out for now.
     default.kvstore.get_or_set(source)
     default.kvstore.set(thumbnail, source)
     return thumbnail
开发者ID:AdrianRibao,项目名称:sorl-thumbnail,代码行数:29,代码来源:base.py

示例2: _create_alternative_resolutions

    def _create_alternative_resolutions(self, source_image, geometry_string,
                                        options, name):
        """
        Creates the thumbnail by using default.engine with multiple output
        sizes.  Appends @<ratio>x to the file name.
        """
        if not options['alternative_resolutions']:
            return

        ratio = default.engine.get_image_ratio(source_image)
        geometry = parse_geometry(geometry_string, ratio)
        file_type = name.split('.')[len(name.split('.')) - 1]

        for resolution in options['alternative_resolutions']:
            resolution_geometry = (int(geometry[0] * resolution), int(geometry[1] * resolution))
            resolution_options = options.copy()
            if 'crop' in options and isinstance(options['crop'], basestring):
                crop = options['crop'].split(" ")
                for i in xrange(len(crop)):
                    s = re.match("(\d+)px", crop[i])
                    if s:
                        crop[i] = "%spx" % int(int(s.group(1)) * resolution)
                resolution_options['crop'] = " ".join(crop)

            thumbnail_name = name.replace(".%s" % file_type,
                                          "@%sx.%s" % (resolution, file_type))
            image = default.engine.create(source_image, resolution_geometry, resolution_options)
            thumbnail = ImageFile(thumbnail_name, default.storage)
            default.engine.write(image, resolution_options, thumbnail)
            size = default.engine.get_image_size(image)
            thumbnail.set_size(size)
开发者ID:UKA,项目名称:sorl-thumbnail,代码行数:31,代码来源:base.py

示例3: _get_geometry

    def _get_geometry(self, image_file):
        image = ImageFile(image_file)
        source_image = default.engine.get_image(image)
        size = default.engine.get_image_size(source_image)
        print "GEOM: %sx%s" % (str(size[0]), str(size[1]))
        image.set_size(size)

        exif_rotated = False

        if hasattr(source_image, '_getexif'):
            exif = source_image._getexif()
            orientation = exif and exif.get(self.EXIF_ORIENTATION_TAG, 0)
            exif_rotated = orientation in (6, 8)

        actual_size = exif_rotated and size[::-1] or size
        width, height = actual_size

        if width >= height:
            height = height*self.DEFAULT_WIDTH/width
            width = self.DEFAULT_WIDTH
        else:
            width = width*self.DEFAULT_WIDTH/height
            height = self.DEFAULT_WIDTH

        return width, height
开发者ID:aert,项目名称:lemidora,代码行数:25,代码来源:wall_image_service.py

示例4: _create_alternative_resolutions

    def _create_alternative_resolutions(self, source_image, geometry_string,
                                        options, name):
        """
        Creates the thumbnail by using default.engine with multiple output
        sizes.  Appends @<ratio>x to the file name.
        """
        ratio = default.engine.get_image_ratio(source_image, options)
        geometry = parse_geometry(geometry_string, ratio)
        file_name, dot_file_ext = os.path.splitext(name)

        for resolution in settings.THUMBNAIL_ALTERNATIVE_RESOLUTIONS:
            resolution_geometry = (int(geometry[0] * resolution), int(geometry[1] * resolution))
            resolution_options = options.copy()
            if 'crop' in options and isinstance(options['crop'], string_types):
                crop = options['crop'].split(" ")
                for i in range(len(crop)):
                    s = re.match("(\d+)px", crop[i])
                    if s:
                        crop[i] = "%spx" % int(int(s.group(1)) * resolution)
                resolution_options['crop'] = " ".join(crop)

            image = default.engine.create(source_image, resolution_geometry, options)
            thumbnail_name = '%(file_name)s%(suffix)s%(file_ext)s' % {
                'file_name': file_name,
                'suffix': '@%sx' % resolution,
                'file_ext': dot_file_ext
            }
            thumbnail = ImageFile(thumbnail_name, default.storage)
            default.engine.write(image, resolution_options, thumbnail)
            size = default.engine.get_image_size(image)
            thumbnail.set_size(size)
开发者ID:,项目名称:,代码行数:31,代码来源:

示例5: test_storage_serialize

 def test_storage_serialize(self):
     im = ImageFile(Item.objects.get(image="500x500.jpg").image)
     self.assertEqual(im.serialize_storage(), "thumbnail_tests.storage.TestStorage")
     self.assertEqual(ImageFile("http://www.image.jpg").serialize_storage(), "sorl.thumbnail.images.UrlStorage")
     self.assertEqual(
         ImageFile("http://www.image.jpg", default.storage).serialize_storage(),
         "thumbnail_tests.storage.TestStorage",
     )
     self.assertEqual(ImageFile("getit", default_storage).serialize_storage(), "thumbnail_tests.storage.TestStorage")
开发者ID:jonashaag,项目名称:sorl-thumbnail,代码行数:9,代码来源:tests.py

示例6: delete

 def delete(self, file_, delete_file=True):
     """
     Deletes file_ references in Key Value store and optionally the file_
     it self.
     """
     image_file = ImageFile(file_)
     if delete_file:
         image_file.delete()
     default.kvstore.delete(image_file)
开发者ID:,项目名称:,代码行数:9,代码来源:

示例7: get_thumbnail

    def get_thumbnail(self, file_, geometry_string, **options):
        """
        Returns thumbnail as an ImageFile instance for file with geometry and
        options given. First it will try to get it from the key value store,
        secondly it will create it.
        """
        logger.debug('Getting thumbnail for file [%s] at [%s]', file_,
                     geometry_string)
        source = ImageFile(file_)

        #preserve image filetype
        if settings.THUMBNAIL_PRESERVE_FORMAT:
            self.default_options['format'] = self._get_format(file_)

        for key in self.default_options.keys():
            if not key in options:
                options.update({key: self.default_options[key]})

        # For the future I think it is better to add options only if they
        # differ from the default settings as below. This will ensure the same
        # filenames being generated for new options at default.
        for key, attr in self.extra_options:
            value = getattr(settings, attr)
            if value != getattr(default_settings, attr):
                options.setdefault(key, value)
        name = self._get_thumbnail_filename(source, geometry_string, options)
        thumbnail = ImageFile(name, default.storage)
        cached = default.kvstore.get(thumbnail)
        if cached:
            return cached
        else:
            # We have to check exists() because the Storage backend does not
            # overwrite in some implementations.
            # so we make the assumption that if the thumbnail is not cached, it doesn't exist
            try:
                source_image = default.engine.get_image(source)
            except IOError:
                # if S3Storage says file doesn't exist remotely, don't try to
                # create it, exit early
                # Will return working empty image type; 404'd image
                logger.warn('Remote file [%s] at [%s] does not exist', file_,
                            geometry_string)
                return thumbnail
                # We might as well set the size since we have the image in memory
            size = default.engine.get_image_size(source_image)
            source.set_size(size)
            self._create_thumbnail(source_image, geometry_string, options,
                                   thumbnail)
            # If the thumbnail exists we don't create it, the other option is
        # to delete and write but this could lead to race conditions so I
        # will just leave that out for now.
        default.kvstore.get_or_set(source)
        default.kvstore.set(thumbnail, source)
        return thumbnail
开发者ID:xyz666,项目名称:sorl-thumbnail,代码行数:54,代码来源:base.py

示例8: create_thumbnail

def create_thumbnail(file_, geometry_string, options, name):
    thumbnail = ImageFile(name, default.storage)

    if not thumbnail.exists():
        source = ImageFile(file_)
        source_image = default.engine.get_image(source)
        size = default.engine.get_image_size(source_image)
        source.set_size(size)
        default.backend._create_thumbnail(source_image, geometry_string, options, thumbnail)

        # Need to update both the source and the thumbnail with correct sizing
        default.kvstore.set(source)
        default.kvstore.set(thumbnail, source)
开发者ID:aidanlister,项目名称:sorlery,代码行数:13,代码来源:tasks.py

示例9: get_thumbnail

 def get_thumbnail(self, file_, geometry_string, **options):
     """
     Returns thumbnail as an ImageFile instance for file with geometry and
     options given. First it will try to get it from the key value store,
     secondly it will create it.
     """
     if not options.get('format'):
         ext = str(file_).split('.')[-1].lower()
         options['format'] = ext.upper() if ext in AUTO_FORMATS else settings.THUMBNAIL_FORMAT
                 
     source = ImageFile(file_)
     for key, value in self.default_options.items():
         options.setdefault(key, value)
     # For the future I think it is better to add options only if they
     # differ from the default settings as below. This will ensure the same
     # filenames beeing generated for new options at default.
     for key, attr in self.extra_options:
         value = getattr(settings, attr)
         if value != getattr(default_settings, attr):
             options.setdefault(key, value)
     name = self._get_thumbnail_filename(source, geometry_string, options)
     thumbnail = ImageFile(name, default.storage)
     cached = default.kvstore.get(thumbnail)
     if cached:
         return cached
     if not thumbnail.exists():
         # We have to check exists() because the Storage backend does not
         # overwrite in some implementations.
         try: 
             source_image = default.engine.get_image(source)
         except IOError:
             if settings.THUMBNAIL_IMAGE_MISSING_DUMMY:
                 return DummyImageFile(geometry_string)
             else:
                 raise
         
         # We might as well set the size since we have the image in memory
         size = default.engine.get_image_size(source_image)
         source.set_size(size)
         self._create_thumbnail(source_image, geometry_string, options,
                                thumbnail)
         self._create_alternative_resolutions(source, geometry_string,
                                              options, thumbnail.name)
     # If the thumbnail exists we don't create it, the other option is
     # to delete and write but this could lead to race conditions so I
     # will just leave that out for now.
     default.kvstore.get_or_set(source)
     default.kvstore.set(thumbnail, source)
     return thumbnail
开发者ID:rmoch,项目名称:sorl-thumbnail,代码行数:49,代码来源:base.py

示例10: test_storage_serialize

 def test_storage_serialize(self):
     im = ImageFile(Item.objects.get(image='500x500.jpg').image)
     self.assertEqual(im.serialize_storage(), 'thumbnail_tests.storage.TestStorage')
     self.assertEqual(
         ImageFile('http://www.image.jpg').serialize_storage(),
         'sorl.thumbnail.images.UrlStorage',
     )
     self.assertEqual(
         ImageFile('http://www.image.jpg', default.storage).serialize_storage(),
         'thumbnail_tests.storage.TestStorage',
     )
     self.assertEqual(
         ImageFile('getit', default_storage).serialize_storage(),
         'thumbnail_tests.storage.TestStorage',
     )
开发者ID:aalebedev,项目名称:sorl-thumbnail,代码行数:15,代码来源:tests.py

示例11: create_thumbnail

def create_thumbnail(image_file, geometry_string, **options):
    # Note that thumbnail options must be same for a type of thumbnail.
    # Otherwise, different thumbnails are created.
    source = ImageFile(image_file)
    for key, value in default.backend.default_options.items():
            options.setdefault(key, value)
    name = default.backend._get_thumbnail_filename(source, geometry_string, options)
    thumbnail = ImageFile(name, default.storage)
    source_image = default.engine.get_image(source)
    default.backend._create_thumbnail(source_image, geometry_string, options, thumbnail)

    # Need to set size to store in kvstore.
    size = default.engine.get_image_size(source_image)
    source.set_size(size)

    default.kvstore.get_or_set(source)
    default.kvstore.set(thumbnail, source)
开发者ID:carriercomm,项目名称:sorl-thumbnail-async,代码行数:17,代码来源:tasks.py

示例12: create_thumbnail

def create_thumbnail(file_, geometry_string, options, name, force=False):
    if file_:
        source = ImageFile(file_)
    else:
        return

    thumbnail = ImageFile(name, default.storage)

    # We have to check exists() because the Storage backend does not
    # overwrite in some implementations.
    if settings.THUMBNAIL_FORCE_OVERWRITE or not thumbnail.exists() or force:
        try:
            source_image = default.engine.get_image(source)
        except IOError as e:
            logger.exception(e)
            # if S3Storage says file doesn't exist remotely, don't try to
            # create it and exit early.
            # Will return working empty image type; 404'd image
            logger.warn(
                text_type('Remote file [%s] at [%s] does not exist'),
                file_, geometry_string)
            return

        # We might as well set the size since we have the image in memory
        try:
            image_info = default.engine.get_image_info(source_image)
            options['image_info'] = image_info
        except AttributeError:
            options['image_info'] = {}
        size = default.engine.get_image_size(source_image)
        source.set_size(size)

        try:
            default.backend._create_thumbnail(
                source_image, geometry_string, options, thumbnail)
            default.backend._create_alternative_resolutions(
                source_image, geometry_string, options, thumbnail.name)
        finally:
            default.engine.cleanup(source_image)

    # If the thumbnail exists we don't create it, the other option is
    # to delete and write but this could lead to race conditions so I
    # will just leave that out for now.
    default.kvstore.get_or_set(source)
    default.kvstore.set(thumbnail, source)
开发者ID:hovel,项目名称:sorlery,代码行数:45,代码来源:tasks.py

示例13: get_thumbnail

 def get_thumbnail(self, file_, geometry_string, **options):
     """
     Returns thumbnail as an ImageFile instance for file with geometry and
     options given. First it will try to get it from the key value store,
     secondly it will create it.
     """
     source = ImageFile(file_)
     for key, value in self.default_options.iteritems():
         options.setdefault(key, value)
     options['mtime'] = os.path.getmtime(source.storage.path(source))###customization
     name = self._get_thumbnail_filename(source, geometry_string, options)
     thumbnail = ImageFile(name, default.storage)
     cached = default.kvstore.get(thumbnail)
     if cached and cached.exists():###customization
         return cached
     if not thumbnail.exists():
         # We have to check exists() because the Storage backend does not
         # overwrite in some implementations.
         source_image = default.engine.get_image(source)
         size = default.engine.get_image_size(source_image)
         if options.get('autocrop', None):
             source_image = autocrop(source_image, geometry_string, options)
         # We might as well set the size since we have the image in memory
         size = default.engine.get_image_size(source_image)
         source.set_size(size)
         ### customization: race condition, do not raise an OSError when the dir exists.
         # see sorl.thumbnail.images.ImageFile.write, it's not safe to simply throw
         # /sub/dir/name.jpg to django.core.files.storage.FileSystemStorage._save 
         full_path = thumbnail.storage.path(name)
         directory = os.path.dirname(full_path)
         if not os.path.exists(directory):
             try:
                 os.makedirs(directory)
             except OSError:
                 pass
         ### end of customization
         self._create_thumbnail(source_image, geometry_string, options,
                                thumbnail)
     # If the thumbnail exists we don't create it, the other option is
     # to delete and write but this could lead to race conditions so I
     # will just leave that out for now.
     default.kvstore.get_or_set(source)
     default.kvstore.set(thumbnail, source)
     return thumbnail
开发者ID:fruitschen,项目名称:custom-sorl-thumbnail,代码行数:44,代码来源:backends.py

示例14: get_thumbnail

    def get_thumbnail(self, file_, geometry_string, force_create=True, **options):
        """
        Returns thumbnail as an ImageFile instance for file with geometry and
        options given. First it will try to get it from the key value store,
        secondly it will create it.
        """
        source = ImageFile(file_)

        if settings.THUMBNAIL_PRESERVE_FORMAT:
            format = self._get_format(file_)
            if format == "GIF":
                options.setdefault("format", format)

        for key, value in self.default_options.iteritems():
            options.setdefault(key, value)
        # For the future I think it is better to add options only if they
        # differ from the default settings as below. This will ensure the same
        # filenames beeing generated for new options at default.
        for key, attr in self.extra_options:
            value = getattr(settings, attr)
            if value != getattr(default_settings, attr):
                options.setdefault(key, value)
        name = self._get_thumbnail_filename(source, geometry_string, options)
        thumbnail = ImageFile(name, default.storage)
        cached = default.kvstore.get(thumbnail)
        if cached:
            return cached
        if not force_create:
            return source
        if not thumbnail.exists():
            # We have to check exists() because the Storage backend does not
            # overwrite in some implementations.
            source_image = default.engine.get_image(source)
            # We might as well set the size since we have the image in memory
            size = default.engine.get_image_size(source_image)
            source.set_size(size)
            self._create_thumbnail(source_image, geometry_string, options, thumbnail)
        # If the thumbnail exists we don't create it, the other option is
        # to delete and write but this could lead to race conditions so I
        # will just leave that out for now.
        default.kvstore.get_or_set(source)
        default.kvstore.set(thumbnail, source)
        return thumbnail
开发者ID:Architizer,项目名称:sorl-thumbnail,代码行数:43,代码来源:base.py

示例15: thumbnail

def thumbnail(request, root_dir=None):
    """
    Scales (conserving aspect ratio) a requested image with given width, height
    and orientation
    """
    width = request.GET.get('width', None)
    height = request.GET.get('height', None)
    crop = request.GET.get('crop', None)
    orientation = request.GET.get('orientation', constants.ORIENTATION_DEFAULT)
    geometry_string = make_geometry_string(width, height)
    if root_dir is None:
        root_dir = settings.IMAGERESIZER_ROOT
    resource_path = request.path.replace(
        settings.IMAGERESIZER_PATH_TO_REMOVE, '', 1
    )
    path = os.path.realpath(os.path.join(root_dir, resource_path))
    if not os.path.exists(path):
        raise Http404
    if geometry_string is None:
        image = ImageFile(path, storage=default.storage)
        image.set_size()
        geometry_string = make_geometry_string(image.width, image.height)
    thumbnail = get_thumbnail(path, geometry_string,
            ll_transverse=True \
                if orientation == constants.ORIENTATION_LANDSCAPE \
                else False)
    mimetype, encoding = mimetypes.guess_type(path)
    response = HttpResponse(thumbnail.read(), mimetype=mimetype)
    last_modified = http_date(
        time.mktime(
            thumbnail.storage.modified_time(thumbnail.name).timetuple()
        )
    )
    response['Last-Modified'] = last_modified
    response['ETag'] = quote_etag(hashlib.sha1(last_modified).hexdigest())
    response['Content-Length'] = thumbnail.storage.size(thumbnail.name)
    response['Accept-Ranges'] = 'bytes'
    return response
开发者ID:biznixcn,项目名称:WR,代码行数:38,代码来源:views.py


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