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


Python PIL.JpegImagePlugin类代码示例

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


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

示例1: test_save_cjpeg

    def test_save_cjpeg(self):
        img = Image.open(TEST_FILE)

        tempfile = self.tempfile("temp.jpg")
        JpegImagePlugin._save_cjpeg(img, 0, tempfile)
        # Default save quality is 75%, so a tiny bit of difference is alright
        self.assert_image_similar(img, Image.open(tempfile), 17)
开发者ID:dvska,项目名称:Pillow,代码行数:7,代码来源:test_file_jpeg.py

示例2: test_jpeg

    def test_jpeg(self):
        path = os.path.join(TEST_DATA_PATH, "Sam_Hat1.jpg")
        image = Image.objects.create_from_path(path)

        # Re-load the image, now that the task is done
        image = Image.objects.get(id=image.id)

        self.assertTrue(image.source.path.endswith("Sam_Hat1.jpg"))
        self.assertEqual(image.width, 3264)
        self.assertEqual(image.height, 2448)
        self.assertEqual(image.jpeg_quality, None)
        self.assertTrue(os.path.exists(image.optimized.path))
        self.assertTrue(os.path.exists(image.source.path))

        source = PILImage.open(image.source.path)
        optimized = PILImage.open(image.optimized.path)

        self.assertEqual(
            source.quantization,
            optimized.quantization
        )

        self.assertEqual(
            JpegImagePlugin.get_sampling(source),
            JpegImagePlugin.get_sampling(optimized),
        )
开发者ID:emcconville,项目名称:betty-cropper,代码行数:26,代码来源:test_image_files.py

示例3: optimize_image

def optimize_image(image_model, image_buffer, filename):

    im = PILImage.open(image_buffer)

    # Let's cache some important stuff
    format = im.format
    icc_profile = im.info.get("icc_profile")
    quantization = getattr(im, "quantization", None)
    subsampling = None
    if format == "JPEG":
        try:
            subsampling = JpegImagePlugin.get_sampling(im)
        except IndexError:
            # Ignore if sampling fails
            logger.debug('JPEG sampling failed, ignoring')
        except:
            # mparent(2016-03-25): Eventually eliminate "catch all", but need to log errors to see
            # if we're missing any other exception types in the wild
            logger.exception('JPEG sampling error')

    if im.size[0] > settings.BETTY_MAX_WIDTH:
        # If the image is really large, we'll save a more reasonable version as the "original"
        height = settings.BETTY_MAX_WIDTH * float(im.size[1]) / float(im.size[0])
        im = im.resize((settings.BETTY_MAX_WIDTH, int(round(height))), PILImage.ANTIALIAS)

        out_buffer = io.BytesIO()
        if format == "JPEG" and im.mode == "RGB":
            # For JPEG files, we need to make sure that we keep the quantization profile
            try:
                im.save(
                    out_buffer,
                    icc_profile=icc_profile,
                    qtables=quantization,
                    subsampling=subsampling,
                    format="JPEG")
            except ValueError as e:
                # Maybe the image already had an invalid quant table?
                if e.args[:1] == ('Invalid quantization table',):
                    out_buffer = io.BytesIO()  # Make sure it's empty after failed save attempt
                    im.save(
                        out_buffer,
                        icc_profile=icc_profile,
                        format=format,
                    )
                else:
                    raise
        else:
            im.save(out_buffer,
                    icc_profile=icc_profile,
                    format=format)

        image_model.optimized.save(filename, File(out_buffer))

    else:
        # No modifications, just save original as optimized
        image_buffer.seek(0)
        image_model.optimized.save(filename, File(image_buffer))

    image_model.save()
开发者ID:theonion,项目名称:betty-cropper,代码行数:59,代码来源:models.py

示例4: optimize_image

