2010-07-31 06:52:47 +04:00
|
|
|
#
|
|
|
|
# The Python Imaging Library.
|
|
|
|
# $Id$
|
|
|
|
#
|
|
|
|
# JPEG (JFIF) file handling
|
|
|
|
#
|
2015-05-29 07:59:54 +03:00
|
|
|
# See "Digital Compression and Coding of Continuous-Tone Still Images,
|
2010-07-31 06:52:47 +04:00
|
|
|
# Part 1, Requirements and Guidelines" (CCITT T.81 / ISO 10918-1)
|
|
|
|
#
|
|
|
|
# History:
|
|
|
|
# 1995-09-09 fl Created
|
|
|
|
# 1995-09-13 fl Added full parser
|
|
|
|
# 1996-03-25 fl Added hack to use the IJG command line utilities
|
|
|
|
# 1996-05-05 fl Workaround Photoshop 2.5 CMYK polarity bug
|
|
|
|
# 1996-05-28 fl Added draft support, JFIF version (0.1)
|
|
|
|
# 1996-12-30 fl Added encoder options, added progression property (0.2)
|
|
|
|
# 1997-08-27 fl Save mode 1 images as BW (0.3)
|
|
|
|
# 1998-07-12 fl Added YCbCr to draft and save methods (0.4)
|
|
|
|
# 1998-10-19 fl Don't hang on files using 16-bit DQT's (0.4.1)
|
|
|
|
# 2001-04-16 fl Extract DPI settings from JFIF files (0.4.2)
|
|
|
|
# 2002-07-01 fl Skip pad bytes before markers; identify Exif files (0.4.3)
|
|
|
|
# 2003-04-25 fl Added experimental EXIF decoder (0.5)
|
|
|
|
# 2003-06-06 fl Added experimental EXIF GPSinfo decoder
|
|
|
|
# 2003-09-13 fl Extract COM markers
|
|
|
|
# 2009-09-06 fl Added icc_profile support (from Florian Hoech)
|
|
|
|
# 2009-03-06 fl Changed CMYK handling; always use Adobe polarity (0.6)
|
|
|
|
# 2009-03-08 fl Added subsampling support (from Justin Huff).
|
|
|
|
#
|
|
|
|
# Copyright (c) 1997-2003 by Secret Labs AB.
|
|
|
|
# Copyright (c) 1995-1996 by Fredrik Lundh.
|
|
|
|
#
|
|
|
|
# See the README file for information on usage and redistribution.
|
|
|
|
#
|
|
|
|
|
2014-05-05 23:41:09 +04:00
|
|
|
import array
|
|
|
|
import struct
|
2014-07-16 19:36:56 +04:00
|
|
|
import io
|
2015-07-19 15:56:04 +03:00
|
|
|
import warnings
|
2015-01-14 10:07:41 +03:00
|
|
|
from struct import unpack_from
|
2014-07-16 19:36:56 +04:00
|
|
|
from PIL import Image, ImageFile, TiffImagePlugin, _binary
|
2013-03-26 16:36:13 +04:00
|
|
|
from PIL.JpegPresets import presets
|
2013-06-30 15:04:42 +04:00
|
|
|
from PIL._util import isStringType
|
2010-07-31 06:52:47 +04:00
|
|
|
|
py3k: The big push
There are two main issues fixed with this commit:
* bytes vs. str: All file, image, and palette data are now handled as
bytes. A new _binary module consolidates the hacks needed to do this
across Python versions. tostring/fromstring methods have been renamed to
tobytes/frombytes, but the Python 2.6/2.7 versions alias them to the old
names for compatibility. Users should move to tobytes/frombytes.
One other potentially-breaking change is that text data in image files
(such as tags, comments) are now explicitly handled with a specific
character encoding in mind. This works well with the Unicode str in
Python 3, but may trip up old code expecting a straight byte-for-byte
translation to a Python string. This also required a change to Gohlke's
tags tests (in Tests/test_file_png.py) to expect Unicode strings from
the code.
* True div vs. floor div: Many division operations used the "/" operator
to do floor division, which is now the "//" operator in Python 3. These
were fixed.
As of this commit, on the first pass, I have one failing test (improper
handling of a slice object in a C module, test_imagepath.py) in Python 3,
and three that that I haven't tried running yet (test_imagegl,
test_imagegrab, and test_imageqt). I also haven't tested anything on
Windows. All but the three skipped tests run flawlessly against Pythons
2.6 and 2.7.
2012-10-21 01:01:53 +04:00
|
|
|
i8 = _binary.i8
|
|
|
|
o8 = _binary.o8
|
|
|
|
i16 = _binary.i16be
|
|
|
|
i32 = _binary.i32be
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2015-08-25 15:27:18 +03:00
|
|
|
__version__ = "0.6"
|
|
|
|
|
2014-05-05 23:41:09 +04:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
#
|
|
|
|
# Parser
|
|
|
|
|
|
|
|
def Skip(self, marker):
|
|
|
|
n = i16(self.fp.read(2))-2
|
|
|
|
ImageFile._safe_read(self.fp, n)
|
|
|
|
|
2014-05-05 23:41:09 +04:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
def APP(self, marker):
|
|
|
|
#
|
|
|
|
# Application marker. Store these in the APP dictionary.
|
|
|
|
# Also look for well-known application markers.
|
|
|
|
|
|
|
|
n = i16(self.fp.read(2))-2
|
|
|
|
s = ImageFile._safe_read(self.fp, n)
|
|
|
|
|
2014-05-05 23:41:09 +04:00
|
|
|
app = "APP%d" % (marker & 15)
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2014-05-05 23:41:09 +04:00
|
|
|
self.app[app] = s # compatibility
|
2010-07-31 06:52:47 +04:00
|
|
|
self.applist.append((app, s))
|
|
|
|
|
py3k: The big push
There are two main issues fixed with this commit:
* bytes vs. str: All file, image, and palette data are now handled as
bytes. A new _binary module consolidates the hacks needed to do this
across Python versions. tostring/fromstring methods have been renamed to
tobytes/frombytes, but the Python 2.6/2.7 versions alias them to the old
names for compatibility. Users should move to tobytes/frombytes.
One other potentially-breaking change is that text data in image files
(such as tags, comments) are now explicitly handled with a specific
character encoding in mind. This works well with the Unicode str in
Python 3, but may trip up old code expecting a straight byte-for-byte
translation to a Python string. This also required a change to Gohlke's
tags tests (in Tests/test_file_png.py) to expect Unicode strings from
the code.
* True div vs. floor div: Many division operations used the "/" operator
to do floor division, which is now the "//" operator in Python 3. These
were fixed.
As of this commit, on the first pass, I have one failing test (improper
handling of a slice object in a C module, test_imagepath.py) in Python 3,
and three that that I haven't tried running yet (test_imagegl,
test_imagegrab, and test_imageqt). I also haven't tested anything on
Windows. All but the three skipped tests run flawlessly against Pythons
2.6 and 2.7.
2012-10-21 01:01:53 +04:00
|
|
|
if marker == 0xFFE0 and s[:4] == b"JFIF":
|
2010-07-31 06:52:47 +04:00
|
|
|
# extract JFIF information
|
2014-05-05 23:41:09 +04:00
|
|
|
self.info["jfif"] = version = i16(s, 5) # version
|
2010-07-31 06:52:47 +04:00
|
|
|
self.info["jfif_version"] = divmod(version, 256)
|
|
|
|
# extract JFIF properties
|
|
|
|
try:
|
py3k: The big push
There are two main issues fixed with this commit:
* bytes vs. str: All file, image, and palette data are now handled as
bytes. A new _binary module consolidates the hacks needed to do this
across Python versions. tostring/fromstring methods have been renamed to
tobytes/frombytes, but the Python 2.6/2.7 versions alias them to the old
names for compatibility. Users should move to tobytes/frombytes.
One other potentially-breaking change is that text data in image files
(such as tags, comments) are now explicitly handled with a specific
character encoding in mind. This works well with the Unicode str in
Python 3, but may trip up old code expecting a straight byte-for-byte
translation to a Python string. This also required a change to Gohlke's
tags tests (in Tests/test_file_png.py) to expect Unicode strings from
the code.
* True div vs. floor div: Many division operations used the "/" operator
to do floor division, which is now the "//" operator in Python 3. These
were fixed.
As of this commit, on the first pass, I have one failing test (improper
handling of a slice object in a C module, test_imagepath.py) in Python 3,
and three that that I haven't tried running yet (test_imagegl,
test_imagegrab, and test_imageqt). I also haven't tested anything on
Windows. All but the three skipped tests run flawlessly against Pythons
2.6 and 2.7.
2012-10-21 01:01:53 +04:00
|
|
|
jfif_unit = i8(s[7])
|
2010-07-31 06:52:47 +04:00
|
|
|
jfif_density = i16(s, 8), i16(s, 10)
|
|
|
|
except:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
if jfif_unit == 1:
|
|
|
|
self.info["dpi"] = jfif_density
|
|
|
|
self.info["jfif_unit"] = jfif_unit
|
|
|
|
self.info["jfif_density"] = jfif_density
|
py3k: The big push
There are two main issues fixed with this commit:
* bytes vs. str: All file, image, and palette data are now handled as
bytes. A new _binary module consolidates the hacks needed to do this
across Python versions. tostring/fromstring methods have been renamed to
tobytes/frombytes, but the Python 2.6/2.7 versions alias them to the old
names for compatibility. Users should move to tobytes/frombytes.
One other potentially-breaking change is that text data in image files
(such as tags, comments) are now explicitly handled with a specific
character encoding in mind. This works well with the Unicode str in
Python 3, but may trip up old code expecting a straight byte-for-byte
translation to a Python string. This also required a change to Gohlke's
tags tests (in Tests/test_file_png.py) to expect Unicode strings from
the code.
* True div vs. floor div: Many division operations used the "/" operator
to do floor division, which is now the "//" operator in Python 3. These
were fixed.
As of this commit, on the first pass, I have one failing test (improper
handling of a slice object in a C module, test_imagepath.py) in Python 3,
and three that that I haven't tried running yet (test_imagegl,
test_imagegrab, and test_imageqt). I also haven't tested anything on
Windows. All but the three skipped tests run flawlessly against Pythons
2.6 and 2.7.
2012-10-21 01:01:53 +04:00
|
|
|
elif marker == 0xFFE1 and s[:5] == b"Exif\0":
|
2010-07-31 06:52:47 +04:00
|
|
|
# extract Exif information (incomplete)
|
2014-05-05 23:41:09 +04:00
|
|
|
self.info["exif"] = s # FIXME: value will change
|
py3k: The big push
There are two main issues fixed with this commit:
* bytes vs. str: All file, image, and palette data are now handled as
bytes. A new _binary module consolidates the hacks needed to do this
across Python versions. tostring/fromstring methods have been renamed to
tobytes/frombytes, but the Python 2.6/2.7 versions alias them to the old
names for compatibility. Users should move to tobytes/frombytes.
One other potentially-breaking change is that text data in image files
(such as tags, comments) are now explicitly handled with a specific
character encoding in mind. This works well with the Unicode str in
Python 3, but may trip up old code expecting a straight byte-for-byte
translation to a Python string. This also required a change to Gohlke's
tags tests (in Tests/test_file_png.py) to expect Unicode strings from
the code.
* True div vs. floor div: Many division operations used the "/" operator
to do floor division, which is now the "//" operator in Python 3. These
were fixed.
As of this commit, on the first pass, I have one failing test (improper
handling of a slice object in a C module, test_imagepath.py) in Python 3,
and three that that I haven't tried running yet (test_imagegl,
test_imagegrab, and test_imageqt). I also haven't tested anything on
Windows. All but the three skipped tests run flawlessly against Pythons
2.6 and 2.7.
2012-10-21 01:01:53 +04:00
|
|
|
elif marker == 0xFFE2 and s[:5] == b"FPXR\0":
|
2010-07-31 06:52:47 +04:00
|
|
|
# extract FlashPix information (incomplete)
|
2014-05-05 23:41:09 +04:00
|
|
|
self.info["flashpix"] = s # FIXME: value will change
|
py3k: The big push
There are two main issues fixed with this commit:
* bytes vs. str: All file, image, and palette data are now handled as
bytes. A new _binary module consolidates the hacks needed to do this
across Python versions. tostring/fromstring methods have been renamed to
tobytes/frombytes, but the Python 2.6/2.7 versions alias them to the old
names for compatibility. Users should move to tobytes/frombytes.
One other potentially-breaking change is that text data in image files
(such as tags, comments) are now explicitly handled with a specific
character encoding in mind. This works well with the Unicode str in
Python 3, but may trip up old code expecting a straight byte-for-byte
translation to a Python string. This also required a change to Gohlke's
tags tests (in Tests/test_file_png.py) to expect Unicode strings from
the code.
* True div vs. floor div: Many division operations used the "/" operator
to do floor division, which is now the "//" operator in Python 3. These
were fixed.
As of this commit, on the first pass, I have one failing test (improper
handling of a slice object in a C module, test_imagepath.py) in Python 3,
and three that that I haven't tried running yet (test_imagegl,
test_imagegrab, and test_imageqt). I also haven't tested anything on
Windows. All but the three skipped tests run flawlessly against Pythons
2.6 and 2.7.
2012-10-21 01:01:53 +04:00
|
|
|
elif marker == 0xFFE2 and s[:12] == b"ICC_PROFILE\0":
|
2010-07-31 06:52:47 +04:00
|
|
|
# Since an ICC profile can be larger than the maximum size of
|
|
|
|
# a JPEG marker (64K), we need provisions to split it into
|
|
|
|
# multiple markers. The format defined by the ICC specifies
|
|
|
|
# one or more APP2 markers containing the following data:
|
|
|
|
# Identifying string ASCII "ICC_PROFILE\0" (12 bytes)
|
|
|
|
# Marker sequence number 1, 2, etc (1 byte)
|
|
|
|
# Number of markers Total of APP2's used (1 byte)
|
|
|
|
# Profile data (remainder of APP2 data)
|
|
|
|
# Decoders should use the marker sequence numbers to
|
|
|
|
# reassemble the profile, rather than assuming that the APP2
|
|
|
|
# markers appear in the correct sequence.
|
|
|
|
self.icclist.append(s)
|
py3k: The big push
There are two main issues fixed with this commit:
* bytes vs. str: All file, image, and palette data are now handled as
bytes. A new _binary module consolidates the hacks needed to do this
across Python versions. tostring/fromstring methods have been renamed to
tobytes/frombytes, but the Python 2.6/2.7 versions alias them to the old
names for compatibility. Users should move to tobytes/frombytes.
One other potentially-breaking change is that text data in image files
(such as tags, comments) are now explicitly handled with a specific
character encoding in mind. This works well with the Unicode str in
Python 3, but may trip up old code expecting a straight byte-for-byte
translation to a Python string. This also required a change to Gohlke's
tags tests (in Tests/test_file_png.py) to expect Unicode strings from
the code.
* True div vs. floor div: Many division operations used the "/" operator
to do floor division, which is now the "//" operator in Python 3. These
were fixed.
As of this commit, on the first pass, I have one failing test (improper
handling of a slice object in a C module, test_imagepath.py) in Python 3,
and three that that I haven't tried running yet (test_imagegl,
test_imagegrab, and test_imageqt). I also haven't tested anything on
Windows. All but the three skipped tests run flawlessly against Pythons
2.6 and 2.7.
2012-10-21 01:01:53 +04:00
|
|
|
elif marker == 0xFFEE and s[:5] == b"Adobe":
|
2010-07-31 06:52:47 +04:00
|
|
|
self.info["adobe"] = i16(s, 5)
|
|
|
|
# extract Adobe custom properties
|
|
|
|
try:
|
py3k: The big push
There are two main issues fixed with this commit:
* bytes vs. str: All file, image, and palette data are now handled as
bytes. A new _binary module consolidates the hacks needed to do this
across Python versions. tostring/fromstring methods have been renamed to
tobytes/frombytes, but the Python 2.6/2.7 versions alias them to the old
names for compatibility. Users should move to tobytes/frombytes.
One other potentially-breaking change is that text data in image files
(such as tags, comments) are now explicitly handled with a specific
character encoding in mind. This works well with the Unicode str in
Python 3, but may trip up old code expecting a straight byte-for-byte
translation to a Python string. This also required a change to Gohlke's
tags tests (in Tests/test_file_png.py) to expect Unicode strings from
the code.
* True div vs. floor div: Many division operations used the "/" operator
to do floor division, which is now the "//" operator in Python 3. These
were fixed.
As of this commit, on the first pass, I have one failing test (improper
handling of a slice object in a C module, test_imagepath.py) in Python 3,
and three that that I haven't tried running yet (test_imagegl,
test_imagegrab, and test_imageqt). I also haven't tested anything on
Windows. All but the three skipped tests run flawlessly against Pythons
2.6 and 2.7.
2012-10-21 01:01:53 +04:00
|
|
|
adobe_transform = i8(s[1])
|
2010-07-31 06:52:47 +04:00
|
|
|
except:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
self.info["adobe_transform"] = adobe_transform
|
2014-07-16 19:36:56 +04:00
|
|
|
elif marker == 0xFFE2 and s[:4] == b"MPF\0":
|
|
|
|
# extract MPO information
|
|
|
|
self.info["mp"] = s[4:]
|
2014-08-28 15:44:19 +04:00
|
|
|
# offset is current location minus buffer size
|
|
|
|
# plus constant header size
|
2014-07-23 02:23:45 +04:00
|
|
|
self.info["mpoffset"] = self.fp.tell() - n + 4
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2014-05-05 23:41:09 +04:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
def COM(self, marker):
|
|
|
|
#
|
|
|
|
# Comment marker. Store these in the APP dictionary.
|
|
|
|
n = i16(self.fp.read(2))-2
|
|
|
|
s = ImageFile._safe_read(self.fp, n)
|
|
|
|
|
2014-05-05 23:41:09 +04:00
|
|
|
self.app["COM"] = s # compatibility
|
2010-07-31 06:52:47 +04:00
|
|
|
self.applist.append(("COM", s))
|
|
|
|
|
2014-05-05 23:41:09 +04:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
def SOF(self, marker):
|
|
|
|
#
|
|
|
|
# Start of frame marker. Defines the size and mode of the
|
|
|
|
# image. JPEG is colour blind, so we use some simple
|
|
|
|
# heuristics to map the number of layers to an appropriate
|
|
|
|
# mode. Note that this could be made a bit brighter, by
|
|
|
|
# looking for JFIF and Adobe APP markers.
|
|
|
|
|
|
|
|
n = i16(self.fp.read(2))-2
|
|
|
|
s = ImageFile._safe_read(self.fp, n)
|
|
|
|
self.size = i16(s[3:]), i16(s[1:])
|
|
|
|
|
py3k: The big push
There are two main issues fixed with this commit:
* bytes vs. str: All file, image, and palette data are now handled as
bytes. A new _binary module consolidates the hacks needed to do this
across Python versions. tostring/fromstring methods have been renamed to
tobytes/frombytes, but the Python 2.6/2.7 versions alias them to the old
names for compatibility. Users should move to tobytes/frombytes.
One other potentially-breaking change is that text data in image files
(such as tags, comments) are now explicitly handled with a specific
character encoding in mind. This works well with the Unicode str in
Python 3, but may trip up old code expecting a straight byte-for-byte
translation to a Python string. This also required a change to Gohlke's
tags tests (in Tests/test_file_png.py) to expect Unicode strings from
the code.
* True div vs. floor div: Many division operations used the "/" operator
to do floor division, which is now the "//" operator in Python 3. These
were fixed.
As of this commit, on the first pass, I have one failing test (improper
handling of a slice object in a C module, test_imagepath.py) in Python 3,
and three that that I haven't tried running yet (test_imagegl,
test_imagegrab, and test_imageqt). I also haven't tested anything on
Windows. All but the three skipped tests run flawlessly against Pythons
2.6 and 2.7.
2012-10-21 01:01:53 +04:00
|
|
|
self.bits = i8(s[0])
|
2010-07-31 06:52:47 +04:00
|
|
|
if self.bits != 8:
|
|
|
|
raise SyntaxError("cannot handle %d-bit layers" % self.bits)
|
|
|
|
|
py3k: The big push
There are two main issues fixed with this commit:
* bytes vs. str: All file, image, and palette data are now handled as
bytes. A new _binary module consolidates the hacks needed to do this
across Python versions. tostring/fromstring methods have been renamed to
tobytes/frombytes, but the Python 2.6/2.7 versions alias them to the old
names for compatibility. Users should move to tobytes/frombytes.
One other potentially-breaking change is that text data in image files
(such as tags, comments) are now explicitly handled with a specific
character encoding in mind. This works well with the Unicode str in
Python 3, but may trip up old code expecting a straight byte-for-byte
translation to a Python string. This also required a change to Gohlke's
tags tests (in Tests/test_file_png.py) to expect Unicode strings from
the code.
* True div vs. floor div: Many division operations used the "/" operator
to do floor division, which is now the "//" operator in Python 3. These
were fixed.
As of this commit, on the first pass, I have one failing test (improper
handling of a slice object in a C module, test_imagepath.py) in Python 3,
and three that that I haven't tried running yet (test_imagegl,
test_imagegrab, and test_imageqt). I also haven't tested anything on
Windows. All but the three skipped tests run flawlessly against Pythons
2.6 and 2.7.
2012-10-21 01:01:53 +04:00
|
|
|
self.layers = i8(s[5])
|
2010-07-31 06:52:47 +04:00
|
|
|
if self.layers == 1:
|
|
|
|
self.mode = "L"
|
|
|
|
elif self.layers == 3:
|
|
|
|
self.mode = "RGB"
|
|
|
|
elif self.layers == 4:
|
|
|
|
self.mode = "CMYK"
|
|
|
|
else:
|
|
|
|
raise SyntaxError("cannot handle %d-layer images" % self.layers)
|
|
|
|
|
|
|
|
if marker in [0xFFC2, 0xFFC6, 0xFFCA, 0xFFCE]:
|
|
|
|
self.info["progressive"] = self.info["progression"] = 1
|
|
|
|
|
|
|
|
if self.icclist:
|
|
|
|
# fixup icc profile
|
2014-05-05 23:41:09 +04:00
|
|
|
self.icclist.sort() # sort by sequence number
|
py3k: The big push
There are two main issues fixed with this commit:
* bytes vs. str: All file, image, and palette data are now handled as
bytes. A new _binary module consolidates the hacks needed to do this
across Python versions. tostring/fromstring methods have been renamed to
tobytes/frombytes, but the Python 2.6/2.7 versions alias them to the old
names for compatibility. Users should move to tobytes/frombytes.
One other potentially-breaking change is that text data in image files
(such as tags, comments) are now explicitly handled with a specific
character encoding in mind. This works well with the Unicode str in
Python 3, but may trip up old code expecting a straight byte-for-byte
translation to a Python string. This also required a change to Gohlke's
tags tests (in Tests/test_file_png.py) to expect Unicode strings from
the code.
* True div vs. floor div: Many division operations used the "/" operator
to do floor division, which is now the "//" operator in Python 3. These
were fixed.
As of this commit, on the first pass, I have one failing test (improper
handling of a slice object in a C module, test_imagepath.py) in Python 3,
and three that that I haven't tried running yet (test_imagegl,
test_imagegrab, and test_imageqt). I also haven't tested anything on
Windows. All but the three skipped tests run flawlessly against Pythons
2.6 and 2.7.
2012-10-21 01:01:53 +04:00
|
|
|
if i8(self.icclist[0][13]) == len(self.icclist):
|
2010-07-31 06:52:47 +04:00
|
|
|
profile = []
|
|
|
|
for p in self.icclist:
|
|
|
|
profile.append(p[14:])
|
py3k: The big push
There are two main issues fixed with this commit:
* bytes vs. str: All file, image, and palette data are now handled as
bytes. A new _binary module consolidates the hacks needed to do this
across Python versions. tostring/fromstring methods have been renamed to
tobytes/frombytes, but the Python 2.6/2.7 versions alias them to the old
names for compatibility. Users should move to tobytes/frombytes.
One other potentially-breaking change is that text data in image files
(such as tags, comments) are now explicitly handled with a specific
character encoding in mind. This works well with the Unicode str in
Python 3, but may trip up old code expecting a straight byte-for-byte
translation to a Python string. This also required a change to Gohlke's
tags tests (in Tests/test_file_png.py) to expect Unicode strings from
the code.
* True div vs. floor div: Many division operations used the "/" operator
to do floor division, which is now the "//" operator in Python 3. These
were fixed.
As of this commit, on the first pass, I have one failing test (improper
handling of a slice object in a C module, test_imagepath.py) in Python 3,
and three that that I haven't tried running yet (test_imagegl,
test_imagegrab, and test_imageqt). I also haven't tested anything on
Windows. All but the three skipped tests run flawlessly against Pythons
2.6 and 2.7.
2012-10-21 01:01:53 +04:00
|
|
|
icc_profile = b"".join(profile)
|
2010-07-31 06:52:47 +04:00
|
|
|
else:
|
2014-05-05 23:41:09 +04:00
|
|
|
icc_profile = None # wrong number of fragments
|
2010-07-31 06:52:47 +04:00
|
|
|
self.info["icc_profile"] = icc_profile
|
|
|
|
self.icclist = None
|
|
|
|
|
|
|
|
for i in range(6, len(s), 3):
|
|
|
|
t = s[i:i+3]
|
|
|
|
# 4-tuples: id, vsamp, hsamp, qtable
|
2014-05-05 23:41:09 +04:00
|
|
|
self.layer.append((t[0], i8(t[1])//16, i8(t[1]) & 15, i8(t[2])))
|
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
def DQT(self, marker):
|
|
|
|
#
|
|
|
|
# Define quantization table. Support baseline 8-bit tables
|
|
|
|
# only. Note that there might be more than one table in
|
|
|
|
# each marker.
|
|
|
|
|
|
|
|
# FIXME: The quantization tables can be used to estimate the
|
|
|
|
# compression quality.
|
|
|
|
|
|
|
|
n = i16(self.fp.read(2))-2
|
|
|
|
s = ImageFile._safe_read(self.fp, n)
|
|
|
|
while len(s):
|
|
|
|
if len(s) < 65:
|
|
|
|
raise SyntaxError("bad quantization table marker")
|
py3k: The big push
There are two main issues fixed with this commit:
* bytes vs. str: All file, image, and palette data are now handled as
bytes. A new _binary module consolidates the hacks needed to do this
across Python versions. tostring/fromstring methods have been renamed to
tobytes/frombytes, but the Python 2.6/2.7 versions alias them to the old
names for compatibility. Users should move to tobytes/frombytes.
One other potentially-breaking change is that text data in image files
(such as tags, comments) are now explicitly handled with a specific
character encoding in mind. This works well with the Unicode str in
Python 3, but may trip up old code expecting a straight byte-for-byte
translation to a Python string. This also required a change to Gohlke's
tags tests (in Tests/test_file_png.py) to expect Unicode strings from
the code.
* True div vs. floor div: Many division operations used the "/" operator
to do floor division, which is now the "//" operator in Python 3. These
were fixed.
As of this commit, on the first pass, I have one failing test (improper
handling of a slice object in a C module, test_imagepath.py) in Python 3,
and three that that I haven't tried running yet (test_imagegl,
test_imagegrab, and test_imageqt). I also haven't tested anything on
Windows. All but the three skipped tests run flawlessly against Pythons
2.6 and 2.7.
2012-10-21 01:01:53 +04:00
|
|
|
v = i8(s[0])
|
|
|
|
if v//16 == 0:
|
2014-05-05 23:41:09 +04:00
|
|
|
self.quantization[v & 15] = array.array("b", s[1:65])
|
2010-07-31 06:52:47 +04:00
|
|
|
s = s[65:]
|
|
|
|
else:
|
2014-05-05 23:41:09 +04:00
|
|
|
return # FIXME: add code to read 16-bit tables!
|
2010-07-31 06:52:47 +04:00
|
|
|
# raise SyntaxError, "bad quantization table element size"
|
|
|
|
|
|
|
|
|
|
|
|
#
|
|
|
|
# JPEG marker table
|
|
|
|
|
|
|
|
MARKER = {
|
|
|
|
0xFFC0: ("SOF0", "Baseline DCT", SOF),
|
|
|
|
0xFFC1: ("SOF1", "Extended Sequential DCT", SOF),
|
|
|
|
0xFFC2: ("SOF2", "Progressive DCT", SOF),
|
|
|
|
0xFFC3: ("SOF3", "Spatial lossless", SOF),
|
|
|
|
0xFFC4: ("DHT", "Define Huffman table", Skip),
|
|
|
|
0xFFC5: ("SOF5", "Differential sequential DCT", SOF),
|
|
|
|
0xFFC6: ("SOF6", "Differential progressive DCT", SOF),
|
|
|
|
0xFFC7: ("SOF7", "Differential spatial", SOF),
|
|
|
|
0xFFC8: ("JPG", "Extension", None),
|
|
|
|
0xFFC9: ("SOF9", "Extended sequential DCT (AC)", SOF),
|
|
|
|
0xFFCA: ("SOF10", "Progressive DCT (AC)", SOF),
|
|
|
|
0xFFCB: ("SOF11", "Spatial lossless DCT (AC)", SOF),
|
|
|
|
0xFFCC: ("DAC", "Define arithmetic coding conditioning", Skip),
|
|
|
|
0xFFCD: ("SOF13", "Differential sequential DCT (AC)", SOF),
|
|
|
|
0xFFCE: ("SOF14", "Differential progressive DCT (AC)", SOF),
|
|
|
|
0xFFCF: ("SOF15", "Differential spatial (AC)", SOF),
|
|
|
|
0xFFD0: ("RST0", "Restart 0", None),
|
|
|
|
0xFFD1: ("RST1", "Restart 1", None),
|
|
|
|
0xFFD2: ("RST2", "Restart 2", None),
|
|
|
|
0xFFD3: ("RST3", "Restart 3", None),
|
|
|
|
0xFFD4: ("RST4", "Restart 4", None),
|
|
|
|
0xFFD5: ("RST5", "Restart 5", None),
|
|
|
|
0xFFD6: ("RST6", "Restart 6", None),
|
|
|
|
0xFFD7: ("RST7", "Restart 7", None),
|
|
|
|
0xFFD8: ("SOI", "Start of image", None),
|
|
|
|
0xFFD9: ("EOI", "End of image", None),
|
|
|
|
0xFFDA: ("SOS", "Start of scan", Skip),
|
|
|
|
0xFFDB: ("DQT", "Define quantization table", DQT),
|
|
|
|
0xFFDC: ("DNL", "Define number of lines", Skip),
|
|
|
|
0xFFDD: ("DRI", "Define restart interval", Skip),
|
|
|
|
0xFFDE: ("DHP", "Define hierarchical progression", SOF),
|
|
|
|
0xFFDF: ("EXP", "Expand reference component", Skip),
|
|
|
|
0xFFE0: ("APP0", "Application segment 0", APP),
|
|
|
|
0xFFE1: ("APP1", "Application segment 1", APP),
|
|
|
|
0xFFE2: ("APP2", "Application segment 2", APP),
|
|
|
|
0xFFE3: ("APP3", "Application segment 3", APP),
|
|
|
|
0xFFE4: ("APP4", "Application segment 4", APP),
|
|
|
|
0xFFE5: ("APP5", "Application segment 5", APP),
|
|
|
|
0xFFE6: ("APP6", "Application segment 6", APP),
|
|
|
|
0xFFE7: ("APP7", "Application segment 7", APP),
|
|
|
|
0xFFE8: ("APP8", "Application segment 8", APP),
|
|
|
|
0xFFE9: ("APP9", "Application segment 9", APP),
|
|
|
|
0xFFEA: ("APP10", "Application segment 10", APP),
|
|
|
|
0xFFEB: ("APP11", "Application segment 11", APP),
|
|
|
|
0xFFEC: ("APP12", "Application segment 12", APP),
|
|
|
|
0xFFED: ("APP13", "Application segment 13", APP),
|
|
|
|
0xFFEE: ("APP14", "Application segment 14", APP),
|
|
|
|
0xFFEF: ("APP15", "Application segment 15", APP),
|
|
|
|
0xFFF0: ("JPG0", "Extension 0", None),
|
|
|
|
0xFFF1: ("JPG1", "Extension 1", None),
|
|
|
|
0xFFF2: ("JPG2", "Extension 2", None),
|
|
|
|
0xFFF3: ("JPG3", "Extension 3", None),
|
|
|
|
0xFFF4: ("JPG4", "Extension 4", None),
|
|
|
|
0xFFF5: ("JPG5", "Extension 5", None),
|
|
|
|
0xFFF6: ("JPG6", "Extension 6", None),
|
|
|
|
0xFFF7: ("JPG7", "Extension 7", None),
|
|
|
|
0xFFF8: ("JPG8", "Extension 8", None),
|
|
|
|
0xFFF9: ("JPG9", "Extension 9", None),
|
|
|
|
0xFFFA: ("JPG10", "Extension 10", None),
|
|
|
|
0xFFFB: ("JPG11", "Extension 11", None),
|
|
|
|
0xFFFC: ("JPG12", "Extension 12", None),
|
|
|
|
0xFFFD: ("JPG13", "Extension 13", None),
|
|
|
|
0xFFFE: ("COM", "Comment", COM)
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
def _accept(prefix):
|
py3k: The big push
There are two main issues fixed with this commit:
* bytes vs. str: All file, image, and palette data are now handled as
bytes. A new _binary module consolidates the hacks needed to do this
across Python versions. tostring/fromstring methods have been renamed to
tobytes/frombytes, but the Python 2.6/2.7 versions alias them to the old
names for compatibility. Users should move to tobytes/frombytes.
One other potentially-breaking change is that text data in image files
(such as tags, comments) are now explicitly handled with a specific
character encoding in mind. This works well with the Unicode str in
Python 3, but may trip up old code expecting a straight byte-for-byte
translation to a Python string. This also required a change to Gohlke's
tags tests (in Tests/test_file_png.py) to expect Unicode strings from
the code.
* True div vs. floor div: Many division operations used the "/" operator
to do floor division, which is now the "//" operator in Python 3. These
were fixed.
As of this commit, on the first pass, I have one failing test (improper
handling of a slice object in a C module, test_imagepath.py) in Python 3,
and three that that I haven't tried running yet (test_imagegl,
test_imagegrab, and test_imageqt). I also haven't tested anything on
Windows. All but the three skipped tests run flawlessly against Pythons
2.6 and 2.7.
2012-10-21 01:01:53 +04:00
|
|
|
return prefix[0:1] == b"\377"
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2014-05-05 23:41:09 +04:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
##
|
|
|
|
# Image plugin for JPEG and JFIF images.
|
|
|
|
|
|
|
|
class JpegImageFile(ImageFile.ImageFile):
|
|
|
|
|
|
|
|
format = "JPEG"
|
|
|
|
format_description = "JPEG (ISO 10918)"
|
|
|
|
|
|
|
|
def _open(self):
|
|
|
|
|
|
|
|
s = self.fp.read(1)
|
|
|
|
|
2015-07-06 19:05:08 +03:00
|
|
|
if i8(s) != 255:
|
2010-07-31 06:52:47 +04:00
|
|
|
raise SyntaxError("not a JPEG file")
|
|
|
|
|
|
|
|
# Create attributes
|
|
|
|
self.bits = self.layers = 0
|
|
|
|
|
|
|
|
# JPEG specifics (internal)
|
|
|
|
self.layer = []
|
|
|
|
self.huffman_dc = {}
|
|
|
|
self.huffman_ac = {}
|
|
|
|
self.quantization = {}
|
2014-05-05 23:41:09 +04:00
|
|
|
self.app = {} # compatibility
|
2010-07-31 06:52:47 +04:00
|
|
|
self.applist = []
|
|
|
|
self.icclist = []
|
|
|
|
|
2012-10-17 07:39:56 +04:00
|
|
|
while True:
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2014-05-05 23:09:57 +04:00
|
|
|
i = i8(s)
|
|
|
|
if i == 0xFF:
|
|
|
|
s = s + self.fp.read(1)
|
|
|
|
i = i16(s)
|
|
|
|
else:
|
|
|
|
# Skip non-0xFF junk
|
2015-07-06 19:05:08 +03:00
|
|
|
s = self.fp.read(1)
|
2014-05-05 23:09:57 +04:00
|
|
|
continue
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2012-10-16 01:18:27 +04:00
|
|
|
if i in MARKER:
|
2010-07-31 06:52:47 +04:00
|
|
|
name, description, handler = MARKER[i]
|
|
|
|
# print hex(i), name, description
|
|
|
|
if handler is not None:
|
|
|
|
handler(self, i)
|
2014-05-05 23:09:57 +04:00
|
|
|
if i == 0xFFDA: # start of scan
|
2010-07-31 06:52:47 +04:00
|
|
|
rawmode = self.mode
|
|
|
|
if self.mode == "CMYK":
|
2014-05-05 23:09:57 +04:00
|
|
|
rawmode = "CMYK;I" # assume adobe conventions
|
2014-08-28 15:44:19 +04:00
|
|
|
self.tile = [("jpeg", (0, 0) + self.size, 0,
|
|
|
|
(rawmode, ""))]
|
2010-07-31 06:52:47 +04:00
|
|
|
# self.__offset = self.fp.tell()
|
|
|
|
break
|
|
|
|
s = self.fp.read(1)
|
2014-05-05 23:09:57 +04:00
|
|
|
elif i == 0 or i == 0xFFFF:
|
2010-07-31 06:52:47 +04:00
|
|
|
# padded marker or junk; move on
|
2014-05-21 15:35:29 +04:00
|
|
|
s = b"\xff"
|
2010-07-31 06:52:47 +04:00
|
|
|
else:
|
|
|
|
raise SyntaxError("no marker found")
|
|
|
|
|
|
|
|
def draft(self, mode, size):
|
|
|
|
|
|
|
|
if len(self.tile) != 1:
|
|
|
|
return
|
|
|
|
|
|
|
|
d, e, o, a = self.tile[0]
|
|
|
|
scale = 0
|
|
|
|
|
|
|
|
if a[0] == "RGB" and mode in ["L", "YCbCr"]:
|
|
|
|
self.mode = mode
|
|
|
|
a = mode, ""
|
|
|
|
|
|
|
|
if size:
|
py3k: The big push
There are two main issues fixed with this commit:
* bytes vs. str: All file, image, and palette data are now handled as
bytes. A new _binary module consolidates the hacks needed to do this
across Python versions. tostring/fromstring methods have been renamed to
tobytes/frombytes, but the Python 2.6/2.7 versions alias them to the old
names for compatibility. Users should move to tobytes/frombytes.
One other potentially-breaking change is that text data in image files
(such as tags, comments) are now explicitly handled with a specific
character encoding in mind. This works well with the Unicode str in
Python 3, but may trip up old code expecting a straight byte-for-byte
translation to a Python string. This also required a change to Gohlke's
tags tests (in Tests/test_file_png.py) to expect Unicode strings from
the code.
* True div vs. floor div: Many division operations used the "/" operator
to do floor division, which is now the "//" operator in Python 3. These
were fixed.
As of this commit, on the first pass, I have one failing test (improper
handling of a slice object in a C module, test_imagepath.py) in Python 3,
and three that that I haven't tried running yet (test_imagegl,
test_imagegrab, and test_imageqt). I also haven't tested anything on
Windows. All but the three skipped tests run flawlessly against Pythons
2.6 and 2.7.
2012-10-21 01:01:53 +04:00
|
|
|
scale = max(self.size[0] // size[0], self.size[1] // size[1])
|
2010-07-31 06:52:47 +04:00
|
|
|
for s in [8, 4, 2, 1]:
|
|
|
|
if scale >= s:
|
|
|
|
break
|
py3k: The big push
There are two main issues fixed with this commit:
* bytes vs. str: All file, image, and palette data are now handled as
bytes. A new _binary module consolidates the hacks needed to do this
across Python versions. tostring/fromstring methods have been renamed to
tobytes/frombytes, but the Python 2.6/2.7 versions alias them to the old
names for compatibility. Users should move to tobytes/frombytes.
One other potentially-breaking change is that text data in image files
(such as tags, comments) are now explicitly handled with a specific
character encoding in mind. This works well with the Unicode str in
Python 3, but may trip up old code expecting a straight byte-for-byte
translation to a Python string. This also required a change to Gohlke's
tags tests (in Tests/test_file_png.py) to expect Unicode strings from
the code.
* True div vs. floor div: Many division operations used the "/" operator
to do floor division, which is now the "//" operator in Python 3. These
were fixed.
As of this commit, on the first pass, I have one failing test (improper
handling of a slice object in a C module, test_imagepath.py) in Python 3,
and three that that I haven't tried running yet (test_imagegl,
test_imagegrab, and test_imageqt). I also haven't tested anything on
Windows. All but the three skipped tests run flawlessly against Pythons
2.6 and 2.7.
2012-10-21 01:01:53 +04:00
|
|
|
e = e[0], e[1], (e[2]-e[0]+s-1)//s+e[0], (e[3]-e[1]+s-1)//s+e[1]
|
|
|
|
self.size = ((self.size[0]+s-1)//s, (self.size[1]+s-1)//s)
|
2010-07-31 06:52:47 +04:00
|
|
|
scale = s
|
|
|
|
|
|
|
|
self.tile = [(d, e, o, a)]
|
2014-11-28 04:21:46 +03:00
|
|
|
self.decoderconfig = (scale, 0)
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
return self
|
|
|
|
|
|
|
|
def load_djpeg(self):
|
|
|
|
|
|
|
|
# ALTERNATIVE: handle JPEGs via the IJG command line utilities
|
|
|
|
|
2014-06-27 08:28:44 +04:00
|
|
|
import subprocess
|
2014-05-05 23:41:09 +04:00
|
|
|
import tempfile
|
|
|
|
import os
|
2014-03-15 02:56:41 +04:00
|
|
|
f, path = tempfile.mkstemp()
|
|
|
|
os.close(f)
|
|
|
|
if os.path.exists(self.filename):
|
2014-07-01 03:52:07 +04:00
|
|
|
subprocess.check_call(["djpeg", "-outfile", path, self.filename])
|
2014-03-15 02:56:41 +04:00
|
|
|
else:
|
|
|
|
raise ValueError("Invalid Filename")
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
try:
|
2014-03-15 02:56:41 +04:00
|
|
|
self.im = Image.core.open_ppm(path)
|
2010-07-31 06:52:47 +04:00
|
|
|
finally:
|
2014-05-05 23:41:09 +04:00
|
|
|
try:
|
|
|
|
os.unlink(path)
|
2015-12-02 08:23:49 +03:00
|
|
|
except OSError:
|
2014-05-05 23:41:09 +04:00
|
|
|
pass
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
self.mode = self.im.mode
|
|
|
|
self.size = self.im.size
|
|
|
|
|
|
|
|
self.tile = []
|
|
|
|
|
|
|
|
def _getexif(self):
|
2013-09-29 20:17:37 +04:00
|
|
|
return _getexif(self)
|
|
|
|
|
2014-07-16 19:36:56 +04:00
|
|
|
def _getmp(self):
|
|
|
|
return _getmp(self)
|
|
|
|
|
|
|
|
|
2013-09-29 20:17:37 +04:00
|
|
|
def _getexif(self):
|
|
|
|
# Extract EXIF information. This method is highly experimental,
|
|
|
|
# and is likely to be replaced with something better in a future
|
|
|
|
# version.
|
2014-05-05 23:41:09 +04:00
|
|
|
|
2013-09-29 20:17:37 +04:00
|
|
|
# The EXIF record consists of a TIFF file embedded in a JPEG
|
|
|
|
# application marker (!).
|
|
|
|
try:
|
|
|
|
data = self.info["exif"]
|
|
|
|
except KeyError:
|
|
|
|
return None
|
|
|
|
file = io.BytesIO(data[6:])
|
|
|
|
head = file.read(8)
|
|
|
|
# process dictionary
|
2015-09-11 20:09:14 +03:00
|
|
|
info = TiffImagePlugin.ImageFileDirectory_v2(head)
|
2013-09-29 20:17:37 +04:00
|
|
|
info.load(file)
|
2014-12-30 13:57:45 +03:00
|
|
|
exif = dict(info)
|
2013-09-29 20:17:37 +04:00
|
|
|
# get exif extension
|
|
|
|
try:
|
2015-09-10 14:36:07 +03:00
|
|
|
# exif field 0x8769 is an offset pointer to the location
|
|
|
|
# of the nested embedded exif ifd.
|
|
|
|
# It should be a long, but may be corrupted.
|
2013-09-29 20:17:37 +04:00
|
|
|
file.seek(exif[0x8769])
|
2015-07-29 13:01:23 +03:00
|
|
|
except (KeyError, TypeError):
|
2013-09-29 20:17:37 +04:00
|
|
|
pass
|
|
|
|
else:
|
2015-09-11 20:09:14 +03:00
|
|
|
info = TiffImagePlugin.ImageFileDirectory_v2(head)
|
2010-07-31 06:52:47 +04:00
|
|
|
info.load(file)
|
2014-12-30 13:57:45 +03:00
|
|
|
exif.update(info)
|
2013-09-29 20:17:37 +04:00
|
|
|
# get gpsinfo extension
|
|
|
|
try:
|
2015-09-10 14:36:07 +03:00
|
|
|
# exif field 0x8825 is an offset pointer to the location
|
2015-09-15 14:37:51 +03:00
|
|
|
# of the nested embedded gps exif ifd.
|
2015-09-10 14:36:07 +03:00
|
|
|
# It should be a long, but may be corrupted.
|
2015-09-15 04:06:51 +03:00
|
|
|
file.seek(exif[0x8825])
|
2015-09-10 14:19:25 +03:00
|
|
|
except (KeyError, TypeError):
|
2013-09-29 20:17:37 +04:00
|
|
|
pass
|
|
|
|
else:
|
2015-09-11 20:09:14 +03:00
|
|
|
info = TiffImagePlugin.ImageFileDirectory_v2(head)
|
2013-09-29 20:17:37 +04:00
|
|
|
info.load(file)
|
2014-12-30 13:57:45 +03:00
|
|
|
exif[0x8825] = dict(info)
|
2013-09-29 20:17:37 +04:00
|
|
|
return exif
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2014-07-16 19:36:56 +04:00
|
|
|
|
|
|
|
def _getmp(self):
|
|
|
|
# Extract MP information. This method was inspired by the "highly
|
|
|
|
# experimental" _getexif version that's been in use for years now,
|
|
|
|
# itself based on the ImageFileDirectory class in the TIFF plug-in.
|
|
|
|
|
|
|
|
# The MP record essentially consists of a TIFF file embedded in a JPEG
|
|
|
|
# application marker.
|
|
|
|
try:
|
|
|
|
data = self.info["mp"]
|
|
|
|
except KeyError:
|
|
|
|
return None
|
2015-04-24 11:24:52 +03:00
|
|
|
file_contents = io.BytesIO(data)
|
|
|
|
head = file_contents.read(8)
|
2014-07-22 21:31:51 +04:00
|
|
|
endianness = '>' if head[:4] == b'\x4d\x4d\x00\x2a' else '<'
|
2014-07-16 19:36:56 +04:00
|
|
|
# process dictionary
|
2015-09-11 20:09:14 +03:00
|
|
|
info = TiffImagePlugin.ImageFileDirectory_v2(head)
|
2015-04-24 11:24:52 +03:00
|
|
|
info.load(file_contents)
|
2014-12-30 13:57:45 +03:00
|
|
|
mp = dict(info)
|
2014-07-22 21:31:51 +04:00
|
|
|
# it's an error not to have a number of images
|
|
|
|
try:
|
|
|
|
quant = mp[0xB001]
|
|
|
|
except KeyError:
|
|
|
|
raise SyntaxError("malformed MP Index (no number of images)")
|
|
|
|
# get MP entries
|
2015-01-14 10:07:41 +03:00
|
|
|
mpentries = []
|
2014-07-22 21:31:51 +04:00
|
|
|
try:
|
2015-01-14 10:07:41 +03:00
|
|
|
rawmpentries = mp[0xB002]
|
2014-07-22 21:31:51 +04:00
|
|
|
for entrynum in range(0, quant):
|
2015-01-14 10:07:41 +03:00
|
|
|
unpackedentry = unpack_from(
|
|
|
|
'{0}LLLHH'.format(endianness), rawmpentries, entrynum * 16)
|
2014-08-28 15:44:19 +04:00
|
|
|
labels = ('Attribute', 'Size', 'DataOffset', 'EntryNo1',
|
|
|
|
'EntryNo2')
|
2014-07-22 21:31:51 +04:00
|
|
|
mpentry = dict(zip(labels, unpackedentry))
|
2014-07-24 23:00:19 +04:00
|
|
|
mpentryattr = {
|
2014-08-28 15:44:19 +04:00
|
|
|
'DependentParentImageFlag': bool(mpentry['Attribute'] &
|
|
|
|
(1 << 31)),
|
|
|
|
'DependentChildImageFlag': bool(mpentry['Attribute'] &
|
|
|
|
(1 << 30)),
|
|
|
|
'RepresentativeImageFlag': bool(mpentry['Attribute'] &
|
|
|
|
(1 << 29)),
|
|
|
|
'Reserved': (mpentry['Attribute'] & (3 << 27)) >> 27,
|
|
|
|
'ImageDataFormat': (mpentry['Attribute'] & (7 << 24)) >> 24,
|
2014-07-24 23:00:19 +04:00
|
|
|
'MPType': mpentry['Attribute'] & 0x00FFFFFF
|
|
|
|
}
|
|
|
|
if mpentryattr['ImageDataFormat'] == 0:
|
|
|
|
mpentryattr['ImageDataFormat'] = 'JPEG'
|
|
|
|
else:
|
|
|
|
raise SyntaxError("unsupported picture format in MPO")
|
|
|
|
mptypemap = {
|
|
|
|
0x000000: 'Undefined',
|
|
|
|
0x010001: 'Large Thumbnail (VGA Equivalent)',
|
|
|
|
0x010002: 'Large Thumbnail (Full HD Equivalent)',
|
|
|
|
0x020001: 'Multi-Frame Image (Panorama)',
|
|
|
|
0x020002: 'Multi-Frame Image: (Disparity)',
|
|
|
|
0x020003: 'Multi-Frame Image: (Multi-Angle)',
|
|
|
|
0x030000: 'Baseline MP Primary Image'
|
|
|
|
}
|
|
|
|
mpentryattr['MPType'] = mptypemap.get(mpentryattr['MPType'],
|
2014-08-28 15:44:19 +04:00
|
|
|
'Unknown')
|
2014-07-24 23:00:19 +04:00
|
|
|
mpentry['Attribute'] = mpentryattr
|
2014-07-22 21:31:51 +04:00
|
|
|
mpentries.append(mpentry)
|
|
|
|
mp[0xB002] = mpentries
|
|
|
|
except KeyError:
|
|
|
|
raise SyntaxError("malformed MP Index (bad MP Entry)")
|
2014-07-24 23:00:19 +04:00
|
|
|
# Next we should try and parse the individual image unique ID list;
|
|
|
|
# we don't because I've never seen this actually used in a real MPO
|
|
|
|
# file and so can't test it.
|
2014-07-16 19:36:56 +04:00
|
|
|
return mp
|
|
|
|
|
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
# --------------------------------------------------------------------
|
|
|
|
# stuff to save JPEG files
|
|
|
|
|
|
|
|
RAWMODE = {
|
|
|
|
"1": "L",
|
|
|
|
"L": "L",
|
|
|
|
"RGB": "RGB",
|
|
|
|
"RGBA": "RGB",
|
|
|
|
"RGBX": "RGB",
|
2014-05-05 23:41:09 +04:00
|
|
|
"CMYK": "CMYK;I", # assume adobe conventions
|
2010-07-31 06:52:47 +04:00
|
|
|
"YCbCr": "YCbCr",
|
|
|
|
}
|
|
|
|
|
2015-08-25 15:27:18 +03:00
|
|
|
zigzag_index = (0, 1, 5, 6, 14, 15, 27, 28,
|
|
|
|
2, 4, 7, 13, 16, 26, 29, 42,
|
|
|
|
3, 8, 12, 17, 25, 30, 41, 43,
|
|
|
|
9, 11, 18, 24, 31, 40, 44, 53,
|
|
|
|
10, 19, 23, 32, 39, 45, 52, 54,
|
|
|
|
20, 22, 33, 38, 46, 51, 55, 60,
|
|
|
|
21, 34, 37, 47, 50, 56, 59, 61,
|
|
|
|
35, 36, 48, 49, 57, 58, 62, 63)
|
2013-03-07 05:23:02 +04:00
|
|
|
|
2014-08-28 15:44:19 +04:00
|
|
|
samplings = {(1, 1, 1, 1, 1, 1): 0,
|
2013-03-07 05:23:02 +04:00
|
|
|
(2, 1, 1, 1, 1, 1): 1,
|
|
|
|
(2, 2, 1, 1, 1, 1): 2,
|
2014-08-28 15:44:19 +04:00
|
|
|
}
|
2013-03-07 05:23:02 +04:00
|
|
|
|
2014-05-05 23:41:09 +04:00
|
|
|
|
2013-03-07 05:23:02 +04:00
|
|
|
def convert_dict_qtables(qtables):
|
2014-03-28 03:40:44 +04:00
|
|
|
qtables = [qtables[key] for key in range(len(qtables)) if key in qtables]
|
2013-03-07 05:23:02 +04:00
|
|
|
for idx, table in enumerate(qtables):
|
|
|
|
qtables[idx] = [table[i] for i in zigzag_index]
|
|
|
|
return qtables
|
|
|
|
|
2014-05-05 23:41:09 +04:00
|
|
|
|
2013-03-07 05:23:02 +04:00
|
|
|
def get_sampling(im):
|
2014-09-02 22:49:24 +04:00
|
|
|
# There's no subsampling when image have only 1 layer
|
|
|
|
# (grayscale images) or when they are CMYK (4 layers),
|
|
|
|
# so set subsampling to default value.
|
|
|
|
#
|
|
|
|
# NOTE: currently Pillow can't encode JPEG to YCCK format.
|
|
|
|
# If YCCK support is added in the future, subsampling code will have
|
|
|
|
# to be updated (here and in JpegEncode.c) to deal with 4 layers.
|
|
|
|
if not hasattr(im, 'layers') or im.layers in (1, 4):
|
|
|
|
return -1
|
2013-03-07 05:23:02 +04:00
|
|
|
sampling = im.layer[0][1:3] + im.layer[1][1:3] + im.layer[2][1:3]
|
|
|
|
return samplings.get(sampling, -1)
|
|
|
|
|
2014-05-05 23:41:09 +04:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
def _save(im, fp, filename):
|
|
|
|
|
|
|
|
try:
|
|
|
|
rawmode = RAWMODE[im.mode]
|
|
|
|
except KeyError:
|
|
|
|
raise IOError("cannot write mode %s as JPEG" % im.mode)
|
|
|
|
|
|
|
|
info = im.encoderinfo
|
|
|
|
|
|
|
|
dpi = info.get("dpi", (0, 0))
|
|
|
|
|
2013-03-07 05:23:02 +04:00
|
|
|
quality = info.get("quality", 0)
|
2010-07-31 06:52:47 +04:00
|
|
|
subsampling = info.get("subsampling", -1)
|
2013-03-07 05:23:02 +04:00
|
|
|
qtables = info.get("qtables")
|
|
|
|
|
|
|
|
if quality == "keep":
|
|
|
|
quality = 0
|
|
|
|
subsampling = "keep"
|
|
|
|
qtables = "keep"
|
|
|
|
elif quality in presets:
|
|
|
|
preset = presets[quality]
|
|
|
|
quality = 0
|
|
|
|
subsampling = preset.get('subsampling', -1)
|
|
|
|
qtables = preset.get('quantization')
|
|
|
|
elif not isinstance(quality, int):
|
|
|
|
raise ValueError("Invalid quality setting")
|
|
|
|
else:
|
|
|
|
if subsampling in presets:
|
|
|
|
subsampling = presets[subsampling].get('subsampling', -1)
|
2014-05-29 02:21:58 +04:00
|
|
|
if isStringType(qtables) and qtables in presets:
|
2013-03-07 05:23:02 +04:00
|
|
|
qtables = presets[qtables].get('quantization')
|
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
if subsampling == "4:4:4":
|
|
|
|
subsampling = 0
|
|
|
|
elif subsampling == "4:2:2":
|
|
|
|
subsampling = 1
|
|
|
|
elif subsampling == "4:1:1":
|
|
|
|
subsampling = 2
|
2013-03-07 05:23:02 +04:00
|
|
|
elif subsampling == "keep":
|
|
|
|
if im.format != "JPEG":
|
2014-08-28 15:44:19 +04:00
|
|
|
raise ValueError(
|
|
|
|
"Cannot use 'keep' when original image is not a JPEG")
|
2013-03-26 16:36:13 +04:00
|
|
|
subsampling = get_sampling(im)
|
2013-03-07 05:23:02 +04:00
|
|
|
|
|
|
|
def validate_qtables(qtables):
|
|
|
|
if qtables is None:
|
|
|
|
return qtables
|
2013-06-30 15:04:42 +04:00
|
|
|
if isStringType(qtables):
|
2013-03-07 05:23:02 +04:00
|
|
|
try:
|
|
|
|
lines = [int(num) for line in qtables.splitlines()
|
|
|
|
for num in line.split('#', 1)[0].split()]
|
|
|
|
except ValueError:
|
|
|
|
raise ValueError("Invalid quantization table")
|
|
|
|
else:
|
2014-03-28 03:40:44 +04:00
|
|
|
qtables = [lines[s:s+64] for s in range(0, len(lines), 64)]
|
2013-03-07 05:23:02 +04:00
|
|
|
if isinstance(qtables, (tuple, list, dict)):
|
|
|
|
if isinstance(qtables, dict):
|
|
|
|
qtables = convert_dict_qtables(qtables)
|
|
|
|
elif isinstance(qtables, tuple):
|
|
|
|
qtables = list(qtables)
|
|
|
|
if not (0 < len(qtables) < 5):
|
|
|
|
raise ValueError("None or too many quantization tables")
|
|
|
|
for idx, table in enumerate(qtables):
|
|
|
|
try:
|
|
|
|
if len(table) != 64:
|
|
|
|
raise
|
|
|
|
table = array.array('b', table)
|
|
|
|
except TypeError:
|
|
|
|
raise ValueError("Invalid quantization table")
|
|
|
|
else:
|
|
|
|
qtables[idx] = list(table)
|
|
|
|
return qtables
|
2013-03-26 16:36:13 +04:00
|
|
|
|
2013-03-07 05:23:02 +04:00
|
|
|
if qtables == "keep":
|
|
|
|
if im.format != "JPEG":
|
2014-08-28 15:44:19 +04:00
|
|
|
raise ValueError(
|
|
|
|
"Cannot use 'keep' when original image is not a JPEG")
|
2013-03-07 05:23:02 +04:00
|
|
|
qtables = getattr(im, "quantization", None)
|
|
|
|
qtables = validate_qtables(qtables)
|
2010-07-31 06:52:47 +04:00
|
|
|
|
py3k: The big push
There are two main issues fixed with this commit:
* bytes vs. str: All file, image, and palette data are now handled as
bytes. A new _binary module consolidates the hacks needed to do this
across Python versions. tostring/fromstring methods have been renamed to
tobytes/frombytes, but the Python 2.6/2.7 versions alias them to the old
names for compatibility. Users should move to tobytes/frombytes.
One other potentially-breaking change is that text data in image files
(such as tags, comments) are now explicitly handled with a specific
character encoding in mind. This works well with the Unicode str in
Python 3, but may trip up old code expecting a straight byte-for-byte
translation to a Python string. This also required a change to Gohlke's
tags tests (in Tests/test_file_png.py) to expect Unicode strings from
the code.
* True div vs. floor div: Many division operations used the "/" operator
to do floor division, which is now the "//" operator in Python 3. These
were fixed.
As of this commit, on the first pass, I have one failing test (improper
handling of a slice object in a C module, test_imagepath.py) in Python 3,
and three that that I haven't tried running yet (test_imagegl,
test_imagegrab, and test_imageqt). I also haven't tested anything on
Windows. All but the three skipped tests run flawlessly against Pythons
2.6 and 2.7.
2012-10-21 01:01:53 +04:00
|
|
|
extra = b""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
icc_profile = info.get("icc_profile")
|
|
|
|
if icc_profile:
|
|
|
|
ICC_OVERHEAD_LEN = 14
|
|
|
|
MAX_BYTES_IN_MARKER = 65533
|
|
|
|
MAX_DATA_BYTES_IN_MARKER = MAX_BYTES_IN_MARKER - ICC_OVERHEAD_LEN
|
|
|
|
markers = []
|
|
|
|
while icc_profile:
|
|
|
|
markers.append(icc_profile[:MAX_DATA_BYTES_IN_MARKER])
|
|
|
|
icc_profile = icc_profile[MAX_DATA_BYTES_IN_MARKER:]
|
|
|
|
i = 1
|
|
|
|
for marker in markers:
|
|
|
|
size = struct.pack(">H", 2 + ICC_OVERHEAD_LEN + len(marker))
|
2014-08-28 15:44:19 +04:00
|
|
|
extra += (b"\xFF\xE2" + size + b"ICC_PROFILE\0" + o8(i) +
|
|
|
|
o8(len(markers)) + marker)
|
2014-05-10 08:36:15 +04:00
|
|
|
i += 1
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
# get keyword arguments
|
|
|
|
im.encoderconfig = (
|
2013-03-07 05:23:02 +04:00
|
|
|
quality,
|
2010-07-31 06:52:47 +04:00
|
|
|
# "progressive" is the official name, but older documentation
|
|
|
|
# says "progression"
|
|
|
|
# FIXME: issue a warning if the wrong form is used (post-1.1.7)
|
2012-10-16 01:18:27 +04:00
|
|
|
"progressive" in info or "progression" in info,
|
2010-07-31 06:52:47 +04:00
|
|
|
info.get("smooth", 0),
|
2012-10-16 01:18:27 +04:00
|
|
|
"optimize" in info,
|
2010-07-31 06:52:47 +04:00
|
|
|
info.get("streamtype", 0),
|
|
|
|
dpi[0], dpi[1],
|
|
|
|
subsampling,
|
2013-03-07 05:23:02 +04:00
|
|
|
qtables,
|
2010-07-31 06:52:47 +04:00
|
|
|
extra,
|
2013-01-11 17:41:38 +04:00
|
|
|
info.get("exif", b"")
|
2010-07-31 06:52:47 +04:00
|
|
|
)
|
|
|
|
|
2014-05-05 23:41:09 +04:00
|
|
|
# if we optimize, libjpeg needs a buffer big enough to hold the whole image
|
|
|
|
# in a shot. Guessing on the size, at im.size bytes. (raw pizel size is
|
|
|
|
# channels*size, this is a value that's been used in a django patch.
|
2015-09-28 14:53:25 +03:00
|
|
|
# https://github.com/matthewwithanm/django-imagekit/issues/50
|
2014-05-05 23:41:09 +04:00
|
|
|
bufsize = 0
|
2013-08-02 16:36:46 +04:00
|
|
|
if "optimize" in info or "progressive" in info or "progression" in info:
|
2015-04-24 02:26:52 +03:00
|
|
|
# keep sets quality to 0, but the actual value may be high.
|
2015-01-18 21:56:29 +03:00
|
|
|
if quality >= 95 or quality == 0:
|
2014-01-27 23:27:03 +04:00
|
|
|
bufsize = 2 * im.size[0] * im.size[1]
|
|
|
|
else:
|
|
|
|
bufsize = im.size[0] * im.size[1]
|
2013-07-01 02:42:19 +04:00
|
|
|
|
2013-05-15 09:29:31 +04:00
|
|
|
# The exif info needs to be written as one block, + APP1, + one spare byte.
|
2013-08-02 16:36:46 +04:00
|
|
|
# Ensure that our buffer is big enough
|
2014-05-05 23:41:09 +04:00
|
|
|
bufsize = max(ImageFile.MAXBLOCK, bufsize, len(info.get("exif", b"")) + 5)
|
|
|
|
|
|
|
|
ImageFile._save(im, fp, [("jpeg", (0, 0)+im.size, 0, rawmode)], bufsize)
|
2013-03-23 09:27:12 +04:00
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
def _save_cjpeg(im, fp, filename):
|
|
|
|
# ALTERNATIVE: handle JPEGs via the IJG command line utilities.
|
|
|
|
import os
|
2014-06-27 08:28:44 +04:00
|
|
|
import subprocess
|
|
|
|
tempfile = im._dump()
|
2014-07-01 03:52:07 +04:00
|
|
|
subprocess.check_call(["cjpeg", "-outfile", filename, tempfile])
|
2014-05-05 23:41:09 +04:00
|
|
|
try:
|
2015-05-08 07:28:49 +03:00
|
|
|
os.unlink(tempfile)
|
2015-12-02 08:23:49 +03:00
|
|
|
except OSError:
|
2014-05-05 23:41:09 +04:00
|
|
|
pass
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2014-07-24 19:16:12 +04:00
|
|
|
|
|
|
|
##
|
|
|
|
# Factory for making JPEG and MPO instances
|
|
|
|
def jpeg_factory(fp=None, filename=None):
|
|
|
|
im = JpegImageFile(fp, filename)
|
|
|
|
try:
|
2015-07-19 15:56:04 +03:00
|
|
|
mpheader = im._getmp()
|
2014-07-24 19:16:12 +04:00
|
|
|
if mpheader[45057] > 1:
|
|
|
|
# It's actually an MPO
|
2014-07-25 19:50:21 +04:00
|
|
|
from .MpoImagePlugin import MpoImageFile
|
2014-07-24 19:16:12 +04:00
|
|
|
im = MpoImageFile(fp, filename)
|
|
|
|
except (TypeError, IndexError):
|
|
|
|
# It is really a JPEG
|
|
|
|
pass
|
2015-07-19 15:56:04 +03:00
|
|
|
except SyntaxError:
|
|
|
|
warnings.warn("Image appears to be a malformed MPO file, it will be "
|
|
|
|
"interpreted as a base JPEG file")
|
|
|
|
pass
|
2014-07-24 19:16:12 +04:00
|
|
|
return im
|
|
|
|
|
|
|
|
|
2010-07-31 06:52:47 +04:00
|
|
|
# -------------------------------------------------------------------q-
|
|
|
|
# Registry stuff
|
|
|
|
|
2015-07-04 16:29:58 +03:00
|
|
|
Image.register_open(JpegImageFile.format, jpeg_factory, _accept)
|
|
|
|
Image.register_save(JpegImageFile.format, _save)
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2015-07-04 16:29:58 +03:00
|
|
|
Image.register_extension(JpegImageFile.format, ".jfif")
|
|
|
|
Image.register_extension(JpegImageFile.format, ".jpe")
|
|
|
|
Image.register_extension(JpegImageFile.format, ".jpg")
|
|
|
|
Image.register_extension(JpegImageFile.format, ".jpeg")
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2015-07-04 16:29:58 +03:00
|
|
|
Image.register_mime(JpegImageFile.format, "image/jpeg")
|