本文整理汇总了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)
示例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),
)
示例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()
示例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()
示例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)
示例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)
示例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()
示例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
示例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
示例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
示例11: _save
def _save(im, fp, filename):
# Note that we can only save the current frame at present
return JpegImagePlugin._save(im, fp, filename)
示例12: _accept
def _accept(prefix):
return JpegImagePlugin._accept(prefix)