def optimize_image(image):

    im = PILImage.open(image.source.path)
    
    # Let's cache some important stuff
    format = im.format
    icc_profile = im.info.get("icc_profile")
    quantization = getattr(im, "quantization", None)
    subsampling = None
    if format == "JPEG":
        try:
            subsampling = JpegImagePlugin.get_sampling(im)
        except:
            pass  # Sometimes, crazy images exist.

    filename = os.path.split(image.source.path)[1]

    if im.size[0] > settings.BETTY_MAX_WIDTH:
        # If the image is really large, we'll save a more reasonable version as the "original"
        height = settings.BETTY_MAX_WIDTH * float(im.size[1]) / float(im.size[0])
        im = im.resize((settings.BETTY_MAX_WIDTH, int(round(height))), PILImage.ANTIALIAS)

        """OK, so this suuuuuucks. When we convert or resize an Image, it
        is no longer a JPEG. So, in order to reset the quanitzation, etc,
        we need to save this to a file and then re-read it from the
        filesystem. Silly, I know. Once my pull request is approved, this
        can be removed, and we can just pass the qtables into the save method.
        PR is here: https://github.com/python-imaging/Pillow/pull/677
        """
        temp = tempfile.NamedTemporaryFile()
        im.save(temp, format="JPEG")
        temp.seek(0)
        im = PILImage.open(temp)

        im.quantization = quantization

    image.optimized.name = optimized_upload_to(image, filename)
    if format == "JPEG" and im.mode == "RGB":
        # For JPEG files, we need to make sure that we keep the quantization profile
        try:
            im.save(
                image.optimized.name,
                icc_profile=icc_profile,
                quality="keep",
                subsampling=subsampling)
        except (TypeError, ValueError) as e:
            # Maybe the image already had an invalid quant table?
            if e.message.startswith("Not a valid numbers of quantization tables"):
                im.save(
                    image.optimized.name,
                    icc_profile=icc_profile
                )
            else:
                raise
    else:
        im.save(image.optimized.name, icc_profile=icc_profile)
    image.save()
开发者ID:emcconville,项目名称:betty-cropper,代码行数:57,代码来源:models.py

示例5: test_jpeg

def test_jpeg():
    shutil.rmtree(bettysettings.BETTY_IMAGE_ROOT, ignore_errors=True)

    path = os.path.join(TEST_DATA_PATH, "Sam_Hat1.jpg")
    image = Image.objects.create_from_path(path)

    # Re-load the image, now that the task is done
    image = Image.objects.get(id=image.id)

    assert image.source.path.endswith("Sam_Hat1.jpg")
    assert image.width == 3264
    assert image.height == 2448
    assert image.jpeg_quality is None
    assert os.path.exists(image.optimized.path)
    assert os.path.exists(image.source.path)

    source = PILImage.open(image.source.path)
    optimized = PILImage.open(image.optimized.path)

    assert source.quantization == optimized.quantization
    assert JpegImagePlugin.get_sampling(source) == JpegImagePlugin.get_sampling(optimized)
开发者ID:csinchok,项目名称:betty-cropper-1,代码行数:21,代码来源:test_image_files.py

示例6: test_jpeg

def test_jpeg():

    path = os.path.join(TEST_DATA_PATH, "Sam_Hat1.jpg")
    image = Image.objects.create_from_path(path)

    # Re-load the image, now that the task is done
    image = Image.objects.get(id=image.id)

    assert image.source.path.endswith("Sam_Hat1.jpg")
    assert image.width == 3264
    assert image.height == 2448
    assert image.jpeg_quality is None
    assert os.path.exists(image.optimized.path)
    assert os.path.exists(image.source.path)
    assert not image.animated

    source = PILImage.open(image.source.path)
    optimized = PILImage.open(image.optimized.path)

    assert source.quantization == optimized.quantization
    assert JpegImagePlugin.get_sampling(source) == JpegImagePlugin.get_sampling(optimized)
开发者ID:theonion,项目名称:betty-cropper,代码行数:21,代码来源:test_image_files.py

示例7: optimize_image

def optimize_image(image):

    im = PILImage.open(image.source.path)

    # Let's cache some important stuff
    format = im.format
    icc_profile = im.info.get("icc_profile")
    quantization = getattr(im, "quantization", None)
    subsampling = None
    if format == "JPEG":
        try:
            subsampling = JpegImagePlugin.get_sampling(im)
        except:
            pass  # Sometimes, crazy images exist.

    filename = os.path.split(image.source.path)[1]

    image.optimized.name = optimized_upload_to(image, filename)
    if im.size[0] > settings.BETTY_MAX_WIDTH:
        # If the image is really large, we'll save a more reasonable version as the "original"
        height = settings.BETTY_MAX_WIDTH * float(im.size[1]) / float(im.size[0])
        im = im.resize((settings.BETTY_MAX_WIDTH, int(round(height))), PILImage.ANTIALIAS)

        if format == "JPEG" and im.mode == "RGB":
            # For JPEG files, we need to make sure that we keep the quantization profile
            try:
                im.save(
                    image.optimized.name,
                    icc_profile=icc_profile,
                    qtables=quantization,
                    subsampling=subsampling,
                    format="JPEG")
            except (TypeError, ValueError) as e:
                # Maybe the image already had an invalid quant table?
                if e.message.startswith("Not a valid numbers of quantization tables"):
                    im.save(
                        image.optimized.name,
                        icc_profile=icc_profile
                    )
                else:
                    raise
        else:
            im.save(image.optimized.name, icc_profile=icc_profile)
    else:
        shutil.copy2(image.source.path, image.optimized.name)

    image.save()
开发者ID:csinchok,项目名称:betty-cropper-1,代码行数:47,代码来源:models.py

示例8: create_image

    def create_image(self, buffer):
        img = Image.open(BytesIO(buffer))
        self.icc_profile = img.info.get('icc_profile')
        self.transparency = img.info.get('transparency')
        self.exif = img.info.get('exif')

        self.subsampling = JpegImagePlugin.get_sampling(img)
        if (self.subsampling == -1):  # n/a for this file
            self.subsampling = None
        self.qtables = getattr(img, 'quantization', None)

        if self.context.config.ALLOW_ANIMATED_GIFS and self.extension == '.gif':
            frames = []
            for frame in ImageSequence.Iterator(img):
                frames.append(frame.convert('P'))
            img.seek(0)
            self.frame_count = len(frames)
            return frames

        return img
开发者ID:beiley,项目名称:thumbor,代码行数:20,代码来源:pil.py

示例9: create_image

    def create_image(self, buffer):
        try:
            img = Image.open(BytesIO(buffer))
        except DecompressionBombExceptions as e:
            logger.warning("[PILEngine] create_image failed: {0}".format(e))
            return None
        self.icc_profile = img.info.get('icc_profile')
        self.exif = img.info.get('exif')
        self.original_mode = img.mode

        self.subsampling = JpegImagePlugin.get_sampling(img)
        if (self.subsampling == -1):  # n/a for this file
            self.subsampling = None
        self.qtables = getattr(img, 'quantization', None)

        if self.context.config.ALLOW_ANIMATED_GIFS and self.extension == '.gif':
            frames = []
            for frame in ImageSequence.Iterator(img):
                frames.append(frame.convert('P'))
            img.seek(0)
            self.frame_count = len(frames)
            return frames

        return img
开发者ID:dannyeuu,项目名称:thumbor,代码行数:24,代码来源:pil.py

示例10: getiptcinfo

def getiptcinfo(im):

    import StringIO

    data = None

    if isinstance(im, IptcImageFile):
        # return info dictionary right away
        return im.info

    elif isinstance(im, JpegImagePlugin.JpegImageFile):
        # extract the IPTC/NAA resource
        try:
            app = im.app["APP13"]
            if app[:14] == "Photoshop 3.0\x00":
                app = app[14:]
                # parse the image resource block
                offset = 0
                while app[offset:offset+4] == "8BIM":
                    offset = offset + 4
                    # resource code
                    code = JpegImagePlugin.i16(app, offset)
                    offset = offset + 2
                    # resource name (usually empty)
                    name_len = ord(app[offset])
                    name = app[offset+1:offset+1+name_len]
                    offset = 1 + offset + name_len
                    if offset & 1:
                        offset = offset + 1
                    # resource data block
                    size = JpegImagePlugin.i32(app, offset)
                    offset = offset + 4
                    if code == 0x0404:
                        # 0x0404 contains IPTC/NAA data
                        data = app[offset:offset+size]
                        break
                    offset = offset + size
                    if offset & 1:
                        offset = offset + 1
        except (AttributeError, KeyError):
            pass

    elif isinstance(im, TiffImagePlugin.TiffImageFile):
        # get raw data from the IPTC/NAA tag (PhotoShop tags the data
        # as 4-byte integers, so we cannot use the get method...)
        try:
            type, data = im.tag.tagdata[TiffImagePlugin.IPTC_NAA_CHUNK]
        except (AttributeError, KeyError):
            pass

    if data is None:
        return None # no properties

    # create an IptcImagePlugin object without initializing it
    class FakeImage:
        pass
    im = FakeImage()
    im.__class__ = IptcImageFile

    # parse the IPTC information chunk
    im.info = {}
    im.fp = StringIO.StringIO(data)

    try:
        im._open()
    except (IndexError, KeyError):
        pass # expected failure

    return im.info
开发者ID:gefferson,项目名称:projeto_extensao,代码行数:69,代码来源:IptcImagePlugin.py

示例11: _save

def _save(im, fp, filename):
    # Note that we can only save the current frame at present
    return JpegImagePlugin._save(im, fp, filename)
开发者ID:AnubhabB,项目名称:Pillow,代码行数:3,代码来源:MpoImagePlugin.py

示例12: _accept

def _accept(prefix):
    return JpegImagePlugin._accept(prefix)
开发者ID:AnubhabB,项目名称:Pillow,代码行数:2,代码来源:MpoImagePlugin.py


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