{
    "file_diffs": [
        {
            "old_file_content": "#\n# The Python Imaging Library.\n# $Id$\n#\n# TIFF file handling\n#\n# TIFF is a flexible, if somewhat aged, image file format originally\n# defined by Aldus.  Although TIFF supports a wide variety of pixel\n# layouts and compression methods, the name doesn't really stand for\n# \"thousands of incompatible file formats,\" it just feels that way.\n#\n# To read TIFF data from a stream, the stream must be seekable.  For\n# progressive decoding, make sure to use TIFF files where the tag\n# directory is placed first in the file.\n#\n# History:\n# 1995-09-01 fl   Created\n# 1996-05-04 fl   Handle JPEGTABLES tag\n# 1996-05-18 fl   Fixed COLORMAP support\n# 1997-01-05 fl   Fixed PREDICTOR support\n# 1997-08-27 fl   Added support for rational tags (from Perry Stoll)\n# 1998-01-10 fl   Fixed seek/tell (from Jan Blom)\n# 1998-07-15 fl   Use private names for internal variables\n# 1999-06-13 fl   Rewritten for PIL 1.0 (1.0)\n# 2000-10-11 fl   Additional fixes for Python 2.0 (1.1)\n# 2001-04-17 fl   Fixed rewind support (seek to frame 0) (1.2)\n# 2001-05-12 fl   Added write support for more tags (from Greg Couch) (1.3)\n# 2001-12-18 fl   Added workaround for broken Matrox library\n# 2002-01-18 fl   Don't mess up if photometric tag is missing (D. Alan Stewart)\n# 2003-05-19 fl   Check FILLORDER tag\n# 2003-09-26 fl   Added RGBa support\n# 2004-02-24 fl   Added DPI support; fixed rational write support\n# 2005-02-07 fl   Added workaround for broken Corel Draw 10 files\n# 2006-01-09 fl   Added support for float/double tags (from Russell Nelson)\n#\n# Copyright (c) 1997-2006 by Secret Labs AB.  All rights reserved.\n# Copyright (c) 1995-1997 by Fredrik Lundh\n#\n# See the README file for information on usage and redistribution.\n#\n\nfrom __future__ import division, print_function\n\nfrom . import Image, ImageFile, ImagePalette, TiffTags\nfrom ._binary import i8, o8\n\nimport collections\nfrom fractions import Fraction\nfrom numbers import Number, Rational\n\nimport io\nimport itertools\nimport os\nimport struct\nimport sys\nimport warnings\n\nfrom .TiffTags import TYPES\n\n\n__version__ = \"1.3.5\"\nDEBUG = False  # Needs to be merged with the new logging approach.\n\n# Set these to true to force use of libtiff for reading or writing.\nREAD_LIBTIFF = False\nWRITE_LIBTIFF = False\nIFD_LEGACY_API = True\n\nII = b\"II\"  # little-endian (Intel style)\nMM = b\"MM\"  # big-endian (Motorola style)\n\n#\n# --------------------------------------------------------------------\n# Read TIFF files\n\n# a few tag names, just to make the code below a bit more readable\nIMAGEWIDTH = 256\nIMAGELENGTH = 257\nBITSPERSAMPLE = 258\nCOMPRESSION = 259\nPHOTOMETRIC_INTERPRETATION = 262\nFILLORDER = 266\nIMAGEDESCRIPTION = 270\nSTRIPOFFSETS = 273\nSAMPLESPERPIXEL = 277\nROWSPERSTRIP = 278\nSTRIPBYTECOUNTS = 279\nX_RESOLUTION = 282\nY_RESOLUTION = 283\nPLANAR_CONFIGURATION = 284\nRESOLUTION_UNIT = 296\nSOFTWARE = 305\nDATE_TIME = 306\nARTIST = 315\nPREDICTOR = 317\nCOLORMAP = 320\nTILEOFFSETS = 324\nEXTRASAMPLES = 338\nSAMPLEFORMAT = 339\nJPEGTABLES = 347\nCOPYRIGHT = 33432\nIPTC_NAA_CHUNK = 33723  # newsphoto properties\nPHOTOSHOP_CHUNK = 34377  # photoshop properties\nICCPROFILE = 34675\nEXIFIFD = 34665\nXMP = 700\n\n# https://github.com/imagej/ImageJA/blob/master/src/main/java/ij/io/TiffDecoder.java\nIMAGEJ_META_DATA_BYTE_COUNTS = 50838\nIMAGEJ_META_DATA = 50839\n\nCOMPRESSION_INFO = {\n    # Compression => pil compression name\n    1: \"raw\",\n    2: \"tiff_ccitt\",\n    3: \"group3\",\n    4: \"group4\",\n    5: \"tiff_lzw\",\n    6: \"tiff_jpeg\",  # obsolete\n    7: \"jpeg\",\n    8: \"tiff_adobe_deflate\",\n    32771: \"tiff_raw_16\",  # 16-bit padding\n    32773: \"packbits\",\n    32809: \"tiff_thunderscan\",\n    32946: \"tiff_deflate\",\n    34676: \"tiff_sgilog\",\n    34677: \"tiff_sgilog24\",\n}\n\nCOMPRESSION_INFO_REV = {v: k for k, v in COMPRESSION_INFO.items()}\n\nOPEN_INFO = {\n    # (ByteOrder, PhotoInterpretation, SampleFormat, FillOrder, BitsPerSample,\n    #  ExtraSamples) => mode, rawmode\n    (II, 0, (1,), 1, (1,), ()): (\"1\", \"1;I\"),\n    (MM, 0, (1,), 1, (1,), ()): (\"1\", \"1;I\"),\n    (II, 0, (1,), 2, (1,), ()): (\"1\", \"1;IR\"),\n    (MM, 0, (1,), 2, (1,), ()): (\"1\", \"1;IR\"),\n    (II, 1, (1,), 1, (1,), ()): (\"1\", \"1\"),\n    (MM, 1, (1,), 1, (1,), ()): (\"1\", \"1\"),\n    (II, 1, (1,), 2, (1,), ()): (\"1\", \"1;R\"),\n    (MM, 1, (1,), 2, (1,), ()): (\"1\", \"1;R\"),\n\n    (II, 0, (1,), 1, (2,), ()): (\"L\", \"L;2I\"),\n    (MM, 0, (1,), 1, (2,), ()): (\"L\", \"L;2I\"),\n    (II, 0, (1,), 2, (2,), ()): (\"L\", \"L;2IR\"),\n    (MM, 0, (1,), 2, (2,), ()): (\"L\", \"L;2IR\"),\n    (II, 1, (1,), 1, (2,), ()): (\"L\", \"L;2\"),\n    (MM, 1, (1,), 1, (2,), ()): (\"L\", \"L;2\"),\n    (II, 1, (1,), 2, (2,), ()): (\"L\", \"L;2R\"),\n    (MM, 1, (1,), 2, (2,), ()): (\"L\", \"L;2R\"),\n\n    (II, 0, (1,), 1, (4,), ()): (\"L\", \"L;4I\"),\n    (MM, 0, (1,), 1, (4,), ()): (\"L\", \"L;4I\"),\n    (II, 0, (1,), 2, (4,), ()): (\"L\", \"L;4IR\"),\n    (MM, 0, (1,), 2, (4,), ()): (\"L\", \"L;4IR\"),\n    (II, 1, (1,), 1, (4,), ()): (\"L\", \"L;4\"),\n    (MM, 1, (1,), 1, (4,), ()): (\"L\", \"L;4\"),\n    (II, 1, (1,), 2, (4,), ()): (\"L\", \"L;4R\"),\n    (MM, 1, (1,), 2, (4,), ()): (\"L\", \"L;4R\"),\n\n    (II, 0, (1,), 1, (8,), ()): (\"L\", \"L;I\"),\n    (MM, 0, (1,), 1, (8,), ()): (\"L\", \"L;I\"),\n    (II, 0, (1,), 2, (8,), ()): (\"L\", \"L;IR\"),\n    (MM, 0, (1,), 2, (8,), ()): (\"L\", \"L;IR\"),\n    (II, 1, (1,), 1, (8,), ()): (\"L\", \"L\"),\n    (MM, 1, (1,), 1, (8,), ()): (\"L\", \"L\"),\n    (II, 1, (1,), 2, (8,), ()): (\"L\", \"L;R\"),\n    (MM, 1, (1,), 2, (8,), ()): (\"L\", \"L;R\"),\n\n    (II, 1, (1,), 1, (12,), ()): (\"I;16\", \"I;12\"),\n\n    (II, 1, (1,), 1, (16,), ()): (\"I;16\", \"I;16\"),\n    (MM, 1, (1,), 1, (16,), ()): (\"I;16B\", \"I;16B\"),\n    (II, 1, (2,), 1, (16,), ()): (\"I;16S\", \"I;16S\"),\n    (MM, 1, (2,), 1, (16,), ()): (\"I;16BS\", \"I;16BS\"),\n\n    (II, 0, (3,), 1, (32,), ()): (\"F\", \"F;32F\"),\n    (MM, 0, (3,), 1, (32,), ()): (\"F\", \"F;32BF\"),\n    (II, 1, (1,), 1, (32,), ()): (\"I\", \"I;32N\"),\n    (II, 1, (2,), 1, (32,), ()): (\"I\", \"I;32S\"),\n    (MM, 1, (2,), 1, (32,), ()): (\"I;32BS\", \"I;32BS\"),\n    (II, 1, (3,), 1, (32,), ()): (\"F\", \"F;32F\"),\n    (MM, 1, (3,), 1, (32,), ()): (\"F\", \"F;32BF\"),\n\n    (II, 1, (1,), 1, (8, 8), (2,)): (\"LA\", \"LA\"),\n    (MM, 1, (1,), 1, (8, 8), (2,)): (\"LA\", \"LA\"),\n\n    (II, 2, (1,), 1, (8, 8, 8), ()): (\"RGB\", \"RGB\"),\n    (MM, 2, (1,), 1, (8, 8, 8), ()): (\"RGB\", \"RGB\"),\n    (II, 2, (1,), 2, (8, 8, 8), ()): (\"RGB\", \"RGB;R\"),\n    (MM, 2, (1,), 2, (8, 8, 8), ()): (\"RGB\", \"RGB;R\"),\n    (II, 2, (1,), 1, (8, 8, 8, 8), ()): (\"RGBA\", \"RGBA\"),  # missing ExtraSamples\n    (MM, 2, (1,), 1, (8, 8, 8, 8), ()): (\"RGBA\", \"RGBA\"),  # missing ExtraSamples\n    (II, 2, (1,), 1, (8, 8, 8, 8), (0,)): (\"RGBX\", \"RGBX\"),\n    (MM, 2, (1,), 1, (8, 8, 8, 8), (0,)): (\"RGBX\", \"RGBX\"),\n    (II, 2, (1,), 1, (8, 8, 8, 8), (1,)): (\"RGBA\", \"RGBa\"),\n    (MM, 2, (1,), 1, (8, 8, 8, 8), (1,)): (\"RGBA\", \"RGBa\"),\n    (II, 2, (1,), 1, (8, 8, 8, 8), (2,)): (\"RGBA\", \"RGBA\"),\n    (MM, 2, (1,), 1, (8, 8, 8, 8), (2,)): (\"RGBA\", \"RGBA\"),\n    (II, 2, (1,), 1, (8, 8, 8, 8), (999,)): (\"RGBA\", \"RGBA\"),  # Corel Draw 10\n    (MM, 2, (1,), 1, (8, 8, 8, 8), (999,)): (\"RGBA\", \"RGBA\"),  # Corel Draw 10\n\n    (II, 3, (1,), 1, (1,), ()): (\"P\", \"P;1\"),\n    (MM, 3, (1,), 1, (1,), ()): (\"P\", \"P;1\"),\n    (II, 3, (1,), 2, (1,), ()): (\"P\", \"P;1R\"),\n    (MM, 3, (1,), 2, (1,), ()): (\"P\", \"P;1R\"),\n    (II, 3, (1,), 1, (2,), ()): (\"P\", \"P;2\"),\n    (MM, 3, (1,), 1, (2,), ()): (\"P\", \"P;2\"),\n    (II, 3, (1,), 2, (2,), ()): (\"P\", \"P;2R\"),\n    (MM, 3, (1,), 2, (2,), ()): (\"P\", \"P;2R\"),\n    (II, 3, (1,), 1, (4,), ()): (\"P\", \"P;4\"),\n    (MM, 3, (1,), 1, (4,), ()): (\"P\", \"P;4\"),\n    (II, 3, (1,), 2, (4,), ()): (\"P\", \"P;4R\"),\n    (MM, 3, (1,), 2, (4,), ()): (\"P\", \"P;4R\"),\n    (II, 3, (1,), 1, (8,), ()): (\"P\", \"P\"),\n    (MM, 3, (1,), 1, (8,), ()): (\"P\", \"P\"),\n    (II, 3, (1,), 1, (8, 8), (2,)): (\"PA\", \"PA\"),\n    (MM, 3, (1,), 1, (8, 8), (2,)): (\"PA\", \"PA\"),\n    (II, 3, (1,), 2, (8,), ()): (\"P\", \"P;R\"),\n    (MM, 3, (1,), 2, (8,), ()): (\"P\", \"P;R\"),\n\n    (II, 5, (1,), 1, (8, 8, 8, 8), ()): (\"CMYK\", \"CMYK\"),\n    (MM, 5, (1,), 1, (8, 8, 8, 8), ()): (\"CMYK\", \"CMYK\"),\n\n    (II, 6, (1,), 1, (8, 8, 8), ()): (\"YCbCr\", \"YCbCr\"),\n    (MM, 6, (1,), 1, (8, 8, 8), ()): (\"YCbCr\", \"YCbCr\"),\n\n    (II, 8, (1,), 1, (8, 8, 8), ()): (\"LAB\", \"LAB\"),\n    (MM, 8, (1,), 1, (8, 8, 8), ()): (\"LAB\", \"LAB\"),\n}\n\nPREFIXES = [b\"MM\\000\\052\", b\"II\\052\\000\", b\"II\\xBC\\000\"]\n\n\ndef _accept(prefix):\n    return prefix[:4] in PREFIXES\n\n\ndef _limit_rational(val, max_val):\n    inv = abs(val) > 1\n    n_d = IFDRational(1 / val if inv else val).limit_rational(max_val)\n    return n_d[::-1] if inv else n_d\n\n##\n# Wrapper for TIFF IFDs.\n\n_load_dispatch = {}\n_write_dispatch = {}\n\n\nclass IFDRational(Rational):\n    \"\"\" Implements a rational class where 0/0 is a legal value to match\n    the in the wild use of exif rationals.\n\n    e.g., DigitalZoomRatio - 0.00/0.00  indicates that no digital zoom was used\n    \"\"\"\n\n    \"\"\" If the denominator is 0, store this as a float('nan'), otherwise store\n    as a fractions.Fraction(). Delegate as appropriate\n\n    \"\"\"\n\n    __slots__ = ('_numerator', '_denominator', '_val')\n\n    def __init__(self, value, denominator=1):\n        \"\"\"\n        :param value: either an integer numerator, a\n        float/rational/other number, or an IFDRational\n        :param denominator: Optional integer denominator\n        \"\"\"\n        self._denominator = denominator\n        self._numerator = value\n        self._val = float(1)\n\n        if isinstance(value, Fraction):\n            self._numerator = value.numerator\n            self._denominator = value.denominator\n            self._val = value\n\n        if isinstance(value, IFDRational):\n            self._denominator = value.denominator\n            self._numerator = value.numerator\n            self._val = value._val\n            return\n\n        if denominator == 0:\n            self._val = float('nan')\n            return\n\n        elif denominator == 1:\n            self._val = Fraction(value)\n        else:\n            self._val = Fraction(value, denominator)\n\n    @property\n    def numerator(a):\n        return a._numerator\n\n    @property\n    def denominator(a):\n        return a._denominator\n\n    def limit_rational(self, max_denominator):\n        \"\"\"\n\n        :param max_denominator: Integer, the maximum denominator value\n        :returns: Tuple of (numerator, denominator)\n        \"\"\"\n\n        if self.denominator == 0:\n            return (self.numerator, self.denominator)\n\n        f = self._val.limit_denominator(max_denominator)\n        return (f.numerator, f.denominator)\n\n    def __repr__(self):\n        return str(float(self._val))\n\n    def __hash__(self):\n        return self._val.__hash__()\n\n    def __eq__(self, other):\n        return self._val == other\n\n    def _delegate(op):\n        def delegate(self, *args):\n            return getattr(self._val, op)(*args)\n        return delegate\n\n    \"\"\" a = ['add','radd', 'sub', 'rsub','div', 'rdiv', 'mul', 'rmul',\n             'truediv', 'rtruediv', 'floordiv',\n             'rfloordiv','mod','rmod', 'pow','rpow', 'pos', 'neg',\n             'abs', 'trunc', 'lt', 'gt', 'le', 'ge', 'nonzero',\n             'ceil', 'floor', 'round']\n        print(\"\\n\".join(\"__%s__ = _delegate('__%s__')\" % (s,s) for s in a))\n        \"\"\"\n\n    __add__ = _delegate('__add__')\n    __radd__ = _delegate('__radd__')\n    __sub__ = _delegate('__sub__')\n    __rsub__ = _delegate('__rsub__')\n    __div__ = _delegate('__div__')\n    __rdiv__ = _delegate('__rdiv__')\n    __mul__ = _delegate('__mul__')\n    __rmul__ = _delegate('__rmul__')\n    __truediv__ = _delegate('__truediv__')\n    __rtruediv__ = _delegate('__rtruediv__')\n    __floordiv__ = _delegate('__floordiv__')\n    __rfloordiv__ = _delegate('__rfloordiv__')\n    __mod__ = _delegate('__mod__')\n    __rmod__ = _delegate('__rmod__')\n    __pow__ = _delegate('__pow__')\n    __rpow__ = _delegate('__rpow__')\n    __pos__ = _delegate('__pos__')\n    __neg__ = _delegate('__neg__')\n    __abs__ = _delegate('__abs__')\n    __trunc__ = _delegate('__trunc__')\n    __lt__ = _delegate('__lt__')\n    __gt__ = _delegate('__gt__')\n    __le__ = _delegate('__le__')\n    __ge__ = _delegate('__ge__')\n    __nonzero__ = _delegate('__nonzero__')\n    __ceil__ = _delegate('__ceil__')\n    __floor__ = _delegate('__floor__')\n    __round__ = _delegate('__round__')\n\n\nclass ImageFileDirectory_v2(collections.MutableMapping):\n    \"\"\"This class represents a TIFF tag directory.  To speed things up, we\n    don't decode tags unless they're asked for.\n\n    Exposes a dictionary interface of the tags in the directory::\n\n        ifd = ImageFileDirectory_v2()\n        ifd[key] = 'Some Data'\n        ifd.tagtype[key] = 2\n        print(ifd[key])\n        'Some Data'\n\n    Individual values are returned as the strings or numbers, sequences are\n    returned as tuples of the values.\n\n    The tiff metadata type of each item is stored in a dictionary of\n    tag types in\n    `~PIL.TiffImagePlugin.ImageFileDirectory_v2.tagtype`. The types\n    are read from a tiff file, guessed from the type added, or added\n    manually.\n\n    Data Structures:\n\n        * self.tagtype = {}\n\n          * Key: numerical tiff tag number\n          * Value: integer corresponding to the data type from `~PIL.TiffTags.TYPES`\n\n    .. versionadded:: 3.0.0\n    \"\"\"\n    \"\"\"\n    Documentation:\n\n        'internal' data structures:\n        * self._tags_v2 = {} Key: numerical tiff tag number\n                             Value: decoded data, as tuple for multiple values\n        * self._tagdata = {} Key: numerical tiff tag number\n                             Value: undecoded byte string from file\n        * self._tags_v1 = {} Key: numerical tiff tag number\n                             Value: decoded data in the v1 format\n\n    Tags will be found in the private attributes self._tagdata, and in\n    self._tags_v2 once decoded.\n\n    Self.legacy_api is a value for internal use, and shouldn't be\n    changed from outside code. In cooperation with the\n    ImageFileDirectory_v1 class, if legacy_api is true, then decoded\n    tags will be populated into both _tags_v1 and _tags_v2. _Tags_v2\n    will be used if this IFD is used in the TIFF save routine. Tags\n    should be read from tags_v1 if legacy_api == true.\n\n    \"\"\"\n\n    def __init__(self, ifh=b\"II\\052\\0\\0\\0\\0\\0\", prefix=None):\n        \"\"\"Initialize an ImageFileDirectory.\n\n        To construct an ImageFileDirectory from a real file, pass the 8-byte\n        magic header to the constructor.  To only set the endianness, pass it\n        as the 'prefix' keyword argument.\n\n        :param ifh: One of the accepted magic headers (cf. PREFIXES); also sets\n              endianness.\n        :param prefix: Override the endianness of the file.\n        \"\"\"\n        if ifh[:4] not in PREFIXES:\n            raise SyntaxError(\"not a TIFF file (header %r not valid)\" % ifh)\n        self._prefix = prefix if prefix is not None else ifh[:2]\n        if self._prefix == MM:\n            self._endian = \">\"\n        elif self._prefix == II:\n            self._endian = \"<\"\n        else:\n            raise SyntaxError(\"not a TIFF IFD\")\n        self.reset()\n        self.next, = self._unpack(\"L\", ifh[4:])\n        self._legacy_api = False\n\n    prefix = property(lambda self: self._prefix)\n    offset = property(lambda self: self._offset)\n    legacy_api = property(lambda self: self._legacy_api)\n\n    @legacy_api.setter\n    def legacy_api(self, value):\n        raise Exception(\"Not allowing setting of legacy api\")\n\n    def reset(self):\n        self._tags_v1 = {}  # will remain empty if legacy_api is false\n        self._tags_v2 = {}  # main tag storage\n        self._tagdata = {}\n        self.tagtype = {}   # added 2008-06-05 by Florian Hoech\n        self._next = None\n        self._offset = None\n\n    def __str__(self):\n        return str(dict(self))\n\n    def as_dict(self):\n        \"\"\"Return a dictionary of the image's tags.\n\n        .. deprecated:: 3.0.0\n        \"\"\"\n        warnings.warn(\"as_dict() is deprecated. \" +\n                      \"Please use dict(ifd) instead.\", DeprecationWarning)\n        return dict(self)\n\n    def named(self):\n        \"\"\"\n        :returns: dict of name|key: value\n\n        Returns the complete tag dictionary, with named tags where possible.\n        \"\"\"\n        return dict((TiffTags.lookup(code).name, value)\n                    for code, value in self.items())\n\n    def __len__(self):\n        return len(set(self._tagdata) | set(self._tags_v2))\n\n    def __getitem__(self, tag):\n        if tag not in self._tags_v2:  # unpack on the fly\n            data = self._tagdata[tag]\n            typ = self.tagtype[tag]\n            size, handler = self._load_dispatch[typ]\n            self[tag] = handler(self, data, self.legacy_api)  # check type\n        val = self._tags_v2[tag]\n        if self.legacy_api and not isinstance(val, (tuple, bytes)):\n            val = val,\n        return val\n\n    def __contains__(self, tag):\n        return tag in self._tags_v2 or tag in self._tagdata\n\n    if bytes is str:\n        def has_key(self, tag):\n            return tag in self\n\n    def __setitem__(self, tag, value):\n        self._setitem(tag, value, self.legacy_api)\n\n    def _setitem(self, tag, value, legacy_api):\n        basetypes = (Number, bytes, str)\n        if bytes is str:\n            basetypes += unicode,\n\n        info = TiffTags.lookup(tag)\n        values = [value] if isinstance(value, basetypes) else value\n\n        if tag not in self.tagtype:\n            if info.type:\n                self.tagtype[tag] = info.type\n            else:\n                self.tagtype[tag] = 7\n                if all(isinstance(v, IFDRational) for v in values):\n                    self.tagtype[tag] = 5\n                elif all(isinstance(v, int) for v in values):\n                    if all(v < 2 ** 16 for v in values):\n                        self.tagtype[tag] = 3\n                    else:\n                        self.tagtype[tag] = 4\n                elif all(isinstance(v, float) for v in values):\n                    self.tagtype[tag] = 12\n                else:\n                    if bytes is str:\n                        # Never treat data as binary by default on Python 2.\n                        self.tagtype[tag] = 2\n                    else:\n                        if all(isinstance(v, str) for v in values):\n                            self.tagtype[tag] = 2\n\n        if self.tagtype[tag] == 7 and bytes is not str:\n            values = [value.encode(\"ascii\", 'replace') if isinstance(value, str) else value]\n\n        values = tuple(info.cvt_enum(value) for value in values)\n\n        dest = self._tags_v1 if legacy_api else self._tags_v2\n\n        if info.length == 1:\n            if legacy_api and self.tagtype[tag] in [5, 10]:\n                values = values,\n            dest[tag], = values\n        else:\n            dest[tag] = values\n\n    def __delitem__(self, tag):\n        self._tags_v2.pop(tag, None)\n        self._tags_v1.pop(tag, None)\n        self._tagdata.pop(tag, None)\n\n    def __iter__(self):\n        return iter(set(self._tagdata) | set(self._tags_v2))\n\n    def _unpack(self, fmt, data):\n        return struct.unpack(self._endian + fmt, data)\n\n    def _pack(self, fmt, *values):\n        return struct.pack(self._endian + fmt, *values)\n\n    def _register_loader(idx, size):\n        def decorator(func):\n            from .TiffTags import TYPES\n            if func.__name__.startswith(\"load_\"):\n                TYPES[idx] = func.__name__[5:].replace(\"_\", \" \")\n            _load_dispatch[idx] = size, func\n            return func\n        return decorator\n\n    def _register_writer(idx):\n        def decorator(func):\n            _write_dispatch[idx] = func\n            return func\n        return decorator\n\n    def _register_basic(idx_fmt_name):\n        from .TiffTags import TYPES\n        idx, fmt, name = idx_fmt_name\n        TYPES[idx] = name\n        size = struct.calcsize(\"=\" + fmt)\n        _load_dispatch[idx] = size, lambda self, data, legacy_api=True: (\n            self._unpack(\"{}{}\".format(len(data) // size, fmt), data))\n        _write_dispatch[idx] = lambda self, *values: (\n            b\"\".join(self._pack(fmt, value) for value in values))\n\n    list(map(_register_basic,\n             [(3, \"H\", \"short\"), (4, \"L\", \"long\"),\n              (6, \"b\", \"signed byte\"), (8, \"h\", \"signed short\"),\n              (9, \"l\", \"signed long\"), (11, \"f\", \"float\"), (12, \"d\", \"double\")]))\n\n    @_register_loader(1, 1)  # Basic type, except for the legacy API.\n    def load_byte(self, data, legacy_api=True):\n        return data\n\n    @_register_writer(1)  # Basic type, except for the legacy API.\n    def write_byte(self, data):\n        return data\n\n    @_register_loader(2, 1)\n    def load_string(self, data, legacy_api=True):\n        if data.endswith(b\"\\0\"):\n            data = data[:-1]\n        return data.decode(\"latin-1\", \"replace\")\n\n    @_register_writer(2)\n    def write_string(self, value):\n        # remerge of https://github.com/python-pillow/Pillow/pull/1416\n        if sys.version_info[0] == 2:\n            value = value.decode('ascii', 'replace')\n        return b\"\" + value.encode('ascii', 'replace') + b\"\\0\"\n\n    @_register_loader(5, 8)\n    def load_rational(self, data, legacy_api=True):\n        vals = self._unpack(\"{}L\".format(len(data) // 4), data)\n        combine = lambda a, b: (a, b) if legacy_api else IFDRational(a, b)\n        return tuple(combine(num, denom)\n                     for num, denom in zip(vals[::2], vals[1::2]))\n\n    @_register_writer(5)\n    def write_rational(self, *values):\n        return b\"\".join(self._pack(\"2L\", *_limit_rational(frac, 2 ** 31))\n                        for frac in values)\n\n    @_register_loader(7, 1)\n    def load_undefined(self, data, legacy_api=True):\n        return data\n\n    @_register_writer(7)\n    def write_undefined(self, value):\n        return value\n\n    @_register_loader(10, 8)\n    def load_signed_rational(self, data, legacy_api=True):\n        vals = self._unpack(\"{}l\".format(len(data) // 4), data)\n        combine = lambda a, b: (a, b) if legacy_api else IFDRational(a, b)\n        return tuple(combine(num, denom)\n                     for num, denom in zip(vals[::2], vals[1::2]))\n\n    @_register_writer(10)\n    def write_signed_rational(self, *values):\n        return b\"\".join(self._pack(\"2L\", *_limit_rational(frac, 2 ** 30))\n                        for frac in values)\n\n    def _ensure_read(self, fp, size):\n        ret = fp.read(size)\n        if len(ret) != size:\n            raise IOError(\"Corrupt EXIF data.  \" +\n                          \"Expecting to read %d bytes but only got %d. \" %\n                          (size, len(ret)))\n        return ret\n\n    def load(self, fp):\n\n        self.reset()\n        self._offset = fp.tell()\n\n        try:\n            for i in range(self._unpack(\"H\", self._ensure_read(fp, 2))[0]):\n                tag, typ, count, data = self._unpack(\"HHL4s\", self._ensure_read(fp, 12))\n                if DEBUG:\n                    tagname = TiffTags.lookup(tag).name\n                    typname = TYPES.get(typ, \"unknown\")\n                    print(\"tag: %s (%d) - type: %s (%d)\" %\n                          (tagname, tag, typname, typ), end=\" \")\n\n                try:\n                    unit_size, handler = self._load_dispatch[typ]\n                except KeyError:\n                    if DEBUG:\n                        print(\"- unsupported type\", typ)\n                    continue  # ignore unsupported type\n                size = count * unit_size\n                if size > 4:\n                    here = fp.tell()\n                    offset, = self._unpack(\"L\", data)\n                    if DEBUG:\n                        print(\"Tag Location: %s - Data Location: %s\" %\n                              (here, offset), end=\" \")\n                    fp.seek(offset)\n                    data = ImageFile._safe_read(fp, size)\n                    fp.seek(here)\n                else:\n                    data = data[:size]\n\n                if len(data) != size:\n                    warnings.warn(\"Possibly corrupt EXIF data.  \"\n                                  \"Expecting to read %d bytes but only got %d. \"\n                                  \"Skipping tag %s\" % (size, len(data), tag))\n                    continue\n\n                if not data:\n                    continue\n\n                self._tagdata[tag] = data\n                self.tagtype[tag] = typ\n\n                if DEBUG:\n                    if size > 32:\n                        print(\"- value: <table: %d bytes>\" % size)\n                    else:\n                        print(\"- value:\", self[tag])\n\n            self.next, = self._unpack(\"L\", self._ensure_read(fp, 4))\n        except IOError as msg:\n            warnings.warn(str(msg))\n            return\n\n    def save(self, fp):\n\n        if fp.tell() == 0:  # skip TIFF header on subsequent pages\n            # tiff header -- PIL always starts the first IFD at offset 8\n            fp.write(self._prefix + self._pack(\"HL\", 42, 8))\n\n        # FIXME What about tagdata?\n        fp.write(self._pack(\"H\", len(self._tags_v2)))\n\n        entries = []\n        offset = fp.tell() + len(self._tags_v2) * 12 + 4\n        stripoffsets = None\n\n        # pass 1: convert tags to binary format\n        # always write tags in ascending order\n        for tag, value in sorted(self._tags_v2.items()):\n            if tag == STRIPOFFSETS:\n                stripoffsets = len(entries)\n            typ = self.tagtype.get(tag)\n            if DEBUG:\n                print(\"Tag %s, Type: %s, Value: %s\" % (tag, typ, value))\n            values = value if isinstance(value, tuple) else (value,)\n            data = self._write_dispatch[typ](self, *values)\n            if DEBUG:\n                tagname = TiffTags.lookup(tag).name\n                typname = TYPES.get(typ, \"unknown\")\n                print(\"save: %s (%d) - type: %s (%d)\" %\n                      (tagname, tag, typname, typ), end=\" \")\n                if len(data) >= 16:\n                    print(\"- value: <table: %d bytes>\" % len(data))\n                else:\n                    print(\"- value:\", values)\n\n            # count is sum of lengths for string and arbitrary data\n            count = len(data) if typ in [2, 7] else len(values)\n            # figure out if data fits into the entry\n            if len(data) <= 4:\n                entries.append((tag, typ, count, data.ljust(4, b\"\\0\"), b\"\"))\n            else:\n                entries.append((tag, typ, count, self._pack(\"L\", offset), data))\n                offset += (len(data) + 1) // 2 * 2  # pad to word\n\n        # update strip offset data to point beyond auxiliary data\n        if stripoffsets is not None:\n            tag, typ, count, value, data = entries[stripoffsets]\n            if data:\n                raise NotImplementedError(\n                    \"multistrip support not yet implemented\")\n            value = self._pack(\"L\", self._unpack(\"L\", value)[0] + offset)\n            entries[stripoffsets] = tag, typ, count, value, data\n\n        # pass 2: write entries to file\n        for tag, typ, count, value, data in entries:\n            if DEBUG > 1:\n                print(tag, typ, count, repr(value), repr(data))\n            fp.write(self._pack(\"HHL4s\", tag, typ, count, value))\n\n        # -- overwrite here for multi-page --\n        fp.write(b\"\\0\\0\\0\\0\")  # end of entries\n\n        # pass 3: write auxiliary data to file\n        for tag, typ, count, value, data in entries:\n            fp.write(data)\n            if len(data) & 1:\n                fp.write(b\"\\0\")\n\n        return offset\n\nImageFileDirectory_v2._load_dispatch = _load_dispatch\nImageFileDirectory_v2._write_dispatch = _write_dispatch\nfor idx, name in TYPES.items():\n    name = name.replace(\" \", \"_\")\n    setattr(ImageFileDirectory_v2, \"load_\" + name, _load_dispatch[idx][1])\n    setattr(ImageFileDirectory_v2, \"write_\" + name, _write_dispatch[idx])\ndel _load_dispatch, _write_dispatch, idx, name\n\n\n# Legacy ImageFileDirectory support.\nclass ImageFileDirectory_v1(ImageFileDirectory_v2):\n    \"\"\"This class represents the **legacy** interface to a TIFF tag directory.\n\n    Exposes a dictionary interface of the tags in the directory::\n\n        ifd = ImageFileDirectory_v1()\n        ifd[key] = 'Some Data'\n        ifd.tagtype[key] = 2\n        print(ifd[key])\n        ('Some Data',)\n\n    Also contains a dictionary of tag types as read from the tiff image file,\n    `~PIL.TiffImagePlugin.ImageFileDirectory_v1.tagtype`.\n\n    Values are returned as a tuple.\n\n    ..  deprecated:: 3.0.0\n    \"\"\"\n    def __init__(self, *args, **kwargs):\n        ImageFileDirectory_v2.__init__(self, *args, **kwargs)\n        self._legacy_api = True\n\n    tags = property(lambda self: self._tags_v1)\n    tagdata = property(lambda self: self._tagdata)\n\n    @classmethod\n    def from_v2(cls, original):\n        \"\"\" Returns an\n        :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`\n        instance with the same data as is contained in the original\n        :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`\n        instance.\n\n        :returns: :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`\n\n        \"\"\"\n\n        ifd = cls(prefix=original.prefix)\n        ifd._tagdata = original._tagdata\n        ifd.tagtype = original.tagtype\n        ifd.next = original.next  # an indicator for multipage tiffs\n        return ifd\n\n    def to_v2(self):\n        \"\"\" Returns an\n        :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`\n        instance with the same data as is contained in the original\n        :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`\n        instance.\n\n        :returns: :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`\n\n        \"\"\"\n\n        ifd = ImageFileDirectory_v2(prefix=self.prefix)\n        ifd._tagdata = dict(self._tagdata)\n        ifd.tagtype = dict(self.tagtype)\n        ifd._tags_v2 = dict(self._tags_v2)\n        return ifd\n\n    def __contains__(self, tag):\n        return tag in self._tags_v1 or tag in self._tagdata\n\n    def __len__(self):\n        return len(set(self._tagdata) | set(self._tags_v1))\n\n    def __iter__(self):\n        return iter(set(self._tagdata) | set(self._tags_v1))\n\n    def __setitem__(self, tag, value):\n        for legacy_api in (False, True):\n            self._setitem(tag, value, legacy_api)\n\n    def __getitem__(self, tag):\n        if tag not in self._tags_v1:  # unpack on the fly\n            data = self._tagdata[tag]\n            typ = self.tagtype[tag]\n            size, handler = self._load_dispatch[typ]\n            for legacy in (False, True):\n                self._setitem(tag, handler(self, data, legacy), legacy)\n        val = self._tags_v1[tag]\n        if not isinstance(val, (tuple, bytes)):\n            val = val,\n        return val\n\n\n# undone -- switch this pointer when IFD_LEGACY_API == False\nImageFileDirectory = ImageFileDirectory_v1\n\n\n##\n# Image plugin for TIFF files.\n\nclass TiffImageFile(ImageFile.ImageFile):\n\n    format = \"TIFF\"\n    format_description = \"Adobe TIFF\"\n\n    def _open(self):\n        \"Open the first image in a TIFF file\"\n\n        # Header\n        ifh = self.fp.read(8)\n\n        # image file directory (tag dictionary)\n        self.tag_v2 = ImageFileDirectory_v2(ifh)\n\n        # legacy tag/ifd entries will be filled in later\n        self.tag = self.ifd = None\n\n        # setup frame pointers\n        self.__first = self.__next = self.tag_v2.next\n        self.__frame = -1\n        self.__fp = self.fp\n        self._frame_pos = []\n        self._n_frames = None\n        self._is_animated = None\n\n        if DEBUG:\n            print(\"*** TiffImageFile._open ***\")\n            print(\"- __first:\", self.__first)\n            print(\"- ifh: \", ifh)\n\n        # and load the first frame\n        self._seek(0)\n\n    @property\n    def n_frames(self):\n        if self._n_frames is None:\n            current = self.tell()\n            try:\n                while True:\n                    self._seek(self.tell() + 1)\n            except EOFError:\n                self._n_frames = self.tell() + 1\n            self.seek(current)\n        return self._n_frames\n\n    @property\n    def is_animated(self):\n        if self._is_animated is None:\n            current = self.tell()\n\n            try:\n                self.seek(1)\n                self._is_animated = True\n            except EOFError:\n                self._is_animated = False\n\n            self.seek(current)\n        return self._is_animated\n\n    def seek(self, frame):\n        \"Select a given frame as current image\"\n        self._seek(max(frame, 0))  # Questionable backwards compatibility.\n        # Create a new core image object on second and\n        # subsequent frames in the image. Image may be\n        # different size/mode.\n        Image._decompression_bomb_check(self.size)\n        self.im = Image.core.new(self.mode, self.size)\n\n    def _seek(self, frame):\n        self.fp = self.__fp\n        while len(self._frame_pos) <= frame:\n            if not self.__next:\n                raise EOFError(\"no more images in TIFF file\")\n            if DEBUG:\n                print(\"Seeking to frame %s, on frame %s, \"\n                      \"__next %s, location: %s\" %\n                      (frame, self.__frame, self.__next, self.fp.tell()))\n            # reset python3 buffered io handle in case fp\n            # was passed to libtiff, invalidating the buffer\n            self.fp.tell()\n            self.fp.seek(self.__next)\n            self._frame_pos.append(self.__next)\n            if DEBUG:\n                print(\"Loading tags, location: %s\" % self.fp.tell())\n            self.tag_v2.load(self.fp)\n            self.__next = self.tag_v2.next\n            self.__frame += 1\n        self.fp.seek(self._frame_pos[frame])\n        self.tag_v2.load(self.fp)\n        # fill the legacy tag/ifd entries\n        self.tag = self.ifd = ImageFileDirectory_v1.from_v2(self.tag_v2)\n        self.__frame = frame\n        self._setup()\n\n    def tell(self):\n        \"Return the current frame number\"\n        return self.__frame\n\n    def _decoder(self, rawmode, layer, tile=None):\n        \"Setup decoder contexts\"\n\n        args = None\n        if rawmode == \"RGB\" and self._planar_configuration == 2:\n            rawmode = rawmode[layer]\n        compression = self._compression\n        if compression == \"raw\":\n            args = (rawmode, 0, 1)\n        elif compression == \"jpeg\":\n            args = rawmode, \"\"\n            if JPEGTABLES in self.tag_v2:\n                # Hack to handle abbreviated JPEG headers\n                # FIXME This will fail with more than one value\n                self.tile_prefix, = self.tag_v2[JPEGTABLES]\n        elif compression == \"packbits\":\n            args = rawmode\n        elif compression == \"tiff_lzw\":\n            args = rawmode\n            if PREDICTOR in self.tag_v2:\n                # Section 14: Differencing Predictor\n                self.decoderconfig = (self.tag_v2[PREDICTOR],)\n\n        return args\n\n    def load(self):\n        if self.use_load_libtiff:\n            return self._load_libtiff()\n        return super(TiffImageFile, self).load()\n\n    def _load_libtiff(self):\n        \"\"\" Overload method triggered when we detect a compressed tiff\n            Calls out to libtiff \"\"\"\n\n        pixel = Image.Image.load(self)\n\n        if self.tile is None:\n            raise IOError(\"cannot load this image\")\n        if not self.tile:\n            return pixel\n\n        self.load_prepare()\n\n        if not len(self.tile) == 1:\n            raise IOError(\"Not exactly one tile\")\n\n        # (self._compression, (extents tuple),\n        #   0, (rawmode, self._compression, fp))\n        extents = self.tile[0][1]\n        args = list(self.tile[0][3]) + [self.tag_v2.offset]\n\n        # To be nice on memory footprint, if there's a\n        # file descriptor, use that instead of reading\n        # into a string in python.\n        # libtiff closes the file descriptor, so pass in a dup.\n        try:\n            fp = hasattr(self.fp, \"fileno\") and os.dup(self.fp.fileno())\n            # flush the file descriptor, prevents error on pypy 2.4+\n            # should also eliminate the need for fp.tell for py3\n            # in _seek\n            if hasattr(self.fp, \"flush\"):\n                self.fp.flush()\n        except IOError:\n            # io.BytesIO have a fileno, but returns an IOError if\n            # it doesn't use a file descriptor.\n            fp = False\n\n        if fp:\n            args[2] = fp\n\n        decoder = Image._getdecoder(self.mode, 'libtiff', tuple(args),\n                                    self.decoderconfig)\n        try:\n            decoder.setimage(self.im, extents)\n        except ValueError:\n            raise IOError(\"Couldn't set the image\")\n\n        if hasattr(self.fp, \"getvalue\"):\n            # We've got a stringio like thing passed in. Yay for all in memory.\n            # The decoder needs the entire file in one shot, so there's not\n            # a lot we can do here other than give it the entire file.\n            # unless we could do something like get the address of the\n            # underlying string for stringio.\n            #\n            # Rearranging for supporting byteio items, since they have a fileno\n            # that returns an IOError if there's no underlying fp. Easier to\n            # deal with here by reordering.\n            if DEBUG:\n                print(\"have getvalue. just sending in a string from getvalue\")\n            n, err = decoder.decode(self.fp.getvalue())\n        elif hasattr(self.fp, \"fileno\"):\n            # we've got a actual file on disk, pass in the fp.\n            if DEBUG:\n                print(\"have fileno, calling fileno version of the decoder.\")\n            self.fp.seek(0)\n            # 4 bytes, otherwise the trace might error out\n            n, err = decoder.decode(b\"fpfp\")\n        else:\n            # we have something else.\n            if DEBUG:\n                print(\"don't have fileno or getvalue. just reading\")\n            # UNDONE -- so much for that buffer size thing.\n            n, err = decoder.decode(self.fp.read())\n\n        self.tile = []\n        self.readonly = 0\n        # libtiff closed the fp in a, we need to close self.fp, if possible\n        if hasattr(self.fp, 'close'):\n            if not self.__next:\n                self.fp.close()\n        self.fp = None  # might be shared\n\n        if err < 0:\n            raise IOError(err)\n\n        self.load_end()\n\n        return Image.Image.load(self)\n\n    def _setup(self):\n        \"Setup this image object based on current tags\"\n\n        if 0xBC01 in self.tag_v2:\n            raise IOError(\"Windows Media Photo files not yet supported\")\n\n        # extract relevant tags\n        self._compression = COMPRESSION_INFO[self.tag_v2.get(COMPRESSION, 1)]\n        self._planar_configuration = self.tag_v2.get(PLANAR_CONFIGURATION, 1)\n\n        # photometric is a required tag, but not everyone is reading\n        # the specification\n        photo = self.tag_v2.get(PHOTOMETRIC_INTERPRETATION, 0)\n\n        fillorder = self.tag_v2.get(FILLORDER, 1)\n\n        if DEBUG:\n            print(\"*** Summary ***\")\n            print(\"- compression:\", self._compression)\n            print(\"- photometric_interpretation:\", photo)\n            print(\"- planar_configuration:\", self._planar_configuration)\n            print(\"- fill_order:\", fillorder)\n\n        # size\n        xsize = self.tag_v2.get(IMAGEWIDTH)\n        ysize = self.tag_v2.get(IMAGELENGTH)\n        self.size = xsize, ysize\n\n        if DEBUG:\n            print(\"- size:\", self.size)\n\n        sampleFormat = self.tag_v2.get(SAMPLEFORMAT, (1,))\n        if (len(sampleFormat) > 1\n            and max(sampleFormat) == min(sampleFormat) == 1):\n            # SAMPLEFORMAT is properly per band, so an RGB image will\n            # be (1,1,1).  But, we don't support per band pixel types,\n            # and anything more than one band is a uint8. So, just\n            # take the first element. Revisit this if adding support\n            # for more exotic images.\n            sampleFormat = (1,)\n\n        # mode: check photometric interpretation and bits per pixel\n        key = (\n            self.tag_v2.prefix, photo, sampleFormat, fillorder,\n            self.tag_v2.get(BITSPERSAMPLE, (1,)),\n            self.tag_v2.get(EXTRASAMPLES, ())\n            )\n        if DEBUG:\n            print(\"format key:\", key)\n        try:\n            self.mode, rawmode = OPEN_INFO[key]\n        except KeyError:\n            if DEBUG:\n                print(\"- unsupported format\")\n            raise SyntaxError(\"unknown pixel mode\")\n\n        if DEBUG:\n            print(\"- raw mode:\", rawmode)\n            print(\"- pil mode:\", self.mode)\n\n        self.info[\"compression\"] = self._compression\n\n        xres = self.tag_v2.get(X_RESOLUTION, 1)\n        yres = self.tag_v2.get(Y_RESOLUTION, 1)\n\n        if xres and yres:\n            resunit = self.tag_v2.get(RESOLUTION_UNIT, 1)\n            if resunit == 2:  # dots per inch\n                self.info[\"dpi\"] = xres, yres\n            elif resunit == 3:  # dots per centimeter. convert to dpi\n                self.info[\"dpi\"] = xres * 2.54, yres * 2.54\n            else:  # No absolute unit of measurement\n                self.info[\"resolution\"] = xres, yres\n\n        # build tile descriptors\n        x = y = l = 0\n        self.tile = []\n        self.use_load_libtiff = False\n        if STRIPOFFSETS in self.tag_v2:\n            # striped image\n            offsets = self.tag_v2[STRIPOFFSETS]\n            h = self.tag_v2.get(ROWSPERSTRIP, ysize)\n            w = self.size[0]\n            if READ_LIBTIFF or self._compression in [\"tiff_ccitt\", \"group3\",\n                                                     \"group4\", \"tiff_jpeg\",\n                                                     \"tiff_adobe_deflate\",\n                                                     \"tiff_thunderscan\",\n                                                     \"tiff_deflate\",\n                                                     \"tiff_sgilog\",\n                                                     \"tiff_sgilog24\",\n                                                     \"tiff_raw_16\"]:\n                # if DEBUG:\n                #     print(\"Activating g4 compression for whole file\")\n\n                # Decoder expects entire file as one tile.\n                # There's a buffer size limit in load (64k)\n                # so large g4 images will fail if we use that\n                # function.\n                #\n                # Setup the one tile for the whole image, then\n                # use the _load_libtiff function.\n\n                self.use_load_libtiff = True\n\n                # libtiff handles the fillmode for us, so 1;IR should\n                # actually be 1;I. Including the R double reverses the\n                # bits, so stripes of the image are reversed.  See\n                # https://github.com/python-pillow/Pillow/issues/279\n                if fillorder == 2:\n                    key = (\n                        self.tag_v2.prefix, photo, sampleFormat, 1,\n                        self.tag_v2.get(BITSPERSAMPLE, (1,)),\n                        self.tag_v2.get(EXTRASAMPLES, ())\n                        )\n                    if DEBUG:\n                        print(\"format key:\", key)\n                    # this should always work, since all the\n                    # fillorder==2 modes have a corresponding\n                    # fillorder=1 mode\n                    self.mode, rawmode = OPEN_INFO[key]\n                # libtiff always returns the bytes in native order.\n                # we're expecting image byte order. So, if the rawmode\n                # contains I;16, we need to convert from native to image\n                # byte order.\n                if self.mode in ('I;16B', 'I;16') and 'I;16' in rawmode:\n                    rawmode = 'I;16N'\n\n                # Offset in the tile tuple is 0, we go from 0,0 to\n                # w,h, and we only do this once -- eds\n                a = (rawmode, self._compression, False)\n                self.tile.append(\n                    (self._compression,\n                     (0, 0, w, ysize),\n                     0, a))\n                a = None\n\n            else:\n                for i, offset in enumerate(offsets):\n                    a = self._decoder(rawmode, l, i)\n                    self.tile.append(\n                        (self._compression,\n                            (0, min(y, ysize), w, min(y+h, ysize)),\n                            offset, a))\n                    if DEBUG:\n                        print(\"tiles: \", self.tile)\n                    y = y + h\n                    if y >= self.size[1]:\n                        x = y = 0\n                        l += 1\n                    a = None\n        elif TILEOFFSETS in self.tag_v2:\n            # tiled image\n            w = self.tag_v2.get(322)\n            h = self.tag_v2.get(323)\n            a = None\n            for o in self.tag_v2[TILEOFFSETS]:\n                if not a:\n                    a = self._decoder(rawmode, l)\n                # FIXME: this doesn't work if the image size\n                # is not a multiple of the tile size...\n                self.tile.append(\n                    (self._compression,\n                        (x, y, x+w, y+h),\n                        o, a))\n                x = x + w\n                if x >= self.size[0]:\n                    x, y = 0, y + h\n                    if y >= self.size[1]:\n                        x = y = 0\n                        l += 1\n                        a = None\n        else:\n            if DEBUG:\n                print(\"- unsupported data organization\")\n            raise SyntaxError(\"unknown data organization\")\n\n        # Fix up info.\n        if ICCPROFILE in self.tag_v2:\n            self.info['icc_profile'] = self.tag_v2[ICCPROFILE]\n\n        # fixup palette descriptor\n\n        if self.mode == \"P\":\n            palette = [o8(b // 256) for b in self.tag_v2[COLORMAP]]\n            self.palette = ImagePalette.raw(\"RGB;L\", b\"\".join(palette))\n#\n# --------------------------------------------------------------------\n# Write TIFF files\n\n# little endian is default except for image modes with\n# explicit big endian byte-order\n\nSAVE_INFO = {\n    # mode => rawmode, byteorder, photometrics,\n    #           sampleformat, bitspersample, extra\n    \"1\": (\"1\", II, 1, 1, (1,), None),\n    \"L\": (\"L\", II, 1, 1, (8,), None),\n    \"LA\": (\"LA\", II, 1, 1, (8, 8), 2),\n    \"P\": (\"P\", II, 3, 1, (8,), None),\n    \"PA\": (\"PA\", II, 3, 1, (8, 8), 2),\n    \"I\": (\"I;32S\", II, 1, 2, (32,), None),\n    \"I;16\": (\"I;16\", II, 1, 1, (16,), None),\n    \"I;16S\": (\"I;16S\", II, 1, 2, (16,), None),\n    \"F\": (\"F;32F\", II, 1, 3, (32,), None),\n    \"RGB\": (\"RGB\", II, 2, 1, (8, 8, 8), None),\n    \"RGBX\": (\"RGBX\", II, 2, 1, (8, 8, 8, 8), 0),\n    \"RGBA\": (\"RGBA\", II, 2, 1, (8, 8, 8, 8), 2),\n    \"CMYK\": (\"CMYK\", II, 5, 1, (8, 8, 8, 8), None),\n    \"YCbCr\": (\"YCbCr\", II, 6, 1, (8, 8, 8), None),\n    \"LAB\": (\"LAB\", II, 8, 1, (8, 8, 8), None),\n\n    \"I;32BS\": (\"I;32BS\", MM, 1, 2, (32,), None),\n    \"I;16B\": (\"I;16B\", MM, 1, 1, (16,), None),\n    \"I;16BS\": (\"I;16BS\", MM, 1, 2, (16,), None),\n    \"F;32BF\": (\"F;32BF\", MM, 1, 3, (32,), None),\n}\n\n\ndef _save(im, fp, filename):\n\n    try:\n        rawmode, prefix, photo, format, bits, extra = SAVE_INFO[im.mode]\n    except KeyError:\n        raise IOError(\"cannot write mode %s as TIFF\" % im.mode)\n\n    ifd = ImageFileDirectory_v2(prefix=prefix)\n\n    compression = im.encoderinfo.get('compression',\n                                     im.info.get('compression', 'raw'))\n\n    libtiff = WRITE_LIBTIFF or compression != 'raw'\n\n    # required for color libtiff images\n    ifd[PLANAR_CONFIGURATION] = getattr(im, '_planar_configuration', 1)\n\n    ifd[IMAGEWIDTH] = im.size[0]\n    ifd[IMAGELENGTH] = im.size[1]\n\n    # write any arbitrary tags passed in as an ImageFileDirectory\n    info = im.encoderinfo.get(\"tiffinfo\", {})\n    if DEBUG:\n        print(\"Tiffinfo Keys: %s\" % list(info))\n    if isinstance(info, ImageFileDirectory_v1):\n        info = info.to_v2()\n    for key in info:\n        ifd[key] = info.get(key)\n        try:\n            ifd.tagtype[key] = info.tagtype[key]\n        except:\n            pass  # might not be an IFD, Might not have populated type\n\n    # additions written by Greg Couch, gregc@cgl.ucsf.edu\n    # inspired by image-sig posting from Kevin Cazabon, kcazabon@home.com\n    if hasattr(im, 'tag_v2'):\n        # preserve tags from original TIFF image file\n        for key in (RESOLUTION_UNIT, X_RESOLUTION, Y_RESOLUTION,\n                    IPTC_NAA_CHUNK, PHOTOSHOP_CHUNK, XMP):\n            if key in im.tag_v2:\n                ifd[key] = im.tag_v2[key]\n                ifd.tagtype[key] = im.tag_v2.tagtype[key]\n\n    # preserve ICC profile (should also work when saving other formats\n    # which support profiles as TIFF) -- 2008-06-06 Florian Hoech\n    if \"icc_profile\" in im.info:\n        ifd[ICCPROFILE] = im.info[\"icc_profile\"]\n\n    for key, name in [(IMAGEDESCRIPTION, \"description\"),\n                      (X_RESOLUTION, \"resolution\"),\n                      (Y_RESOLUTION, \"resolution\"),\n                      (X_RESOLUTION, \"x_resolution\"),\n                      (Y_RESOLUTION, \"y_resolution\"),\n                      (RESOLUTION_UNIT, \"resolution_unit\"),\n                      (SOFTWARE, \"software\"),\n                      (DATE_TIME, \"date_time\"),\n                      (ARTIST, \"artist\"),\n                      (COPYRIGHT, \"copyright\")]:\n        name_with_spaces = name.replace(\"_\", \" \")\n        if \"_\" in name and name_with_spaces in im.encoderinfo:\n            warnings.warn(\"%r is deprecated; use %r instead\" %\n                          (name_with_spaces, name), DeprecationWarning)\n            ifd[key] = im.encoderinfo[name.replace(\"_\", \" \")]\n        if name in im.encoderinfo:\n            ifd[key] = im.encoderinfo[name]\n\n    dpi = im.encoderinfo.get(\"dpi\")\n    if dpi:\n        ifd[RESOLUTION_UNIT] = 2\n        ifd[X_RESOLUTION] = dpi[0]\n        ifd[Y_RESOLUTION] = dpi[1]\n\n    if bits != (1,):\n        ifd[BITSPERSAMPLE] = bits\n        if len(bits) != 1:\n            ifd[SAMPLESPERPIXEL] = len(bits)\n    if extra is not None:\n        ifd[EXTRASAMPLES] = extra\n    if format != 1:\n        ifd[SAMPLEFORMAT] = format\n\n    ifd[PHOTOMETRIC_INTERPRETATION] = photo\n\n    if im.mode == \"P\":\n        lut = im.im.getpalette(\"RGB\", \"RGB;L\")\n        ifd[COLORMAP] = tuple(i8(v) * 256 for v in lut)\n    # data orientation\n    stride = len(bits) * ((im.size[0]*bits[0]+7)//8)\n    ifd[ROWSPERSTRIP] = im.size[1]\n    ifd[STRIPBYTECOUNTS] = stride * im.size[1]\n    ifd[STRIPOFFSETS] = 0  # this is adjusted by IFD writer\n    # no compression by default:\n    ifd[COMPRESSION] = COMPRESSION_INFO_REV.get(compression, 1)\n\n    if libtiff:\n        if DEBUG:\n            print(\"Saving using libtiff encoder\")\n            print(\"Items: %s\" % sorted(ifd.items()))\n        _fp = 0\n        if hasattr(fp, \"fileno\"):\n            try:\n                fp.seek(0)\n                _fp = os.dup(fp.fileno())\n            except io.UnsupportedOperation:\n                pass\n\n        # STRIPOFFSETS and STRIPBYTECOUNTS are added by the library\n        # based on the data in the strip.\n        blocklist = [STRIPOFFSETS, STRIPBYTECOUNTS]\n        atts = {}\n        # bits per sample is a single short in the tiff directory, not a list.\n        atts[BITSPERSAMPLE] = bits[0]\n        # Merge the ones that we have with (optional) more bits from\n        # the original file, e.g x,y resolution so that we can\n        # save(load('')) == original file.\n        legacy_ifd = {}\n        if hasattr(im, 'tag'):\n            legacy_ifd = im.tag.to_v2()\n        for tag, value in itertools.chain(ifd.items(),\n                                          getattr(im, 'tag_v2', {}).items(),\n                                          legacy_ifd.items()):\n            # Libtiff can only process certain core items without adding\n            # them to the custom dictionary. It will segfault if it attempts\n            # to add a custom tag without the dictionary entry\n            #\n            # UNDONE --  add code for the custom dictionary\n            if tag not in TiffTags.LIBTIFF_CORE:\n                continue\n            if tag not in atts and tag not in blocklist:\n                if isinstance(value, unicode if bytes is str else str):\n                    atts[tag] = value.encode('ascii', 'replace') + b\"\\0\"\n                elif isinstance(value, IFDRational):\n                    atts[tag] = float(value)\n                else:\n                    atts[tag] = value\n\n        if DEBUG:\n            print(\"Converted items: %s\" % sorted(atts.items()))\n\n        # libtiff always expects the bytes in native order.\n        # we're storing image byte order. So, if the rawmode\n        # contains I;16, we need to convert from native to image\n        # byte order.\n        if im.mode in ('I;16B', 'I;16'):\n            rawmode = 'I;16N'\n\n        a = (rawmode, compression, _fp, filename, atts)\n        # print(im.mode, compression, a, im.encoderconfig)\n        e = Image._getencoder(im.mode, 'libtiff', a, im.encoderconfig)\n        e.setimage(im.im, (0, 0)+im.size)\n        while True:\n            # undone, change to self.decodermaxblock:\n            l, s, d = e.encode(16*1024)\n            if not _fp:\n                fp.write(d)\n            if s:\n                break\n        if s < 0:\n            raise IOError(\"encoder error %d when writing image file\" % s)\n\n    else:\n        offset = ifd.save(fp)\n\n        ImageFile._save(im, fp, [\n            (\"raw\", (0, 0)+im.size, offset, (rawmode, stride, 1))\n            ])\n\n    # -- helper for multi-page save --\n    if \"_debug_multipage\" in im.encoderinfo:\n        # just to access o32 and o16 (using correct byte order)\n        im._debug_multipage = ifd\n\nclass AppendingTiffWriter:\n    fieldSizes = [\n        0,  # None\n        1,  # byte\n        1,  # ascii\n        2,  # short\n        4,  # long\n        8,  # rational\n        1,  # sbyte\n        1,  # undefined\n        2,  # sshort\n        4,  # slong\n        8,  # srational\n        4,  # float\n        8,  # double\n    ]\n\n    #    StripOffsets = 273\n    #    FreeOffsets = 288\n    #    TileOffsets = 324\n    #    JPEGQTables = 519\n    #    JPEGDCTables = 520\n    #    JPEGACTables = 521\n    Tags = {273, 288, 324, 519, 520, 521}\n\n    def __init__(self, fn, new=False):\n        if hasattr(fn, 'read'):\n            self.f = fn\n            self.close_fp = False\n        else:\n            self.name = fn\n            self.close_fp = True\n            try:\n                self.f = io.open(fn, \"w+b\" if new else \"r+b\")\n            except IOError:\n                self.f = io.open(fn, \"w+b\")\n        self.beginning = self.f.tell()\n        self.setup()\n\n    def setup(self):\n        # Reset everything.\n        self.f.seek(self.beginning, os.SEEK_SET)\n\n        self.whereToWriteNewIFDOffset = None\n        self.offsetOfNewPage = 0\n\n        self.IIMM = IIMM = self.f.read(4)\n        if not IIMM:\n            # empty file - first page\n            self.isFirst = True\n            return\n\n        self.isFirst = False\n        if IIMM == b\"II\\x2a\\x00\":\n            self.setEndian(\"<\")\n        elif IIMM == b\"MM\\x00\\x2a\":\n            self.setEndian(\">\")\n        else:\n            raise RuntimeError(\"Invalid TIFF file header\")\n\n        self.skipIFDs()\n        self.goToEnd()\n\n    def finalize(self):\n        if self.isFirst:\n            return\n\n        # fix offsets\n        self.f.seek(self.offsetOfNewPage)\n\n        IIMM = self.f.read(4)\n        if not IIMM:\n            # raise RuntimeError(\"nothing written into new page\")\n            # Make it easy to finish a frame without committing to a new one.\n            return\n\n        if IIMM != self.IIMM:\n            raise RuntimeError(\"IIMM of new page doesn't match IIMM of \"\n                               \"first page\")\n\n        IFDoffset = self.readLong()\n        IFDoffset += self.offsetOfNewPage\n        self.f.seek(self.whereToWriteNewIFDOffset)\n        self.writeLong(IFDoffset)\n        self.f.seek(IFDoffset)\n        self.fixIFD()\n\n    def newFrame(self):\n        # Call this to finish a frame.\n        self.finalize()\n        self.setup()\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, exc_type, exc_value, traceback):\n        if self.close_fp:\n            self.close()\n        return False\n\n    def tell(self):\n        return self.f.tell() - self.offsetOfNewPage\n\n    def seek(self, offset, whence):\n        if whence == os.SEEK_SET:\n            offset += self.offsetOfNewPage\n\n        self.f.seek(offset, whence)\n        return self.tell()\n\n    def goToEnd(self):\n        self.f.seek(0, os.SEEK_END)\n        pos = self.f.tell()\n\n        # pad to 16 byte boundary\n        padBytes = 16 - pos % 16\n        if 0 < padBytes < 16:\n            self.f.write(bytes(bytearray(padBytes)))\n        self.offsetOfNewPage = self.f.tell()\n\n    def setEndian(self, endian):\n        self.endian = endian\n        self.longFmt = self.endian + \"L\"\n        self.shortFmt = self.endian + \"H\"\n        self.tagFormat = self.endian + \"HHL\"\n\n    def skipIFDs(self):\n        while True:\n            IFDoffset = self.readLong()\n            if IFDoffset == 0:\n                self.whereToWriteNewIFDOffset = self.f.tell() - 4\n                break\n\n            self.f.seek(IFDoffset)\n            numTags = self.readShort()\n            self.f.seek(numTags * 12, os.SEEK_CUR)\n\n    def write(self, data):\n        return self.f.write(data)\n\n    def readShort(self):\n        value, = struct.unpack(self.shortFmt, self.f.read(2))\n        return value\n\n    def readLong(self):\n        value, = struct.unpack(self.longFmt, self.f.read(4))\n        return value\n\n    def rewriteLastShortToLong(self, value):\n        self.f.seek(-2, os.SEEK_CUR)\n        bytesWritten = self.f.write(struct.pack(self.longFmt, value))\n        if bytesWritten is not None and bytesWritten != 4:\n            raise RuntimeError(\"wrote only %u bytes but wanted 4\" %\n                               bytesWritten)\n\n    def rewriteLastShort(self, value):\n        self.f.seek(-2, os.SEEK_CUR)\n        bytesWritten = self.f.write(struct.pack(self.shortFmt, value))\n        if bytesWritten is not None and bytesWritten != 2:\n            raise RuntimeError(\"wrote only %u bytes but wanted 2\" %\n                               bytesWritten)\n\n    def rewriteLastLong(self, value):\n        self.f.seek(-4, os.SEEK_CUR)\n        bytesWritten = self.f.write(struct.pack(self.longFmt, value))\n        if bytesWritten is not None and bytesWritten != 4:\n            raise RuntimeError(\"wrote only %u bytes but wanted 4\" %\n                               bytesWritten)\n\n    def writeShort(self, value):\n        bytesWritten = self.f.write(struct.pack(self.shortFmt, value))\n        if bytesWritten is not None and bytesWritten != 2:\n            raise RuntimeError(\"wrote only %u bytes but wanted 2\" %\n                               bytesWritten)\n\n    def writeLong(self, value):\n        bytesWritten = self.f.write(struct.pack(self.longFmt, value))\n        if bytesWritten is not None and bytesWritten != 4:\n            raise RuntimeError(\"wrote only %u bytes but wanted 4\" %\n                               bytesWritten)\n\n    def close(self):\n        self.finalize()\n        self.f.close()\n\n    def fixIFD(self):\n        numTags = self.readShort()\n        #trace(\"fixing IFD at %X; number of tags: %u (0x%X)\", self.f.tell()-2,\n        #      numTags, numTags)\n\n        for i in range(numTags):\n            tag, fieldType, count = struct.unpack(self.tagFormat, self.f.read(8))\n            #trace(\"  at %X: tag %u (0x%X), type %u, count %u\", self.f.tell()-8,\n            #      tag, tag, fieldType, count)\n\n            fieldSize = self.fieldSizes[fieldType]\n            totalSize = fieldSize * count\n            isLocal = (totalSize <= 4)\n            if not isLocal:\n                offset = self.readLong()\n                offset += self.offsetOfNewPage\n                self.rewriteLastLong(offset)\n\n            if tag in self.Tags:\n                curPos = self.f.tell()\n\n                if isLocal:\n                    self.fixOffsets(count, isShort=(fieldSize == 2),\n                                    isLong=(fieldSize == 4))\n                    self.f.seek(curPos + 4)\n                else:\n                    self.f.seek(offset)\n                    self.fixOffsets(count, isShort=(fieldSize == 2),\n                                    isLong=(fieldSize == 4))\n                    self.f.seek(curPos)\n\n                offset = curPos = None\n\n            elif isLocal:\n                # skip the locally stored value that is not an offset\n                self.f.seek(4, os.SEEK_CUR)\n\n    def fixOffsets(self, count, isShort=False, isLong=False):\n        if not isShort and not isLong:\n            raise RuntimeError(\"offset is neither short nor long\")\n\n        for i in range(count):\n            offset = self.readShort() if isShort else self.readLong()\n            offset += self.offsetOfNewPage\n            if isShort and offset >= 65536:\n                # offset is now too large - we must convert shorts to longs\n                if count != 1:\n                    raise RuntimeError(\"not implemented\")  # XXX TODO\n\n                # simple case - the offset is just one and therefore it is\n                # local (not referenced with another offset)\n                self.rewriteLastShortToLong(offset)\n                self.f.seek(-10, os.SEEK_CUR)\n                self.writeShort(4)  # rewrite the type to LONG\n                self.f.seek(8, os.SEEK_CUR)\n            elif isShort:\n                self.rewriteLastShort(offset)\n            else:\n                self.rewriteLastLong(offset)\n\ndef _save_all(im, fp, filename):\n    if not hasattr(im, \"n_frames\"):\n        return _save(im, fp, filename)\n\n    cur_idx = im.tell()\n    try:\n        with AppendingTiffWriter(fp) as tf:\n            for idx in range(im.n_frames):\n                im.seek(idx)\n                im.load()\n                _save(im, tf, filename)\n                tf.newFrame()\n    finally:\n        im.seek(cur_idx)\n\n#\n# --------------------------------------------------------------------\n# Register\n\nImage.register_open(TiffImageFile.format, TiffImageFile, _accept)\nImage.register_save(TiffImageFile.format, _save)\nImage.register_save_all(TiffImageFile.format, _save_all)\n\nImage.register_extension(TiffImageFile.format, \".tif\")\nImage.register_extension(TiffImageFile.format, \".tiff\")\n\nImage.register_mime(TiffImageFile.format, \"image/tiff\")\n",
            "new_file_content": "#\n# The Python Imaging Library.\n# $Id$\n#\n# TIFF file handling\n#\n# TIFF is a flexible, if somewhat aged, image file format originally\n# defined by Aldus.  Although TIFF supports a wide variety of pixel\n# layouts and compression methods, the name doesn't really stand for\n# \"thousands of incompatible file formats,\" it just feels that way.\n#\n# To read TIFF data from a stream, the stream must be seekable.  For\n# progressive decoding, make sure to use TIFF files where the tag\n# directory is placed first in the file.\n#\n# History:\n# 1995-09-01 fl   Created\n# 1996-05-04 fl   Handle JPEGTABLES tag\n# 1996-05-18 fl   Fixed COLORMAP support\n# 1997-01-05 fl   Fixed PREDICTOR support\n# 1997-08-27 fl   Added support for rational tags (from Perry Stoll)\n# 1998-01-10 fl   Fixed seek/tell (from Jan Blom)\n# 1998-07-15 fl   Use private names for internal variables\n# 1999-06-13 fl   Rewritten for PIL 1.0 (1.0)\n# 2000-10-11 fl   Additional fixes for Python 2.0 (1.1)\n# 2001-04-17 fl   Fixed rewind support (seek to frame 0) (1.2)\n# 2001-05-12 fl   Added write support for more tags (from Greg Couch) (1.3)\n# 2001-12-18 fl   Added workaround for broken Matrox library\n# 2002-01-18 fl   Don't mess up if photometric tag is missing (D. Alan Stewart)\n# 2003-05-19 fl   Check FILLORDER tag\n# 2003-09-26 fl   Added RGBa support\n# 2004-02-24 fl   Added DPI support; fixed rational write support\n# 2005-02-07 fl   Added workaround for broken Corel Draw 10 files\n# 2006-01-09 fl   Added support for float/double tags (from Russell Nelson)\n#\n# Copyright (c) 1997-2006 by Secret Labs AB.  All rights reserved.\n# Copyright (c) 1995-1997 by Fredrik Lundh\n#\n# See the README file for information on usage and redistribution.\n#\n\nfrom __future__ import division, print_function\n\nfrom . import Image, ImageFile, ImagePalette, TiffTags\nfrom ._binary import i8, o8\n\nimport collections\nfrom fractions import Fraction\nfrom numbers import Number, Rational\n\nimport io\nimport itertools\nimport os\nimport struct\nimport sys\nimport warnings\n\nfrom .TiffTags import TYPES\n\n\n__version__ = \"1.3.5\"\nDEBUG = False  # Needs to be merged with the new logging approach.\n\n# Set these to true to force use of libtiff for reading or writing.\nREAD_LIBTIFF = False\nWRITE_LIBTIFF = False\nIFD_LEGACY_API = True\n\nII = b\"II\"  # little-endian (Intel style)\nMM = b\"MM\"  # big-endian (Motorola style)\n\n#\n# --------------------------------------------------------------------\n# Read TIFF files\n\n# a few tag names, just to make the code below a bit more readable\nIMAGEWIDTH = 256\nIMAGELENGTH = 257\nBITSPERSAMPLE = 258\nCOMPRESSION = 259\nPHOTOMETRIC_INTERPRETATION = 262\nFILLORDER = 266\nIMAGEDESCRIPTION = 270\nSTRIPOFFSETS = 273\nSAMPLESPERPIXEL = 277\nROWSPERSTRIP = 278\nSTRIPBYTECOUNTS = 279\nX_RESOLUTION = 282\nY_RESOLUTION = 283\nPLANAR_CONFIGURATION = 284\nRESOLUTION_UNIT = 296\nSOFTWARE = 305\nDATE_TIME = 306\nARTIST = 315\nPREDICTOR = 317\nCOLORMAP = 320\nTILEOFFSETS = 324\nEXTRASAMPLES = 338\nSAMPLEFORMAT = 339\nJPEGTABLES = 347\nCOPYRIGHT = 33432\nIPTC_NAA_CHUNK = 33723  # newsphoto properties\nPHOTOSHOP_CHUNK = 34377  # photoshop properties\nICCPROFILE = 34675\nEXIFIFD = 34665\nXMP = 700\n\n# https://github.com/imagej/ImageJA/blob/master/src/main/java/ij/io/TiffDecoder.java\nIMAGEJ_META_DATA_BYTE_COUNTS = 50838\nIMAGEJ_META_DATA = 50839\n\nCOMPRESSION_INFO = {\n    # Compression => pil compression name\n    1: \"raw\",\n    2: \"tiff_ccitt\",\n    3: \"group3\",\n    4: \"group4\",\n    5: \"tiff_lzw\",\n    6: \"tiff_jpeg\",  # obsolete\n    7: \"jpeg\",\n    8: \"tiff_adobe_deflate\",\n    32771: \"tiff_raw_16\",  # 16-bit padding\n    32773: \"packbits\",\n    32809: \"tiff_thunderscan\",\n    32946: \"tiff_deflate\",\n    34676: \"tiff_sgilog\",\n    34677: \"tiff_sgilog24\",\n}\n\nCOMPRESSION_INFO_REV = {v: k for k, v in COMPRESSION_INFO.items()}\n\nOPEN_INFO = {\n    # (ByteOrder, PhotoInterpretation, SampleFormat, FillOrder, BitsPerSample,\n    #  ExtraSamples) => mode, rawmode\n    (II, 0, (1,), 1, (1,), ()): (\"1\", \"1;I\"),\n    (MM, 0, (1,), 1, (1,), ()): (\"1\", \"1;I\"),\n    (II, 0, (1,), 2, (1,), ()): (\"1\", \"1;IR\"),\n    (MM, 0, (1,), 2, (1,), ()): (\"1\", \"1;IR\"),\n    (II, 1, (1,), 1, (1,), ()): (\"1\", \"1\"),\n    (MM, 1, (1,), 1, (1,), ()): (\"1\", \"1\"),\n    (II, 1, (1,), 2, (1,), ()): (\"1\", \"1;R\"),\n    (MM, 1, (1,), 2, (1,), ()): (\"1\", \"1;R\"),\n\n    (II, 0, (1,), 1, (2,), ()): (\"L\", \"L;2I\"),\n    (MM, 0, (1,), 1, (2,), ()): (\"L\", \"L;2I\"),\n    (II, 0, (1,), 2, (2,), ()): (\"L\", \"L;2IR\"),\n    (MM, 0, (1,), 2, (2,), ()): (\"L\", \"L;2IR\"),\n    (II, 1, (1,), 1, (2,), ()): (\"L\", \"L;2\"),\n    (MM, 1, (1,), 1, (2,), ()): (\"L\", \"L;2\"),\n    (II, 1, (1,), 2, (2,), ()): (\"L\", \"L;2R\"),\n    (MM, 1, (1,), 2, (2,), ()): (\"L\", \"L;2R\"),\n\n    (II, 0, (1,), 1, (4,), ()): (\"L\", \"L;4I\"),\n    (MM, 0, (1,), 1, (4,), ()): (\"L\", \"L;4I\"),\n    (II, 0, (1,), 2, (4,), ()): (\"L\", \"L;4IR\"),\n    (MM, 0, (1,), 2, (4,), ()): (\"L\", \"L;4IR\"),\n    (II, 1, (1,), 1, (4,), ()): (\"L\", \"L;4\"),\n    (MM, 1, (1,), 1, (4,), ()): (\"L\", \"L;4\"),\n    (II, 1, (1,), 2, (4,), ()): (\"L\", \"L;4R\"),\n    (MM, 1, (1,), 2, (4,), ()): (\"L\", \"L;4R\"),\n\n    (II, 0, (1,), 1, (8,), ()): (\"L\", \"L;I\"),\n    (MM, 0, (1,), 1, (8,), ()): (\"L\", \"L;I\"),\n    (II, 0, (1,), 2, (8,), ()): (\"L\", \"L;IR\"),\n    (MM, 0, (1,), 2, (8,), ()): (\"L\", \"L;IR\"),\n    (II, 1, (1,), 1, (8,), ()): (\"L\", \"L\"),\n    (MM, 1, (1,), 1, (8,), ()): (\"L\", \"L\"),\n    (II, 1, (1,), 2, (8,), ()): (\"L\", \"L;R\"),\n    (MM, 1, (1,), 2, (8,), ()): (\"L\", \"L;R\"),\n\n    (II, 1, (1,), 1, (12,), ()): (\"I;16\", \"I;12\"),\n\n    (II, 1, (1,), 1, (16,), ()): (\"I;16\", \"I;16\"),\n    (MM, 1, (1,), 1, (16,), ()): (\"I;16B\", \"I;16B\"),\n    (II, 1, (2,), 1, (16,), ()): (\"I;16S\", \"I;16S\"),\n    (MM, 1, (2,), 1, (16,), ()): (\"I;16BS\", \"I;16BS\"),\n\n    (II, 0, (3,), 1, (32,), ()): (\"F\", \"F;32F\"),\n    (MM, 0, (3,), 1, (32,), ()): (\"F\", \"F;32BF\"),\n    (II, 1, (1,), 1, (32,), ()): (\"I\", \"I;32N\"),\n    (II, 1, (2,), 1, (32,), ()): (\"I\", \"I;32S\"),\n    (MM, 1, (2,), 1, (32,), ()): (\"I;32BS\", \"I;32BS\"),\n    (II, 1, (3,), 1, (32,), ()): (\"F\", \"F;32F\"),\n    (MM, 1, (3,), 1, (32,), ()): (\"F\", \"F;32BF\"),\n\n    (II, 1, (1,), 1, (8, 8), (2,)): (\"LA\", \"LA\"),\n    (MM, 1, (1,), 1, (8, 8), (2,)): (\"LA\", \"LA\"),\n\n    (II, 2, (1,), 1, (8, 8, 8), ()): (\"RGB\", \"RGB\"),\n    (MM, 2, (1,), 1, (8, 8, 8), ()): (\"RGB\", \"RGB\"),\n    (II, 2, (1,), 2, (8, 8, 8), ()): (\"RGB\", \"RGB;R\"),\n    (MM, 2, (1,), 2, (8, 8, 8), ()): (\"RGB\", \"RGB;R\"),\n    (II, 2, (1,), 1, (8, 8, 8, 8), ()): (\"RGBA\", \"RGBA\"),  # missing ExtraSamples\n    (MM, 2, (1,), 1, (8, 8, 8, 8), ()): (\"RGBA\", \"RGBA\"),  # missing ExtraSamples\n    (II, 2, (1,), 1, (8, 8, 8, 8), (0,)): (\"RGBX\", \"RGBX\"),\n    (MM, 2, (1,), 1, (8, 8, 8, 8), (0,)): (\"RGBX\", \"RGBX\"),\n    (II, 2, (1,), 1, (8, 8, 8, 8), (1,)): (\"RGBA\", \"RGBa\"),\n    (MM, 2, (1,), 1, (8, 8, 8, 8), (1,)): (\"RGBA\", \"RGBa\"),\n    (II, 2, (1,), 1, (8, 8, 8, 8), (2,)): (\"RGBA\", \"RGBA\"),\n    (MM, 2, (1,), 1, (8, 8, 8, 8), (2,)): (\"RGBA\", \"RGBA\"),\n    (II, 2, (1,), 1, (8, 8, 8, 8), (999,)): (\"RGBA\", \"RGBA\"),  # Corel Draw 10\n    (MM, 2, (1,), 1, (8, 8, 8, 8), (999,)): (\"RGBA\", \"RGBA\"),  # Corel Draw 10\n\n    (II, 3, (1,), 1, (1,), ()): (\"P\", \"P;1\"),\n    (MM, 3, (1,), 1, (1,), ()): (\"P\", \"P;1\"),\n    (II, 3, (1,), 2, (1,), ()): (\"P\", \"P;1R\"),\n    (MM, 3, (1,), 2, (1,), ()): (\"P\", \"P;1R\"),\n    (II, 3, (1,), 1, (2,), ()): (\"P\", \"P;2\"),\n    (MM, 3, (1,), 1, (2,), ()): (\"P\", \"P;2\"),\n    (II, 3, (1,), 2, (2,), ()): (\"P\", \"P;2R\"),\n    (MM, 3, (1,), 2, (2,), ()): (\"P\", \"P;2R\"),\n    (II, 3, (1,), 1, (4,), ()): (\"P\", \"P;4\"),\n    (MM, 3, (1,), 1, (4,), ()): (\"P\", \"P;4\"),\n    (II, 3, (1,), 2, (4,), ()): (\"P\", \"P;4R\"),\n    (MM, 3, (1,), 2, (4,), ()): (\"P\", \"P;4R\"),\n    (II, 3, (1,), 1, (8,), ()): (\"P\", \"P\"),\n    (MM, 3, (1,), 1, (8,), ()): (\"P\", \"P\"),\n    (II, 3, (1,), 1, (8, 8), (2,)): (\"PA\", \"PA\"),\n    (MM, 3, (1,), 1, (8, 8), (2,)): (\"PA\", \"PA\"),\n    (II, 3, (1,), 2, (8,), ()): (\"P\", \"P;R\"),\n    (MM, 3, (1,), 2, (8,), ()): (\"P\", \"P;R\"),\n\n    (II, 5, (1,), 1, (8, 8, 8, 8), ()): (\"CMYK\", \"CMYK\"),\n    (MM, 5, (1,), 1, (8, 8, 8, 8), ()): (\"CMYK\", \"CMYK\"),\n\n    (II, 6, (1,), 1, (8, 8, 8), ()): (\"YCbCr\", \"YCbCr\"),\n    (MM, 6, (1,), 1, (8, 8, 8), ()): (\"YCbCr\", \"YCbCr\"),\n\n    (II, 8, (1,), 1, (8, 8, 8), ()): (\"LAB\", \"LAB\"),\n    (MM, 8, (1,), 1, (8, 8, 8), ()): (\"LAB\", \"LAB\"),\n}\n\nPREFIXES = [b\"MM\\000\\052\", b\"II\\052\\000\", b\"II\\xBC\\000\"]\n\n\ndef _accept(prefix):\n    return prefix[:4] in PREFIXES\n\n\ndef _limit_rational(val, max_val):\n    inv = abs(val) > 1\n    n_d = IFDRational(1 / val if inv else val).limit_rational(max_val)\n    return n_d[::-1] if inv else n_d\n\n##\n# Wrapper for TIFF IFDs.\n\n_load_dispatch = {}\n_write_dispatch = {}\n\n\nclass IFDRational(Rational):\n    \"\"\" Implements a rational class where 0/0 is a legal value to match\n    the in the wild use of exif rationals.\n\n    e.g., DigitalZoomRatio - 0.00/0.00  indicates that no digital zoom was used\n    \"\"\"\n\n    \"\"\" If the denominator is 0, store this as a float('nan'), otherwise store\n    as a fractions.Fraction(). Delegate as appropriate\n\n    \"\"\"\n\n    __slots__ = ('_numerator', '_denominator', '_val')\n\n    def __init__(self, value, denominator=1):\n        \"\"\"\n        :param value: either an integer numerator, a\n        float/rational/other number, or an IFDRational\n        :param denominator: Optional integer denominator\n        \"\"\"\n        self._denominator = denominator\n        self._numerator = value\n        self._val = float(1)\n\n        if isinstance(value, Fraction):\n            self._numerator = value.numerator\n            self._denominator = value.denominator\n            self._val = value\n\n        if isinstance(value, IFDRational):\n            self._denominator = value.denominator\n            self._numerator = value.numerator\n            self._val = value._val\n            return\n\n        if denominator == 0:\n            self._val = float('nan')\n            return\n\n        elif denominator == 1:\n            self._val = Fraction(value)\n        else:\n            self._val = Fraction(value, denominator)\n\n    @property\n    def numerator(a):\n        return a._numerator\n\n    @property\n    def denominator(a):\n        return a._denominator\n\n    def limit_rational(self, max_denominator):\n        \"\"\"\n\n        :param max_denominator: Integer, the maximum denominator value\n        :returns: Tuple of (numerator, denominator)\n        \"\"\"\n\n        if self.denominator == 0:\n            return (self.numerator, self.denominator)\n\n        f = self._val.limit_denominator(max_denominator)\n        return (f.numerator, f.denominator)\n\n    def __repr__(self):\n        return str(float(self._val))\n\n    def __hash__(self):\n        return self._val.__hash__()\n\n    def __eq__(self, other):\n        return self._val == other\n\n    def _delegate(op):\n        def delegate(self, *args):\n            return getattr(self._val, op)(*args)\n        return delegate\n\n    \"\"\" a = ['add','radd', 'sub', 'rsub','div', 'rdiv', 'mul', 'rmul',\n             'truediv', 'rtruediv', 'floordiv',\n             'rfloordiv','mod','rmod', 'pow','rpow', 'pos', 'neg',\n             'abs', 'trunc', 'lt', 'gt', 'le', 'ge', 'nonzero',\n             'ceil', 'floor', 'round']\n        print(\"\\n\".join(\"__%s__ = _delegate('__%s__')\" % (s,s) for s in a))\n        \"\"\"\n\n    __add__ = _delegate('__add__')\n    __radd__ = _delegate('__radd__')\n    __sub__ = _delegate('__sub__')\n    __rsub__ = _delegate('__rsub__')\n    __div__ = _delegate('__div__')\n    __rdiv__ = _delegate('__rdiv__')\n    __mul__ = _delegate('__mul__')\n    __rmul__ = _delegate('__rmul__')\n    __truediv__ = _delegate('__truediv__')\n    __rtruediv__ = _delegate('__rtruediv__')\n    __floordiv__ = _delegate('__floordiv__')\n    __rfloordiv__ = _delegate('__rfloordiv__')\n    __mod__ = _delegate('__mod__')\n    __rmod__ = _delegate('__rmod__')\n    __pow__ = _delegate('__pow__')\n    __rpow__ = _delegate('__rpow__')\n    __pos__ = _delegate('__pos__')\n    __neg__ = _delegate('__neg__')\n    __abs__ = _delegate('__abs__')\n    __trunc__ = _delegate('__trunc__')\n    __lt__ = _delegate('__lt__')\n    __gt__ = _delegate('__gt__')\n    __le__ = _delegate('__le__')\n    __ge__ = _delegate('__ge__')\n    __nonzero__ = _delegate('__nonzero__')\n    __ceil__ = _delegate('__ceil__')\n    __floor__ = _delegate('__floor__')\n    __round__ = _delegate('__round__')\n\n\nclass ImageFileDirectory_v2(collections.MutableMapping):\n    \"\"\"This class represents a TIFF tag directory.  To speed things up, we\n    don't decode tags unless they're asked for.\n\n    Exposes a dictionary interface of the tags in the directory::\n\n        ifd = ImageFileDirectory_v2()\n        ifd[key] = 'Some Data'\n        ifd.tagtype[key] = 2\n        print(ifd[key])\n        'Some Data'\n\n    Individual values are returned as the strings or numbers, sequences are\n    returned as tuples of the values.\n\n    The tiff metadata type of each item is stored in a dictionary of\n    tag types in\n    `~PIL.TiffImagePlugin.ImageFileDirectory_v2.tagtype`. The types\n    are read from a tiff file, guessed from the type added, or added\n    manually.\n\n    Data Structures:\n\n        * self.tagtype = {}\n\n          * Key: numerical tiff tag number\n          * Value: integer corresponding to the data type from `~PIL.TiffTags.TYPES`\n\n    .. versionadded:: 3.0.0\n    \"\"\"\n    \"\"\"\n    Documentation:\n\n        'internal' data structures:\n        * self._tags_v2 = {} Key: numerical tiff tag number\n                             Value: decoded data, as tuple for multiple values\n        * self._tagdata = {} Key: numerical tiff tag number\n                             Value: undecoded byte string from file\n        * self._tags_v1 = {} Key: numerical tiff tag number\n                             Value: decoded data in the v1 format\n\n    Tags will be found in the private attributes self._tagdata, and in\n    self._tags_v2 once decoded.\n\n    Self.legacy_api is a value for internal use, and shouldn't be\n    changed from outside code. In cooperation with the\n    ImageFileDirectory_v1 class, if legacy_api is true, then decoded\n    tags will be populated into both _tags_v1 and _tags_v2. _Tags_v2\n    will be used if this IFD is used in the TIFF save routine. Tags\n    should be read from tags_v1 if legacy_api == true.\n\n    \"\"\"\n\n    def __init__(self, ifh=b\"II\\052\\0\\0\\0\\0\\0\", prefix=None):\n        \"\"\"Initialize an ImageFileDirectory.\n\n        To construct an ImageFileDirectory from a real file, pass the 8-byte\n        magic header to the constructor.  To only set the endianness, pass it\n        as the 'prefix' keyword argument.\n\n        :param ifh: One of the accepted magic headers (cf. PREFIXES); also sets\n              endianness.\n        :param prefix: Override the endianness of the file.\n        \"\"\"\n        if ifh[:4] not in PREFIXES:\n            raise SyntaxError(\"not a TIFF file (header %r not valid)\" % ifh)\n        self._prefix = prefix if prefix is not None else ifh[:2]\n        if self._prefix == MM:\n            self._endian = \">\"\n        elif self._prefix == II:\n            self._endian = \"<\"\n        else:\n            raise SyntaxError(\"not a TIFF IFD\")\n        self.reset()\n        self.next, = self._unpack(\"L\", ifh[4:])\n        self._legacy_api = False\n\n    prefix = property(lambda self: self._prefix)\n    offset = property(lambda self: self._offset)\n    legacy_api = property(lambda self: self._legacy_api)\n\n    @legacy_api.setter\n    def legacy_api(self, value):\n        raise Exception(\"Not allowing setting of legacy api\")\n\n    def reset(self):\n        self._tags_v1 = {}  # will remain empty if legacy_api is false\n        self._tags_v2 = {}  # main tag storage\n        self._tagdata = {}\n        self.tagtype = {}   # added 2008-06-05 by Florian Hoech\n        self._next = None\n        self._offset = None\n\n    def __str__(self):\n        return str(dict(self))\n\n    def as_dict(self):\n        \"\"\"Return a dictionary of the image's tags.\n\n        .. deprecated:: 3.0.0\n        \"\"\"\n        warnings.warn(\"as_dict() is deprecated. \" +\n                      \"Please use dict(ifd) instead.\", DeprecationWarning)\n        return dict(self)\n\n    def named(self):\n        \"\"\"\n        :returns: dict of name|key: value\n\n        Returns the complete tag dictionary, with named tags where possible.\n        \"\"\"\n        return dict((TiffTags.lookup(code).name, value)\n                    for code, value in self.items())\n\n    def __len__(self):\n        return len(set(self._tagdata) | set(self._tags_v2))\n\n    def __getitem__(self, tag):\n        if tag not in self._tags_v2:  # unpack on the fly\n            data = self._tagdata[tag]\n            typ = self.tagtype[tag]\n            size, handler = self._load_dispatch[typ]\n            self[tag] = handler(self, data, self.legacy_api)  # check type\n        val = self._tags_v2[tag]\n        if self.legacy_api and not isinstance(val, (tuple, bytes)):\n            val = val,\n        return val\n\n    def __contains__(self, tag):\n        return tag in self._tags_v2 or tag in self._tagdata\n\n    if bytes is str:\n        def has_key(self, tag):\n            return tag in self\n\n    def __setitem__(self, tag, value):\n        self._setitem(tag, value, self.legacy_api)\n\n    def _setitem(self, tag, value, legacy_api):\n        basetypes = (Number, bytes, str)\n        if bytes is str:\n            basetypes += unicode,\n\n        info = TiffTags.lookup(tag)\n        values = [value] if isinstance(value, basetypes) else value\n\n        if tag not in self.tagtype:\n            if info.type:\n                self.tagtype[tag] = info.type\n            else:\n                self.tagtype[tag] = 7\n                if all(isinstance(v, IFDRational) for v in values):\n                    self.tagtype[tag] = 5\n                elif all(isinstance(v, int) for v in values):\n                    if all(v < 2 ** 16 for v in values):\n                        self.tagtype[tag] = 3\n                    else:\n                        self.tagtype[tag] = 4\n                elif all(isinstance(v, float) for v in values):\n                    self.tagtype[tag] = 12\n                else:\n                    if bytes is str:\n                        # Never treat data as binary by default on Python 2.\n                        self.tagtype[tag] = 2\n                    else:\n                        if all(isinstance(v, str) for v in values):\n                            self.tagtype[tag] = 2\n\n        if self.tagtype[tag] == 7 and bytes is not str:\n            values = [value.encode(\"ascii\", 'replace') if isinstance(value, str) else value]\n\n        values = tuple(info.cvt_enum(value) for value in values)\n\n        dest = self._tags_v1 if legacy_api else self._tags_v2\n\n        if info.length == 1:\n            if legacy_api and self.tagtype[tag] in [5, 10]:\n                values = values,\n            dest[tag], = values\n        else:\n            dest[tag] = values\n\n    def __delitem__(self, tag):\n        self._tags_v2.pop(tag, None)\n        self._tags_v1.pop(tag, None)\n        self._tagdata.pop(tag, None)\n\n    def __iter__(self):\n        return iter(set(self._tagdata) | set(self._tags_v2))\n\n    def _unpack(self, fmt, data):\n        return struct.unpack(self._endian + fmt, data)\n\n    def _pack(self, fmt, *values):\n        return struct.pack(self._endian + fmt, *values)\n\n    def _register_loader(idx, size):\n        def decorator(func):\n            from .TiffTags import TYPES\n            if func.__name__.startswith(\"load_\"):\n                TYPES[idx] = func.__name__[5:].replace(\"_\", \" \")\n            _load_dispatch[idx] = size, func\n            return func\n        return decorator\n\n    def _register_writer(idx):\n        def decorator(func):\n            _write_dispatch[idx] = func\n            return func\n        return decorator\n\n    def _register_basic(idx_fmt_name):\n        from .TiffTags import TYPES\n        idx, fmt, name = idx_fmt_name\n        TYPES[idx] = name\n        size = struct.calcsize(\"=\" + fmt)\n        _load_dispatch[idx] = size, lambda self, data, legacy_api=True: (\n            self._unpack(\"{}{}\".format(len(data) // size, fmt), data))\n        _write_dispatch[idx] = lambda self, *values: (\n            b\"\".join(self._pack(fmt, value) for value in values))\n\n    list(map(_register_basic,\n             [(3, \"H\", \"short\"), (4, \"L\", \"long\"),\n              (6, \"b\", \"signed byte\"), (8, \"h\", \"signed short\"),\n              (9, \"l\", \"signed long\"), (11, \"f\", \"float\"), (12, \"d\", \"double\")]))\n\n    @_register_loader(1, 1)  # Basic type, except for the legacy API.\n    def load_byte(self, data, legacy_api=True):\n        return data\n\n    @_register_writer(1)  # Basic type, except for the legacy API.\n    def write_byte(self, data):\n        return data\n\n    @_register_loader(2, 1)\n    def load_string(self, data, legacy_api=True):\n        if data.endswith(b\"\\0\"):\n            data = data[:-1]\n        return data.decode(\"latin-1\", \"replace\")\n\n    @_register_writer(2)\n    def write_string(self, value):\n        # remerge of https://github.com/python-pillow/Pillow/pull/1416\n        if sys.version_info[0] == 2:\n            value = value.decode('ascii', 'replace')\n        return b\"\" + value.encode('ascii', 'replace') + b\"\\0\"\n\n    @_register_loader(5, 8)\n    def load_rational(self, data, legacy_api=True):\n        vals = self._unpack(\"{}L\".format(len(data) // 4), data)\n        combine = lambda a, b: (a, b) if legacy_api else IFDRational(a, b)\n        return tuple(combine(num, denom)\n                     for num, denom in zip(vals[::2], vals[1::2]))\n\n    @_register_writer(5)\n    def write_rational(self, *values):\n        return b\"\".join(self._pack(\"2L\", *_limit_rational(frac, 2 ** 31))\n                        for frac in values)\n\n    @_register_loader(7, 1)\n    def load_undefined(self, data, legacy_api=True):\n        return data\n\n    @_register_writer(7)\n    def write_undefined(self, value):\n        return value\n\n    @_register_loader(10, 8)\n    def load_signed_rational(self, data, legacy_api=True):\n        vals = self._unpack(\"{}l\".format(len(data) // 4), data)\n        combine = lambda a, b: (a, b) if legacy_api else IFDRational(a, b)\n        return tuple(combine(num, denom)\n                     for num, denom in zip(vals[::2], vals[1::2]))\n\n    @_register_writer(10)\n    def write_signed_rational(self, *values):\n        return b\"\".join(self._pack(\"2L\", *_limit_rational(frac, 2 ** 30))\n                        for frac in values)\n\n    def _ensure_read(self, fp, size):\n        ret = fp.read(size)\n        if len(ret) != size:\n            raise IOError(\"Corrupt EXIF data.  \" +\n                          \"Expecting to read %d bytes but only got %d. \" %\n                          (size, len(ret)))\n        return ret\n\n    def load(self, fp):\n\n        self.reset()\n        self._offset = fp.tell()\n\n        try:\n            for i in range(self._unpack(\"H\", self._ensure_read(fp, 2))[0]):\n                tag, typ, count, data = self._unpack(\"HHL4s\", self._ensure_read(fp, 12))\n                if DEBUG:\n                    tagname = TiffTags.lookup(tag).name\n                    typname = TYPES.get(typ, \"unknown\")\n                    print(\"tag: %s (%d) - type: %s (%d)\" %\n                          (tagname, tag, typname, typ), end=\" \")\n\n                try:\n                    unit_size, handler = self._load_dispatch[typ]\n                except KeyError:\n                    if DEBUG:\n                        print(\"- unsupported type\", typ)\n                    continue  # ignore unsupported type\n                size = count * unit_size\n                if size > 4:\n                    here = fp.tell()\n                    offset, = self._unpack(\"L\", data)\n                    if DEBUG:\n                        print(\"Tag Location: %s - Data Location: %s\" %\n                              (here, offset), end=\" \")\n                    fp.seek(offset)\n                    data = ImageFile._safe_read(fp, size)\n                    fp.seek(here)\n                else:\n                    data = data[:size]\n\n                if len(data) != size:\n                    warnings.warn(\"Possibly corrupt EXIF data.  \"\n                                  \"Expecting to read %d bytes but only got %d. \"\n                                  \"Skipping tag %s\" % (size, len(data), tag))\n                    continue\n\n                if not data:\n                    continue\n\n                self._tagdata[tag] = data\n                self.tagtype[tag] = typ\n\n                if DEBUG:\n                    if size > 32:\n                        print(\"- value: <table: %d bytes>\" % size)\n                    else:\n                        print(\"- value:\", self[tag])\n\n            self.next, = self._unpack(\"L\", self._ensure_read(fp, 4))\n        except IOError as msg:\n            warnings.warn(str(msg))\n            return\n\n    def save(self, fp):\n\n        if fp.tell() == 0:  # skip TIFF header on subsequent pages\n            # tiff header -- PIL always starts the first IFD at offset 8\n            fp.write(self._prefix + self._pack(\"HL\", 42, 8))\n\n        # FIXME What about tagdata?\n        fp.write(self._pack(\"H\", len(self._tags_v2)))\n\n        entries = []\n        offset = fp.tell() + len(self._tags_v2) * 12 + 4\n        stripoffsets = None\n\n        # pass 1: convert tags to binary format\n        # always write tags in ascending order\n        for tag, value in sorted(self._tags_v2.items()):\n            if tag == STRIPOFFSETS:\n                stripoffsets = len(entries)\n            typ = self.tagtype.get(tag)\n            if DEBUG:\n                print(\"Tag %s, Type: %s, Value: %s\" % (tag, typ, value))\n            values = value if isinstance(value, tuple) else (value,)\n            data = self._write_dispatch[typ](self, *values)\n            if DEBUG:\n                tagname = TiffTags.lookup(tag).name\n                typname = TYPES.get(typ, \"unknown\")\n                print(\"save: %s (%d) - type: %s (%d)\" %\n                      (tagname, tag, typname, typ), end=\" \")\n                if len(data) >= 16:\n                    print(\"- value: <table: %d bytes>\" % len(data))\n                else:\n                    print(\"- value:\", values)\n\n            # count is sum of lengths for string and arbitrary data\n            count = len(data) if typ in [2, 7] else len(values)\n            # figure out if data fits into the entry\n            if len(data) <= 4:\n                entries.append((tag, typ, count, data.ljust(4, b\"\\0\"), b\"\"))\n            else:\n                entries.append((tag, typ, count, self._pack(\"L\", offset), data))\n                offset += (len(data) + 1) // 2 * 2  # pad to word\n\n        # update strip offset data to point beyond auxiliary data\n        if stripoffsets is not None:\n            tag, typ, count, value, data = entries[stripoffsets]\n            if data:\n                raise NotImplementedError(\n                    \"multistrip support not yet implemented\")\n            value = self._pack(\"L\", self._unpack(\"L\", value)[0] + offset)\n            entries[stripoffsets] = tag, typ, count, value, data\n\n        # pass 2: write entries to file\n        for tag, typ, count, value, data in entries:\n            if DEBUG > 1:\n                print(tag, typ, count, repr(value), repr(data))\n            fp.write(self._pack(\"HHL4s\", tag, typ, count, value))\n\n        # -- overwrite here for multi-page --\n        fp.write(b\"\\0\\0\\0\\0\")  # end of entries\n\n        # pass 3: write auxiliary data to file\n        for tag, typ, count, value, data in entries:\n            fp.write(data)\n            if len(data) & 1:\n                fp.write(b\"\\0\")\n\n        return offset\n\nImageFileDirectory_v2._load_dispatch = _load_dispatch\nImageFileDirectory_v2._write_dispatch = _write_dispatch\nfor idx, name in TYPES.items():\n    name = name.replace(\" \", \"_\")\n    setattr(ImageFileDirectory_v2, \"load_\" + name, _load_dispatch[idx][1])\n    setattr(ImageFileDirectory_v2, \"write_\" + name, _write_dispatch[idx])\ndel _load_dispatch, _write_dispatch, idx, name\n\n\n# Legacy ImageFileDirectory support.\nclass ImageFileDirectory_v1(ImageFileDirectory_v2):\n    \"\"\"This class represents the **legacy** interface to a TIFF tag directory.\n\n    Exposes a dictionary interface of the tags in the directory::\n\n        ifd = ImageFileDirectory_v1()\n        ifd[key] = 'Some Data'\n        ifd.tagtype[key] = 2\n        print(ifd[key])\n        ('Some Data',)\n\n    Also contains a dictionary of tag types as read from the tiff image file,\n    `~PIL.TiffImagePlugin.ImageFileDirectory_v1.tagtype`.\n\n    Values are returned as a tuple.\n\n    ..  deprecated:: 3.0.0\n    \"\"\"\n    def __init__(self, *args, **kwargs):\n        ImageFileDirectory_v2.__init__(self, *args, **kwargs)\n        self._legacy_api = True\n\n    tags = property(lambda self: self._tags_v1)\n    tagdata = property(lambda self: self._tagdata)\n\n    @classmethod\n    def from_v2(cls, original):\n        \"\"\" Returns an\n        :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`\n        instance with the same data as is contained in the original\n        :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`\n        instance.\n\n        :returns: :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`\n\n        \"\"\"\n\n        ifd = cls(prefix=original.prefix)\n        ifd._tagdata = original._tagdata\n        ifd.tagtype = original.tagtype\n        ifd.next = original.next  # an indicator for multipage tiffs\n        return ifd\n\n    def to_v2(self):\n        \"\"\" Returns an\n        :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`\n        instance with the same data as is contained in the original\n        :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`\n        instance.\n\n        :returns: :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`\n\n        \"\"\"\n\n        ifd = ImageFileDirectory_v2(prefix=self.prefix)\n        ifd._tagdata = dict(self._tagdata)\n        ifd.tagtype = dict(self.tagtype)\n        ifd._tags_v2 = dict(self._tags_v2)\n        return ifd\n\n    def __contains__(self, tag):\n        return tag in self._tags_v1 or tag in self._tagdata\n\n    def __len__(self):\n        return len(set(self._tagdata) | set(self._tags_v1))\n\n    def __iter__(self):\n        return iter(set(self._tagdata) | set(self._tags_v1))\n\n    def __setitem__(self, tag, value):\n        for legacy_api in (False, True):\n            self._setitem(tag, value, legacy_api)\n\n    def __getitem__(self, tag):\n        if tag not in self._tags_v1:  # unpack on the fly\n            data = self._tagdata[tag]\n            typ = self.tagtype[tag]\n            size, handler = self._load_dispatch[typ]\n            for legacy in (False, True):\n                self._setitem(tag, handler(self, data, legacy), legacy)\n        val = self._tags_v1[tag]\n        if not isinstance(val, (tuple, bytes)):\n            val = val,\n        return val\n\n\n# undone -- switch this pointer when IFD_LEGACY_API == False\nImageFileDirectory = ImageFileDirectory_v1\n\n\n##\n# Image plugin for TIFF files.\n\nclass TiffImageFile(ImageFile.ImageFile):\n\n    format = \"TIFF\"\n    format_description = \"Adobe TIFF\"\n\n    def _open(self):\n        \"Open the first image in a TIFF file\"\n\n        # Header\n        ifh = self.fp.read(8)\n\n        # image file directory (tag dictionary)\n        self.tag_v2 = ImageFileDirectory_v2(ifh)\n\n        # legacy tag/ifd entries will be filled in later\n        self.tag = self.ifd = None\n\n        # setup frame pointers\n        self.__first = self.__next = self.tag_v2.next\n        self.__frame = -1\n        self.__fp = self.fp\n        self._frame_pos = []\n        self._n_frames = None\n        self._is_animated = None\n\n        if DEBUG:\n            print(\"*** TiffImageFile._open ***\")\n            print(\"- __first:\", self.__first)\n            print(\"- ifh: \", ifh)\n\n        # and load the first frame\n        self._seek(0)\n\n    @property\n    def n_frames(self):\n        if self._n_frames is None:\n            current = self.tell()\n            try:\n                while True:\n                    self._seek(self.tell() + 1)\n            except EOFError:\n                self._n_frames = self.tell() + 1\n            self.seek(current)\n        return self._n_frames\n\n    @property\n    def is_animated(self):\n        if self._is_animated is None:\n            current = self.tell()\n\n            try:\n                self.seek(1)\n                self._is_animated = True\n            except EOFError:\n                self._is_animated = False\n\n            self.seek(current)\n        return self._is_animated\n\n    def seek(self, frame):\n        \"Select a given frame as current image\"\n        self._seek(max(frame, 0))  # Questionable backwards compatibility.\n        # Create a new core image object on second and\n        # subsequent frames in the image. Image may be\n        # different size/mode.\n        Image._decompression_bomb_check(self.size)\n        self.im = Image.core.new(self.mode, self.size)\n\n    def _seek(self, frame):\n        self.fp = self.__fp\n        while len(self._frame_pos) <= frame:\n            if not self.__next:\n                raise EOFError(\"no more images in TIFF file\")\n            if DEBUG:\n                print(\"Seeking to frame %s, on frame %s, \"\n                      \"__next %s, location: %s\" %\n                      (frame, self.__frame, self.__next, self.fp.tell()))\n            # reset python3 buffered io handle in case fp\n            # was passed to libtiff, invalidating the buffer\n            self.fp.tell()\n            self.fp.seek(self.__next)\n            self._frame_pos.append(self.__next)\n            if DEBUG:\n                print(\"Loading tags, location: %s\" % self.fp.tell())\n            self.tag_v2.load(self.fp)\n            self.__next = self.tag_v2.next\n            self.__frame += 1\n        self.fp.seek(self._frame_pos[frame])\n        self.tag_v2.load(self.fp)\n        # fill the legacy tag/ifd entries\n        self.tag = self.ifd = ImageFileDirectory_v1.from_v2(self.tag_v2)\n        self.__frame = frame\n        self._setup()\n\n    def tell(self):\n        \"Return the current frame number\"\n        return self.__frame\n\n    def _decoder(self, rawmode, layer, tile=None):\n        \"Setup decoder contexts\"\n\n        args = None\n        if rawmode == \"RGB\" and self._planar_configuration == 2:\n            rawmode = rawmode[layer]\n        compression = self._compression\n        if compression == \"raw\":\n            args = (rawmode, 0, 1)\n        elif compression == \"jpeg\":\n            args = rawmode, \"\"\n            if JPEGTABLES in self.tag_v2:\n                # Hack to handle abbreviated JPEG headers\n                # FIXME This will fail with more than one value\n                self.tile_prefix, = self.tag_v2[JPEGTABLES]\n        elif compression == \"packbits\":\n            args = rawmode\n        elif compression == \"tiff_lzw\":\n            args = rawmode\n            if PREDICTOR in self.tag_v2:\n                # Section 14: Differencing Predictor\n                self.decoderconfig = (self.tag_v2[PREDICTOR],)\n\n        return args\n\n    def load(self):\n        if self.use_load_libtiff:\n            return self._load_libtiff()\n        return super(TiffImageFile, self).load()\n\n    def _load_libtiff(self):\n        \"\"\" Overload method triggered when we detect a compressed tiff\n            Calls out to libtiff \"\"\"\n\n        pixel = Image.Image.load(self)\n\n        if self.tile is None:\n            raise IOError(\"cannot load this image\")\n        if not self.tile:\n            return pixel\n\n        self.load_prepare()\n\n        if not len(self.tile) == 1:\n            raise IOError(\"Not exactly one tile\")\n\n        # (self._compression, (extents tuple),\n        #   0, (rawmode, self._compression, fp))\n        extents = self.tile[0][1]\n        args = list(self.tile[0][3]) + [self.tag_v2.offset]\n\n        # To be nice on memory footprint, if there's a\n        # file descriptor, use that instead of reading\n        # into a string in python.\n        # libtiff closes the file descriptor, so pass in a dup.\n        try:\n            fp = hasattr(self.fp, \"fileno\") and os.dup(self.fp.fileno())\n            # flush the file descriptor, prevents error on pypy 2.4+\n            # should also eliminate the need for fp.tell for py3\n            # in _seek\n            if hasattr(self.fp, \"flush\"):\n                self.fp.flush()\n        except IOError:\n            # io.BytesIO have a fileno, but returns an IOError if\n            # it doesn't use a file descriptor.\n            fp = False\n\n        if fp:\n            args[2] = fp\n\n        decoder = Image._getdecoder(self.mode, 'libtiff', tuple(args),\n                                    self.decoderconfig)\n        try:\n            decoder.setimage(self.im, extents)\n        except ValueError:\n            raise IOError(\"Couldn't set the image\")\n\n        if hasattr(self.fp, \"getvalue\"):\n            # We've got a stringio like thing passed in. Yay for all in memory.\n            # The decoder needs the entire file in one shot, so there's not\n            # a lot we can do here other than give it the entire file.\n            # unless we could do something like get the address of the\n            # underlying string for stringio.\n            #\n            # Rearranging for supporting byteio items, since they have a fileno\n            # that returns an IOError if there's no underlying fp. Easier to\n            # deal with here by reordering.\n            if DEBUG:\n                print(\"have getvalue. just sending in a string from getvalue\")\n            n, err = decoder.decode(self.fp.getvalue())\n        elif hasattr(self.fp, \"fileno\"):\n            # we've got a actual file on disk, pass in the fp.\n            if DEBUG:\n                print(\"have fileno, calling fileno version of the decoder.\")\n            self.fp.seek(0)\n            # 4 bytes, otherwise the trace might error out\n            n, err = decoder.decode(b\"fpfp\")\n        else:\n            # we have something else.\n            if DEBUG:\n                print(\"don't have fileno or getvalue. just reading\")\n            # UNDONE -- so much for that buffer size thing.\n            n, err = decoder.decode(self.fp.read())\n\n        self.tile = []\n        self.readonly = 0\n        # libtiff closed the fp in a, we need to close self.fp, if possible\n        if hasattr(self.fp, 'close'):\n            if not self.__next:\n                self.fp.close()\n        self.fp = None  # might be shared\n\n        if err < 0:\n            raise IOError(err)\n\n        self.load_end()\n\n        return Image.Image.load(self)\n\n    def _setup(self):\n        \"Setup this image object based on current tags\"\n\n        if 0xBC01 in self.tag_v2:\n            raise IOError(\"Windows Media Photo files not yet supported\")\n\n        # extract relevant tags\n        self._compression = COMPRESSION_INFO[self.tag_v2.get(COMPRESSION, 1)]\n        self._planar_configuration = self.tag_v2.get(PLANAR_CONFIGURATION, 1)\n\n        # photometric is a required tag, but not everyone is reading\n        # the specification\n        photo = self.tag_v2.get(PHOTOMETRIC_INTERPRETATION, 0)\n\n        fillorder = self.tag_v2.get(FILLORDER, 1)\n\n        if DEBUG:\n            print(\"*** Summary ***\")\n            print(\"- compression:\", self._compression)\n            print(\"- photometric_interpretation:\", photo)\n            print(\"- planar_configuration:\", self._planar_configuration)\n            print(\"- fill_order:\", fillorder)\n\n        # size\n        xsize = self.tag_v2.get(IMAGEWIDTH)\n        ysize = self.tag_v2.get(IMAGELENGTH)\n        self.size = xsize, ysize\n\n        if DEBUG:\n            print(\"- size:\", self.size)\n\n        sampleFormat = self.tag_v2.get(SAMPLEFORMAT, (1,))\n        if (len(sampleFormat) > 1\n            and max(sampleFormat) == min(sampleFormat) == 1):\n            # SAMPLEFORMAT is properly per band, so an RGB image will\n            # be (1,1,1).  But, we don't support per band pixel types,\n            # and anything more than one band is a uint8. So, just\n            # take the first element. Revisit this if adding support\n            # for more exotic images.\n            sampleFormat = (1,)\n\n        # mode: check photometric interpretation and bits per pixel\n        key = (\n            self.tag_v2.prefix, photo, sampleFormat, fillorder,\n            self.tag_v2.get(BITSPERSAMPLE, (1,)),\n            self.tag_v2.get(EXTRASAMPLES, ())\n            )\n        if DEBUG:\n            print(\"format key:\", key)\n        try:\n            self.mode, rawmode = OPEN_INFO[key]\n        except KeyError:\n            if DEBUG:\n                print(\"- unsupported format\")\n            raise SyntaxError(\"unknown pixel mode\")\n\n        if DEBUG:\n            print(\"- raw mode:\", rawmode)\n            print(\"- pil mode:\", self.mode)\n\n        self.info[\"compression\"] = self._compression\n\n        xres = self.tag_v2.get(X_RESOLUTION, 1)\n        yres = self.tag_v2.get(Y_RESOLUTION, 1)\n\n        if xres and yres:\n            resunit = self.tag_v2.get(RESOLUTION_UNIT)\n            if resunit == 2:  # dots per inch\n                self.info[\"dpi\"] = xres, yres\n            elif resunit == 3:  # dots per centimeter. convert to dpi\n                self.info[\"dpi\"] = xres * 2.54, yres * 2.54\n            elif resunit == None: # used to default to 1, but now 2)\n                self.info[\"dpi\"] = xres, yres\n                # For backward compatibility, we also preserve the old behavior.\n                self.info[\"resolution\"] = xres, yres\n            else:  # No absolute unit of measurement\n                self.info[\"resolution\"] = xres, yres\n\n        # build tile descriptors\n        x = y = l = 0\n        self.tile = []\n        self.use_load_libtiff = False\n        if STRIPOFFSETS in self.tag_v2:\n            # striped image\n            offsets = self.tag_v2[STRIPOFFSETS]\n            h = self.tag_v2.get(ROWSPERSTRIP, ysize)\n            w = self.size[0]\n            if READ_LIBTIFF or self._compression in [\"tiff_ccitt\", \"group3\",\n                                                     \"group4\", \"tiff_jpeg\",\n                                                     \"tiff_adobe_deflate\",\n                                                     \"tiff_thunderscan\",\n                                                     \"tiff_deflate\",\n                                                     \"tiff_sgilog\",\n                                                     \"tiff_sgilog24\",\n                                                     \"tiff_raw_16\"]:\n                # if DEBUG:\n                #     print(\"Activating g4 compression for whole file\")\n\n                # Decoder expects entire file as one tile.\n                # There's a buffer size limit in load (64k)\n                # so large g4 images will fail if we use that\n                # function.\n                #\n                # Setup the one tile for the whole image, then\n                # use the _load_libtiff function.\n\n                self.use_load_libtiff = True\n\n                # libtiff handles the fillmode for us, so 1;IR should\n                # actually be 1;I. Including the R double reverses the\n                # bits, so stripes of the image are reversed.  See\n                # https://github.com/python-pillow/Pillow/issues/279\n                if fillorder == 2:\n                    key = (\n                        self.tag_v2.prefix, photo, sampleFormat, 1,\n                        self.tag_v2.get(BITSPERSAMPLE, (1,)),\n                        self.tag_v2.get(EXTRASAMPLES, ())\n                        )\n                    if DEBUG:\n                        print(\"format key:\", key)\n                    # this should always work, since all the\n                    # fillorder==2 modes have a corresponding\n                    # fillorder=1 mode\n                    self.mode, rawmode = OPEN_INFO[key]\n                # libtiff always returns the bytes in native order.\n                # we're expecting image byte order. So, if the rawmode\n                # contains I;16, we need to convert from native to image\n                # byte order.\n                if self.mode in ('I;16B', 'I;16') and 'I;16' in rawmode:\n                    rawmode = 'I;16N'\n\n                # Offset in the tile tuple is 0, we go from 0,0 to\n                # w,h, and we only do this once -- eds\n                a = (rawmode, self._compression, False)\n                self.tile.append(\n                    (self._compression,\n                     (0, 0, w, ysize),\n                     0, a))\n                a = None\n\n            else:\n                for i, offset in enumerate(offsets):\n                    a = self._decoder(rawmode, l, i)\n                    self.tile.append(\n                        (self._compression,\n                            (0, min(y, ysize), w, min(y+h, ysize)),\n                            offset, a))\n                    if DEBUG:\n                        print(\"tiles: \", self.tile)\n                    y = y + h\n                    if y >= self.size[1]:\n                        x = y = 0\n                        l += 1\n                    a = None\n        elif TILEOFFSETS in self.tag_v2:\n            # tiled image\n            w = self.tag_v2.get(322)\n            h = self.tag_v2.get(323)\n            a = None\n            for o in self.tag_v2[TILEOFFSETS]:\n                if not a:\n                    a = self._decoder(rawmode, l)\n                # FIXME: this doesn't work if the image size\n                # is not a multiple of the tile size...\n                self.tile.append(\n                    (self._compression,\n                        (x, y, x+w, y+h),\n                        o, a))\n                x = x + w\n                if x >= self.size[0]:\n                    x, y = 0, y + h\n                    if y >= self.size[1]:\n                        x = y = 0\n                        l += 1\n                        a = None\n        else:\n            if DEBUG:\n                print(\"- unsupported data organization\")\n            raise SyntaxError(\"unknown data organization\")\n\n        # Fix up info.\n        if ICCPROFILE in self.tag_v2:\n            self.info['icc_profile'] = self.tag_v2[ICCPROFILE]\n\n        # fixup palette descriptor\n\n        if self.mode == \"P\":\n            palette = [o8(b // 256) for b in self.tag_v2[COLORMAP]]\n            self.palette = ImagePalette.raw(\"RGB;L\", b\"\".join(palette))\n#\n# --------------------------------------------------------------------\n# Write TIFF files\n\n# little endian is default except for image modes with\n# explicit big endian byte-order\n\nSAVE_INFO = {\n    # mode => rawmode, byteorder, photometrics,\n    #           sampleformat, bitspersample, extra\n    \"1\": (\"1\", II, 1, 1, (1,), None),\n    \"L\": (\"L\", II, 1, 1, (8,), None),\n    \"LA\": (\"LA\", II, 1, 1, (8, 8), 2),\n    \"P\": (\"P\", II, 3, 1, (8,), None),\n    \"PA\": (\"PA\", II, 3, 1, (8, 8), 2),\n    \"I\": (\"I;32S\", II, 1, 2, (32,), None),\n    \"I;16\": (\"I;16\", II, 1, 1, (16,), None),\n    \"I;16S\": (\"I;16S\", II, 1, 2, (16,), None),\n    \"F\": (\"F;32F\", II, 1, 3, (32,), None),\n    \"RGB\": (\"RGB\", II, 2, 1, (8, 8, 8), None),\n    \"RGBX\": (\"RGBX\", II, 2, 1, (8, 8, 8, 8), 0),\n    \"RGBA\": (\"RGBA\", II, 2, 1, (8, 8, 8, 8), 2),\n    \"CMYK\": (\"CMYK\", II, 5, 1, (8, 8, 8, 8), None),\n    \"YCbCr\": (\"YCbCr\", II, 6, 1, (8, 8, 8), None),\n    \"LAB\": (\"LAB\", II, 8, 1, (8, 8, 8), None),\n\n    \"I;32BS\": (\"I;32BS\", MM, 1, 2, (32,), None),\n    \"I;16B\": (\"I;16B\", MM, 1, 1, (16,), None),\n    \"I;16BS\": (\"I;16BS\", MM, 1, 2, (16,), None),\n    \"F;32BF\": (\"F;32BF\", MM, 1, 3, (32,), None),\n}\n\n\ndef _save(im, fp, filename):\n\n    try:\n        rawmode, prefix, photo, format, bits, extra = SAVE_INFO[im.mode]\n    except KeyError:\n        raise IOError(\"cannot write mode %s as TIFF\" % im.mode)\n\n    ifd = ImageFileDirectory_v2(prefix=prefix)\n\n    compression = im.encoderinfo.get('compression',\n                                     im.info.get('compression', 'raw'))\n\n    libtiff = WRITE_LIBTIFF or compression != 'raw'\n\n    # required for color libtiff images\n    ifd[PLANAR_CONFIGURATION] = getattr(im, '_planar_configuration', 1)\n\n    ifd[IMAGEWIDTH] = im.size[0]\n    ifd[IMAGELENGTH] = im.size[1]\n\n    # write any arbitrary tags passed in as an ImageFileDirectory\n    info = im.encoderinfo.get(\"tiffinfo\", {})\n    if DEBUG:\n        print(\"Tiffinfo Keys: %s\" % list(info))\n    if isinstance(info, ImageFileDirectory_v1):\n        info = info.to_v2()\n    for key in info:\n        ifd[key] = info.get(key)\n        try:\n            ifd.tagtype[key] = info.tagtype[key]\n        except:\n            pass  # might not be an IFD, Might not have populated type\n\n    # additions written by Greg Couch, gregc@cgl.ucsf.edu\n    # inspired by image-sig posting from Kevin Cazabon, kcazabon@home.com\n    if hasattr(im, 'tag_v2'):\n        # preserve tags from original TIFF image file\n        for key in (RESOLUTION_UNIT, X_RESOLUTION, Y_RESOLUTION,\n                    IPTC_NAA_CHUNK, PHOTOSHOP_CHUNK, XMP):\n            if key in im.tag_v2:\n                ifd[key] = im.tag_v2[key]\n                ifd.tagtype[key] = im.tag_v2.tagtype[key]\n\n    # preserve ICC profile (should also work when saving other formats\n    # which support profiles as TIFF) -- 2008-06-06 Florian Hoech\n    if \"icc_profile\" in im.info:\n        ifd[ICCPROFILE] = im.info[\"icc_profile\"]\n\n    for key, name in [(IMAGEDESCRIPTION, \"description\"),\n                      (X_RESOLUTION, \"resolution\"),\n                      (Y_RESOLUTION, \"resolution\"),\n                      (X_RESOLUTION, \"x_resolution\"),\n                      (Y_RESOLUTION, \"y_resolution\"),\n                      (RESOLUTION_UNIT, \"resolution_unit\"),\n                      (SOFTWARE, \"software\"),\n                      (DATE_TIME, \"date_time\"),\n                      (ARTIST, \"artist\"),\n                      (COPYRIGHT, \"copyright\")]:\n        name_with_spaces = name.replace(\"_\", \" \")\n        if \"_\" in name and name_with_spaces in im.encoderinfo:\n            warnings.warn(\"%r is deprecated; use %r instead\" %\n                          (name_with_spaces, name), DeprecationWarning)\n            ifd[key] = im.encoderinfo[name.replace(\"_\", \" \")]\n        if name in im.encoderinfo:\n            ifd[key] = im.encoderinfo[name]\n\n    dpi = im.encoderinfo.get(\"dpi\")\n    if dpi:\n        ifd[RESOLUTION_UNIT] = 2\n        ifd[X_RESOLUTION] = dpi[0]\n        ifd[Y_RESOLUTION] = dpi[1]\n\n    if bits != (1,):\n        ifd[BITSPERSAMPLE] = bits\n        if len(bits) != 1:\n            ifd[SAMPLESPERPIXEL] = len(bits)\n    if extra is not None:\n        ifd[EXTRASAMPLES] = extra\n    if format != 1:\n        ifd[SAMPLEFORMAT] = format\n\n    ifd[PHOTOMETRIC_INTERPRETATION] = photo\n\n    if im.mode == \"P\":\n        lut = im.im.getpalette(\"RGB\", \"RGB;L\")\n        ifd[COLORMAP] = tuple(i8(v) * 256 for v in lut)\n    # data orientation\n    stride = len(bits) * ((im.size[0]*bits[0]+7)//8)\n    ifd[ROWSPERSTRIP] = im.size[1]\n    ifd[STRIPBYTECOUNTS] = stride * im.size[1]\n    ifd[STRIPOFFSETS] = 0  # this is adjusted by IFD writer\n    # no compression by default:\n    ifd[COMPRESSION] = COMPRESSION_INFO_REV.get(compression, 1)\n\n    if libtiff:\n        if DEBUG:\n            print(\"Saving using libtiff encoder\")\n            print(\"Items: %s\" % sorted(ifd.items()))\n        _fp = 0\n        if hasattr(fp, \"fileno\"):\n            try:\n                fp.seek(0)\n                _fp = os.dup(fp.fileno())\n            except io.UnsupportedOperation:\n                pass\n\n        # STRIPOFFSETS and STRIPBYTECOUNTS are added by the library\n        # based on the data in the strip.\n        blocklist = [STRIPOFFSETS, STRIPBYTECOUNTS]\n        atts = {}\n        # bits per sample is a single short in the tiff directory, not a list.\n        atts[BITSPERSAMPLE] = bits[0]\n        # Merge the ones that we have with (optional) more bits from\n        # the original file, e.g x,y resolution so that we can\n        # save(load('')) == original file.\n        legacy_ifd = {}\n        if hasattr(im, 'tag'):\n            legacy_ifd = im.tag.to_v2()\n        for tag, value in itertools.chain(ifd.items(),\n                                          getattr(im, 'tag_v2', {}).items(),\n                                          legacy_ifd.items()):\n            # Libtiff can only process certain core items without adding\n            # them to the custom dictionary. It will segfault if it attempts\n            # to add a custom tag without the dictionary entry\n            #\n            # UNDONE --  add code for the custom dictionary\n            if tag not in TiffTags.LIBTIFF_CORE:\n                continue\n            if tag not in atts and tag not in blocklist:\n                if isinstance(value, unicode if bytes is str else str):\n                    atts[tag] = value.encode('ascii', 'replace') + b\"\\0\"\n                elif isinstance(value, IFDRational):\n                    atts[tag] = float(value)\n                else:\n                    atts[tag] = value\n\n        if DEBUG:\n            print(\"Converted items: %s\" % sorted(atts.items()))\n\n        # libtiff always expects the bytes in native order.\n        # we're storing image byte order. So, if the rawmode\n        # contains I;16, we need to convert from native to image\n        # byte order.\n        if im.mode in ('I;16B', 'I;16'):\n            rawmode = 'I;16N'\n\n        a = (rawmode, compression, _fp, filename, atts)\n        # print(im.mode, compression, a, im.encoderconfig)\n        e = Image._getencoder(im.mode, 'libtiff', a, im.encoderconfig)\n        e.setimage(im.im, (0, 0)+im.size)\n        while True:\n            # undone, change to self.decodermaxblock:\n            l, s, d = e.encode(16*1024)\n            if not _fp:\n                fp.write(d)\n            if s:\n                break\n        if s < 0:\n            raise IOError(\"encoder error %d when writing image file\" % s)\n\n    else:\n        offset = ifd.save(fp)\n\n        ImageFile._save(im, fp, [\n            (\"raw\", (0, 0)+im.size, offset, (rawmode, stride, 1))\n            ])\n\n    # -- helper for multi-page save --\n    if \"_debug_multipage\" in im.encoderinfo:\n        # just to access o32 and o16 (using correct byte order)\n        im._debug_multipage = ifd\n\nclass AppendingTiffWriter:\n    fieldSizes = [\n        0,  # None\n        1,  # byte\n        1,  # ascii\n        2,  # short\n        4,  # long\n        8,  # rational\n        1,  # sbyte\n        1,  # undefined\n        2,  # sshort\n        4,  # slong\n        8,  # srational\n        4,  # float\n        8,  # double\n    ]\n\n    #    StripOffsets = 273\n    #    FreeOffsets = 288\n    #    TileOffsets = 324\n    #    JPEGQTables = 519\n    #    JPEGDCTables = 520\n    #    JPEGACTables = 521\n    Tags = {273, 288, 324, 519, 520, 521}\n\n    def __init__(self, fn, new=False):\n        if hasattr(fn, 'read'):\n            self.f = fn\n            self.close_fp = False\n        else:\n            self.name = fn\n            self.close_fp = True\n            try:\n                self.f = io.open(fn, \"w+b\" if new else \"r+b\")\n            except IOError:\n                self.f = io.open(fn, \"w+b\")\n        self.beginning = self.f.tell()\n        self.setup()\n\n    def setup(self):\n        # Reset everything.\n        self.f.seek(self.beginning, os.SEEK_SET)\n\n        self.whereToWriteNewIFDOffset = None\n        self.offsetOfNewPage = 0\n\n        self.IIMM = IIMM = self.f.read(4)\n        if not IIMM:\n            # empty file - first page\n            self.isFirst = True\n            return\n\n        self.isFirst = False\n        if IIMM == b\"II\\x2a\\x00\":\n            self.setEndian(\"<\")\n        elif IIMM == b\"MM\\x00\\x2a\":\n            self.setEndian(\">\")\n        else:\n            raise RuntimeError(\"Invalid TIFF file header\")\n\n        self.skipIFDs()\n        self.goToEnd()\n\n    def finalize(self):\n        if self.isFirst:\n            return\n\n        # fix offsets\n        self.f.seek(self.offsetOfNewPage)\n\n        IIMM = self.f.read(4)\n        if not IIMM:\n            # raise RuntimeError(\"nothing written into new page\")\n            # Make it easy to finish a frame without committing to a new one.\n            return\n\n        if IIMM != self.IIMM:\n            raise RuntimeError(\"IIMM of new page doesn't match IIMM of \"\n                               \"first page\")\n\n        IFDoffset = self.readLong()\n        IFDoffset += self.offsetOfNewPage\n        self.f.seek(self.whereToWriteNewIFDOffset)\n        self.writeLong(IFDoffset)\n        self.f.seek(IFDoffset)\n        self.fixIFD()\n\n    def newFrame(self):\n        # Call this to finish a frame.\n        self.finalize()\n        self.setup()\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, exc_type, exc_value, traceback):\n        if self.close_fp:\n            self.close()\n        return False\n\n    def tell(self):\n        return self.f.tell() - self.offsetOfNewPage\n\n    def seek(self, offset, whence):\n        if whence == os.SEEK_SET:\n            offset += self.offsetOfNewPage\n\n        self.f.seek(offset, whence)\n        return self.tell()\n\n    def goToEnd(self):\n        self.f.seek(0, os.SEEK_END)\n        pos = self.f.tell()\n\n        # pad to 16 byte boundary\n        padBytes = 16 - pos % 16\n        if 0 < padBytes < 16:\n            self.f.write(bytes(bytearray(padBytes)))\n        self.offsetOfNewPage = self.f.tell()\n\n    def setEndian(self, endian):\n        self.endian = endian\n        self.longFmt = self.endian + \"L\"\n        self.shortFmt = self.endian + \"H\"\n        self.tagFormat = self.endian + \"HHL\"\n\n    def skipIFDs(self):\n        while True:\n            IFDoffset = self.readLong()\n            if IFDoffset == 0:\n                self.whereToWriteNewIFDOffset = self.f.tell() - 4\n                break\n\n            self.f.seek(IFDoffset)\n            numTags = self.readShort()\n            self.f.seek(numTags * 12, os.SEEK_CUR)\n\n    def write(self, data):\n        return self.f.write(data)\n\n    def readShort(self):\n        value, = struct.unpack(self.shortFmt, self.f.read(2))\n        return value\n\n    def readLong(self):\n        value, = struct.unpack(self.longFmt, self.f.read(4))\n        return value\n\n    def rewriteLastShortToLong(self, value):\n        self.f.seek(-2, os.SEEK_CUR)\n        bytesWritten = self.f.write(struct.pack(self.longFmt, value))\n        if bytesWritten is not None and bytesWritten != 4:\n            raise RuntimeError(\"wrote only %u bytes but wanted 4\" %\n                               bytesWritten)\n\n    def rewriteLastShort(self, value):\n        self.f.seek(-2, os.SEEK_CUR)\n        bytesWritten = self.f.write(struct.pack(self.shortFmt, value))\n        if bytesWritten is not None and bytesWritten != 2:\n            raise RuntimeError(\"wrote only %u bytes but wanted 2\" %\n                               bytesWritten)\n\n    def rewriteLastLong(self, value):\n        self.f.seek(-4, os.SEEK_CUR)\n        bytesWritten = self.f.write(struct.pack(self.longFmt, value))\n        if bytesWritten is not None and bytesWritten != 4:\n            raise RuntimeError(\"wrote only %u bytes but wanted 4\" %\n                               bytesWritten)\n\n    def writeShort(self, value):\n        bytesWritten = self.f.write(struct.pack(self.shortFmt, value))\n        if bytesWritten is not None and bytesWritten != 2:\n            raise RuntimeError(\"wrote only %u bytes but wanted 2\" %\n                               bytesWritten)\n\n    def writeLong(self, value):\n        bytesWritten = self.f.write(struct.pack(self.longFmt, value))\n        if bytesWritten is not None and bytesWritten != 4:\n            raise RuntimeError(\"wrote only %u bytes but wanted 4\" %\n                               bytesWritten)\n\n    def close(self):\n        self.finalize()\n        self.f.close()\n\n    def fixIFD(self):\n        numTags = self.readShort()\n        #trace(\"fixing IFD at %X; number of tags: %u (0x%X)\", self.f.tell()-2,\n        #      numTags, numTags)\n\n        for i in range(numTags):\n            tag, fieldType, count = struct.unpack(self.tagFormat, self.f.read(8))\n            #trace(\"  at %X: tag %u (0x%X), type %u, count %u\", self.f.tell()-8,\n            #      tag, tag, fieldType, count)\n\n            fieldSize = self.fieldSizes[fieldType]\n            totalSize = fieldSize * count\n            isLocal = (totalSize <= 4)\n            if not isLocal:\n                offset = self.readLong()\n                offset += self.offsetOfNewPage\n                self.rewriteLastLong(offset)\n\n            if tag in self.Tags:\n                curPos = self.f.tell()\n\n                if isLocal:\n                    self.fixOffsets(count, isShort=(fieldSize == 2),\n                                    isLong=(fieldSize == 4))\n                    self.f.seek(curPos + 4)\n                else:\n                    self.f.seek(offset)\n                    self.fixOffsets(count, isShort=(fieldSize == 2),\n                                    isLong=(fieldSize == 4))\n                    self.f.seek(curPos)\n\n                offset = curPos = None\n\n            elif isLocal:\n                # skip the locally stored value that is not an offset\n                self.f.seek(4, os.SEEK_CUR)\n\n    def fixOffsets(self, count, isShort=False, isLong=False):\n        if not isShort and not isLong:\n            raise RuntimeError(\"offset is neither short nor long\")\n\n        for i in range(count):\n            offset = self.readShort() if isShort else self.readLong()\n            offset += self.offsetOfNewPage\n            if isShort and offset >= 65536:\n                # offset is now too large - we must convert shorts to longs\n                if count != 1:\n                    raise RuntimeError(\"not implemented\")  # XXX TODO\n\n                # simple case - the offset is just one and therefore it is\n                # local (not referenced with another offset)\n                self.rewriteLastShortToLong(offset)\n                self.f.seek(-10, os.SEEK_CUR)\n                self.writeShort(4)  # rewrite the type to LONG\n                self.f.seek(8, os.SEEK_CUR)\n            elif isShort:\n                self.rewriteLastShort(offset)\n            else:\n                self.rewriteLastLong(offset)\n\ndef _save_all(im, fp, filename):\n    if not hasattr(im, \"n_frames\"):\n        return _save(im, fp, filename)\n\n    cur_idx = im.tell()\n    try:\n        with AppendingTiffWriter(fp) as tf:\n            for idx in range(im.n_frames):\n                im.seek(idx)\n                im.load()\n                _save(im, tf, filename)\n                tf.newFrame()\n    finally:\n        im.seek(cur_idx)\n\n#\n# --------------------------------------------------------------------\n# Register\n\nImage.register_open(TiffImageFile.format, TiffImageFile, _accept)\nImage.register_save(TiffImageFile.format, _save)\nImage.register_save_all(TiffImageFile.format, _save_all)\n\nImage.register_extension(TiffImageFile.format, \".tif\")\nImage.register_extension(TiffImageFile.format, \".tiff\")\n\nImage.register_mime(TiffImageFile.format, \"image/tiff\")\n",
            "header": {
                "file": {
                    "path": "PIL/TiffImagePlugin.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "e5009d0f1",
                "new_commit_hash": "505025bb8",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/PIL/TiffImagePlugin.py"
            },
            "plus_file": {
                "path": "b/PIL/TiffImagePlugin.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 1163,
                            "length": 11
                        },
                        "new_range": {
                            "start": 1163,
                            "length": 15
                        },
                        "section": "class TiffImageFile(ImageFile.ImageFile):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        yres = self.tag_v2.get(Y_RESOLUTION, 1)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        if xres and yres:",
                                "type": "context"
                            },
                            {
                                "content": "            resunit = self.tag_v2.get(RESOLUTION_UNIT, 1)",
                                "type": "deleted"
                            },
                            {
                                "content": "            resunit = self.tag_v2.get(RESOLUTION_UNIT)",
                                "type": "added"
                            },
                            {
                                "content": "            if resunit == 2:  # dots per inch",
                                "type": "context"
                            },
                            {
                                "content": "                self.info[\"dpi\"] = xres, yres",
                                "type": "context"
                            },
                            {
                                "content": "            elif resunit == 3:  # dots per centimeter. convert to dpi",
                                "type": "context"
                            },
                            {
                                "content": "                self.info[\"dpi\"] = xres * 2.54, yres * 2.54",
                                "type": "context"
                            },
                            {
                                "content": "            elif resunit == None: # used to default to 1, but now 2)",
                                "type": "added"
                            },
                            {
                                "content": "                self.info[\"dpi\"] = xres, yres",
                                "type": "added"
                            },
                            {
                                "content": "                # For backward compatibility, we also preserve the old behavior.",
                                "type": "added"
                            },
                            {
                                "content": "                self.info[\"resolution\"] = xres, yres",
                                "type": "added"
                            },
                            {
                                "content": "            else:  # No absolute unit of measurement",
                                "type": "context"
                            },
                            {
                                "content": "                self.info[\"resolution\"] = xres, yres",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "PIL/TiffImagePlugin.py",
                            "type": "method",
                            "name": "TiffImageFile._setup",
                            "content": "class TiffImageFile(ImageFile.ImageFile):\n\n    format = \"TIFF\"\n    format_description = \"Adobe TIFF\"\n\n    def _open(self):\n        \"Open the first image in a TIFF file\"\n\n        # Header\n        ifh = self.fp.read(8)\n\n        # image file directory (tag dictionary)\n        self.tag_v2 = ImageFileDirectory_v2(ifh)\n\n        # legacy tag/ifd entries will be filled in later\n        self.tag = self.ifd = None\n\n        # setup frame pointers\n        self.__first = self.__next = self.tag_v2.next\n        self.__frame = -1\n        self.__fp = self.fp\n        self._frame_pos = []\n        self._n_frames = None\n        self._is_animated = None\n\n        if DEBUG:\n            print(\"*** TiffImageFile._open ***\")\n            print(\"- __first:\", self.__first)\n            print(\"- ifh: \", ifh)\n\n        # and load the first frame\n        self._seek(0)\n\n    @property\n    def n_frames(self):\n        if self._n_frames is None:\n            current = self.tell()\n            try:\n                while True:\n                    self._seek(self.tell() + 1)\n            except EOFError:\n                self._n_frames = self.tell() + 1\n            self.seek(current)\n        return self._n_frames\n\n    @property\n    def is_animated(self):\n        if self._is_animated is None:\n            current = self.tell()\n\n            try:\n                self.seek(1)\n                self._is_animated = True\n            except EOFError:\n                self._is_animated = False\n\n            self.seek(current)\n        return self._is_animated\n\n    def seek(self, frame):\n        \"Select a given frame as current image\"\n        self._seek(max(frame, 0))  # Questionable backwards compatibility.\n        # Create a new core image object on second and\n        # subsequent frames in the image. Image may be\n        # different size/mode.\n        Image._decompression_bomb_check(self.size)\n        self.im = Image.core.new(self.mode, self.size)\n\n    def _seek(self, frame):\n        self.fp = self.__fp\n        while len(self._frame_pos) <= frame:\n            if not self.__next:\n                raise EOFError(\"no more images in TIFF file\")\n            if DEBUG:\n                print(\"Seeking to frame %s, on frame %s, \"\n                      \"__next %s, location: %s\" %\n                      (frame, self.__frame, self.__next, self.fp.tell()))\n            # reset python3 buffered io handle in case fp\n            # was passed to libtiff, invalidating the buffer\n            self.fp.tell()\n            self.fp.seek(self.__next)\n            self._frame_pos.append(self.__next)\n            if DEBUG:\n                print(\"Loading tags, location: %s\" % self.fp.tell())\n            self.tag_v2.load(self.fp)\n            self.__next = self.tag_v2.next\n            self.__frame += 1\n        self.fp.seek(self._frame_pos[frame])\n        self.tag_v2.load(self.fp)\n        # fill the legacy tag/ifd entries\n        self.tag = self.ifd = ImageFileDirectory_v1.from_v2(self.tag_v2)\n        self.__frame = frame\n        self._setup()\n\n    def tell(self):\n        \"Return the current frame number\"\n        return self.__frame\n\n    def _decoder(self, rawmode, layer, tile=None):\n        \"Setup decoder contexts\"\n\n        args = None\n        if rawmode == \"RGB\" and self._planar_configuration == 2:\n            rawmode = rawmode[layer]\n        compression = self._compression\n        if compression == \"raw\":\n            args = (rawmode, 0, 1)\n        elif compression == \"jpeg\":\n            args = rawmode, \"\"\n            if JPEGTABLES in self.tag_v2:\n                # Hack to handle abbreviated JPEG headers\n                # FIXME This will fail with more than one value\n                self.tile_prefix, = self.tag_v2[JPEGTABLES]\n        elif compression == \"packbits\":\n            args = rawmode\n        elif compression == \"tiff_lzw\":\n            args = rawmode\n            if PREDICTOR in self.tag_v2:\n                # Section 14: Differencing Predictor\n                self.decoderconfig = (self.tag_v2[PREDICTOR],)\n\n        return args\n\n    def load(self):\n        if self.use_load_libtiff:\n            return self._load_libtiff()\n        return super(TiffImageFile, self).load()\n\n    def _load_libtiff(self):\n        \"\"\" Overload method triggered when we detect a compressed tiff\n            Calls out to libtiff \"\"\"\n\n        pixel = Image.Image.load(self)\n\n        if self.tile is None:\n            raise IOError(\"cannot load this image\")\n        if not self.tile:\n            return pixel\n\n        self.load_prepare()\n\n        if not len(self.tile) == 1:\n            raise IOError(\"Not exactly one tile\")\n\n        # (self._compression, (extents tuple),\n        #   0, (rawmode, self._compression, fp))\n        extents = self.tile[0][1]\n        args = list(self.tile[0][3]) + [self.tag_v2.offset]\n\n        # To be nice on memory footprint, if there's a\n        # file descriptor, use that instead of reading\n        # into a string in python.\n        # libtiff closes the file descriptor, so pass in a dup.\n        try:\n            fp = hasattr(self.fp, \"fileno\") and os.dup(self.fp.fileno())\n            # flush the file descriptor, prevents error on pypy 2.4+\n            # should also eliminate the need for fp.tell for py3\n            # in _seek\n            if hasattr(self.fp, \"flush\"):\n                self.fp.flush()\n        except IOError:\n            # io.BytesIO have a fileno, but returns an IOError if\n            # it doesn't use a file descriptor.\n            fp = False\n\n        if fp:\n            args[2] = fp\n\n        decoder = Image._getdecoder(self.mode, 'libtiff', tuple(args),\n                                    self.decoderconfig)\n        try:\n            decoder.setimage(self.im, extents)\n        except ValueError:\n            raise IOError(\"Couldn't set the image\")\n\n        if hasattr(self.fp, \"getvalue\"):\n            # We've got a stringio like thing passed in. Yay for all in memory.\n            # The decoder needs the entire file in one shot, so there's not\n            # a lot we can do here other than give it the entire file.\n            # unless we could do something like get the address of the\n            # underlying string for stringio.\n            #\n            # Rearranging for supporting byteio items, since they have a fileno\n            # that returns an IOError if there's no underlying fp. Easier to\n            # deal with here by reordering.\n            if DEBUG:\n                print(\"have getvalue. just sending in a string from getvalue\")\n            n, err = decoder.decode(self.fp.getvalue())\n        elif hasattr(self.fp, \"fileno\"):\n            # we've got a actual file on disk, pass in the fp.\n            if DEBUG:\n                print(\"have fileno, calling fileno version of the decoder.\")\n            self.fp.seek(0)\n            # 4 bytes, otherwise the trace might error out\n            n, err = decoder.decode(b\"fpfp\")\n        else:\n            # we have something else.\n            if DEBUG:\n                print(\"don't have fileno or getvalue. just reading\")\n            # UNDONE -- so much for that buffer size thing.\n            n, err = decoder.decode(self.fp.read())\n\n        self.tile = []\n        self.readonly = 0\n        # libtiff closed the fp in a, we need to close self.fp, if possible\n        if hasattr(self.fp, 'close'):\n            if not self.__next:\n                self.fp.close()\n        self.fp = None  # might be shared\n\n        if err < 0:\n            raise IOError(err)\n\n        self.load_end()\n\n        return Image.Image.load(self)\n\n    def _setup(self):\n        \"Setup this image object based on current tags\"\n\n        if 0xBC01 in self.tag_v2:\n            raise IOError(\"Windows Media Photo files not yet supported\")\n\n        # extract relevant tags\n        self._compression = COMPRESSION_INFO[self.tag_v2.get(COMPRESSION, 1)]\n        self._planar_configuration = self.tag_v2.get(PLANAR_CONFIGURATION, 1)\n\n        # photometric is a required tag, but not everyone is reading\n        # the specification\n        photo = self.tag_v2.get(PHOTOMETRIC_INTERPRETATION, 0)\n\n        fillorder = self.tag_v2.get(FILLORDER, 1)\n\n        if DEBUG:\n            print(\"*** Summary ***\")\n            print(\"- compression:\", self._compression)\n            print(\"- photometric_interpretation:\", photo)\n            print(\"- planar_configuration:\", self._planar_configuration)\n            print(\"- fill_order:\", fillorder)\n\n        # size\n        xsize = self.tag_v2.get(IMAGEWIDTH)\n        ysize = self.tag_v2.get(IMAGELENGTH)\n        self.size = xsize, ysize\n\n        if DEBUG:\n            print(\"- size:\", self.size)\n\n        sampleFormat = self.tag_v2.get(SAMPLEFORMAT, (1,))\n        if (len(sampleFormat) > 1\n            and max(sampleFormat) == min(sampleFormat) == 1):\n            # SAMPLEFORMAT is properly per band, so an RGB image will\n            # be (1,1,1).  But, we don't support per band pixel types,\n            # and anything more than one band is a uint8. So, just\n            # take the first element. Revisit this if adding support\n            # for more exotic images.\n            sampleFormat = (1,)\n\n        # mode: check photometric interpretation and bits per pixel\n        key = (\n            self.tag_v2.prefix, photo, sampleFormat, fillorder,\n            self.tag_v2.get(BITSPERSAMPLE, (1,)),\n            self.tag_v2.get(EXTRASAMPLES, ())\n            )\n        if DEBUG:\n            print(\"format key:\", key)\n        try:\n            self.mode, rawmode = OPEN_INFO[key]\n        except KeyError:\n            if DEBUG:\n                print(\"- unsupported format\")\n            raise SyntaxError(\"unknown pixel mode\")\n\n        if DEBUG:\n            print(\"- raw mode:\", rawmode)\n            print(\"- pil mode:\", self.mode)\n\n        self.info[\"compression\"] = self._compression\n\n        xres = self.tag_v2.get(X_RESOLUTION, 1)\n        yres = self.tag_v2.get(Y_RESOLUTION, 1)\n\n        if xres and yres:\n            resunit = self.tag_v2.get(RESOLUTION_UNIT, 1)\n            if resunit == 2:  # dots per inch\n                self.info[\"dpi\"] = xres, yres\n            elif resunit == 3:  # dots per centimeter. convert to dpi\n                self.info[\"dpi\"] = xres * 2.54, yres * 2.54\n            else:  # No absolute unit of measurement\n                self.info[\"resolution\"] = xres, yres\n\n        # build tile descriptors\n        x = y = l = 0\n        self.tile = []\n        self.use_load_libtiff = False\n        if STRIPOFFSETS in self.tag_v2:\n            # striped image\n            offsets = self.tag_v2[STRIPOFFSETS]\n            h = self.tag_v2.get(ROWSPERSTRIP, ysize)\n            w = self.size[0]\n            if READ_LIBTIFF or self._compression in [\"tiff_ccitt\", \"group3\",\n                                                     \"group4\", \"tiff_jpeg\",\n                                                     \"tiff_adobe_deflate\",\n                                                     \"tiff_thunderscan\",\n                                                     \"tiff_deflate\",\n                                                     \"tiff_sgilog\",\n                                                     \"tiff_sgilog24\",\n                                                     \"tiff_raw_16\"]:\n                # if DEBUG:\n                #     print(\"Activating g4 compression for whole file\")\n\n                # Decoder expects entire file as one tile.\n                # There's a buffer size limit in load (64k)\n                # so large g4 images will fail if we use that\n                # function.\n                #\n                # Setup the one tile for the whole image, then\n                # use the _load_libtiff function.\n\n                self.use_load_libtiff = True\n\n                # libtiff handles the fillmode for us, so 1;IR should\n                # actually be 1;I. Including the R double reverses the\n                # bits, so stripes of the image are reversed.  See\n                # https://github.com/python-pillow/Pillow/issues/279\n                if fillorder == 2:\n                    key = (\n                        self.tag_v2.prefix, photo, sampleFormat, 1,\n                        self.tag_v2.get(BITSPERSAMPLE, (1,)),\n                        self.tag_v2.get(EXTRASAMPLES, ())\n                        )\n                    if DEBUG:\n                        print(\"format key:\", key)\n                    # this should always work, since all the\n                    # fillorder==2 modes have a corresponding\n                    # fillorder=1 mode\n                    self.mode, rawmode = OPEN_INFO[key]\n                # libtiff always returns the bytes in native order.\n                # we're expecting image byte order. So, if the rawmode\n                # contains I;16, we need to convert from native to image\n                # byte order.\n                if self.mode in ('I;16B', 'I;16') and 'I;16' in rawmode:\n                    rawmode = 'I;16N'\n\n                # Offset in the tile tuple is 0, we go from 0,0 to\n                # w,h, and we only do this once -- eds\n                a = (rawmode, self._compression, False)\n                self.tile.append(\n                    (self._compression,\n                     (0, 0, w, ysize),\n                     0, a))\n                a = None\n\n            else:\n                for i, offset in enumerate(offsets):\n                    a = self._decoder(rawmode, l, i)\n                    self.tile.append(\n                        (self._compression,\n                            (0, min(y, ysize), w, min(y+h, ysize)),\n                            offset, a))\n                    if DEBUG:\n                        print(\"tiles: \", self.tile)\n                    y = y + h\n                    if y >= self.size[1]:\n                        x = y = 0\n                        l += 1\n                    a = None\n        elif TILEOFFSETS in self.tag_v2:\n            # tiled image\n            w = self.tag_v2.get(322)\n            h = self.tag_v2.get(323)\n            a = None\n            for o in self.tag_v2[TILEOFFSETS]:\n                if not a:\n                    a = self._decoder(rawmode, l)\n                # FIXME: this doesn't work if the image size\n                # is not a multiple of the tile size...\n                self.tile.append(\n                    (self._compression,\n                        (x, y, x+w, y+h),\n                        o, a))\n                x = x + w\n                if x >= self.size[0]:\n                    x, y = 0, y + h\n                    if y >= self.size[1]:\n                        x = y = 0\n                        l += 1\n                        a = None\n        else:\n            if DEBUG:\n                print(\"- unsupported data organization\")\n            raise SyntaxError(\"unknown data organization\")\n\n        # Fix up info.\n        if ICCPROFILE in self.tag_v2:\n            self.info['icc_profile'] = self.tag_v2[ICCPROFILE]\n\n        # fixup palette descriptor\n\n        if self.mode == \"P\":\n            palette = [o8(b // 256) for b in self.tag_v2[COLORMAP]]\n            self.palette = ImagePalette.raw(\"RGB;L\", b\"\".join(palette))",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 1100,
                            "end_lineno": 1284,
                            "parent": {
                                "file_name": "PIL/TiffImagePlugin.py",
                                "type": "class",
                                "name": "TiffImageFile",
                                "content": "class TiffImageFile(ImageFile.ImageFile):\n\n    format = \"TIFF\"\n    format_description = \"Adobe TIFF\"\n\n    def _open(self):\n        \"Open the first image in a TIFF file\"\n\n        # Header\n        ifh = self.fp.read(8)\n\n        # image file directory (tag dictionary)\n        self.tag_v2 = ImageFileDirectory_v2(ifh)\n\n        # legacy tag/ifd entries will be filled in later\n        self.tag = self.ifd = None\n\n        # setup frame pointers\n        self.__first = self.__next = self.tag_v2.next\n        self.__frame = -1\n        self.__fp = self.fp\n        self._frame_pos = []\n        self._n_frames = None\n        self._is_animated = None\n\n        if DEBUG:\n            print(\"*** TiffImageFile._open ***\")\n            print(\"- __first:\", self.__first)\n            print(\"- ifh: \", ifh)\n\n        # and load the first frame\n        self._seek(0)\n\n    @property\n    def n_frames(self):\n        if self._n_frames is None:\n            current = self.tell()\n            try:\n                while True:\n                    self._seek(self.tell() + 1)\n            except EOFError:\n                self._n_frames = self.tell() + 1\n            self.seek(current)\n        return self._n_frames\n\n    @property\n    def is_animated(self):\n        if self._is_animated is None:\n            current = self.tell()\n\n            try:\n                self.seek(1)\n                self._is_animated = True\n            except EOFError:\n                self._is_animated = False\n\n            self.seek(current)\n        return self._is_animated\n\n    def seek(self, frame):\n        \"Select a given frame as current image\"\n        self._seek(max(frame, 0))  # Questionable backwards compatibility.\n        # Create a new core image object on second and\n        # subsequent frames in the image. Image may be\n        # different size/mode.\n        Image._decompression_bomb_check(self.size)\n        self.im = Image.core.new(self.mode, self.size)\n\n    def _seek(self, frame):\n        self.fp = self.__fp\n        while len(self._frame_pos) <= frame:\n            if not self.__next:\n                raise EOFError(\"no more images in TIFF file\")\n            if DEBUG:\n                print(\"Seeking to frame %s, on frame %s, \"\n                      \"__next %s, location: %s\" %\n                      (frame, self.__frame, self.__next, self.fp.tell()))\n            # reset python3 buffered io handle in case fp\n            # was passed to libtiff, invalidating the buffer\n            self.fp.tell()\n            self.fp.seek(self.__next)\n            self._frame_pos.append(self.__next)\n            if DEBUG:\n                print(\"Loading tags, location: %s\" % self.fp.tell())\n            self.tag_v2.load(self.fp)\n            self.__next = self.tag_v2.next\n            self.__frame += 1\n        self.fp.seek(self._frame_pos[frame])\n        self.tag_v2.load(self.fp)\n        # fill the legacy tag/ifd entries\n        self.tag = self.ifd = ImageFileDirectory_v1.from_v2(self.tag_v2)\n        self.__frame = frame\n        self._setup()\n\n    def tell(self):\n        \"Return the current frame number\"\n        return self.__frame\n\n    def _decoder(self, rawmode, layer, tile=None):\n        \"Setup decoder contexts\"\n\n        args = None\n        if rawmode == \"RGB\" and self._planar_configuration == 2:\n            rawmode = rawmode[layer]\n        compression = self._compression\n        if compression == \"raw\":\n            args = (rawmode, 0, 1)\n        elif compression == \"jpeg\":\n            args = rawmode, \"\"\n            if JPEGTABLES in self.tag_v2:\n                # Hack to handle abbreviated JPEG headers\n                # FIXME This will fail with more than one value\n                self.tile_prefix, = self.tag_v2[JPEGTABLES]\n        elif compression == \"packbits\":\n            args = rawmode\n        elif compression == \"tiff_lzw\":\n            args = rawmode\n            if PREDICTOR in self.tag_v2:\n                # Section 14: Differencing Predictor\n                self.decoderconfig = (self.tag_v2[PREDICTOR],)\n\n        return args\n\n    def load(self):\n        if self.use_load_libtiff:\n            return self._load_libtiff()\n        return super(TiffImageFile, self).load()\n\n    def _load_libtiff(self):\n        \"\"\" Overload method triggered when we detect a compressed tiff\n            Calls out to libtiff \"\"\"\n\n        pixel = Image.Image.load(self)\n\n        if self.tile is None:\n            raise IOError(\"cannot load this image\")\n        if not self.tile:\n            return pixel\n\n        self.load_prepare()\n\n        if not len(self.tile) == 1:\n            raise IOError(\"Not exactly one tile\")\n\n        # (self._compression, (extents tuple),\n        #   0, (rawmode, self._compression, fp))\n        extents = self.tile[0][1]\n        args = list(self.tile[0][3]) + [self.tag_v2.offset]\n\n        # To be nice on memory footprint, if there's a\n        # file descriptor, use that instead of reading\n        # into a string in python.\n        # libtiff closes the file descriptor, so pass in a dup.\n        try:\n            fp = hasattr(self.fp, \"fileno\") and os.dup(self.fp.fileno())\n            # flush the file descriptor, prevents error on pypy 2.4+\n            # should also eliminate the need for fp.tell for py3\n            # in _seek\n            if hasattr(self.fp, \"flush\"):\n                self.fp.flush()\n        except IOError:\n            # io.BytesIO have a fileno, but returns an IOError if\n            # it doesn't use a file descriptor.\n            fp = False\n\n        if fp:\n            args[2] = fp\n\n        decoder = Image._getdecoder(self.mode, 'libtiff', tuple(args),\n                                    self.decoderconfig)\n        try:\n            decoder.setimage(self.im, extents)\n        except ValueError:\n            raise IOError(\"Couldn't set the image\")\n\n        if hasattr(self.fp, \"getvalue\"):\n            # We've got a stringio like thing passed in. Yay for all in memory.\n            # The decoder needs the entire file in one shot, so there's not\n            # a lot we can do here other than give it the entire file.\n            # unless we could do something like get the address of the\n            # underlying string for stringio.\n            #\n            # Rearranging for supporting byteio items, since they have a fileno\n            # that returns an IOError if there's no underlying fp. Easier to\n            # deal with here by reordering.\n            if DEBUG:\n                print(\"have getvalue. just sending in a string from getvalue\")\n            n, err = decoder.decode(self.fp.getvalue())\n        elif hasattr(self.fp, \"fileno\"):\n            # we've got a actual file on disk, pass in the fp.\n            if DEBUG:\n                print(\"have fileno, calling fileno version of the decoder.\")\n            self.fp.seek(0)\n            # 4 bytes, otherwise the trace might error out\n            n, err = decoder.decode(b\"fpfp\")\n        else:\n            # we have something else.\n            if DEBUG:\n                print(\"don't have fileno or getvalue. just reading\")\n            # UNDONE -- so much for that buffer size thing.\n            n, err = decoder.decode(self.fp.read())\n\n        self.tile = []\n        self.readonly = 0\n        # libtiff closed the fp in a, we need to close self.fp, if possible\n        if hasattr(self.fp, 'close'):\n            if not self.__next:\n                self.fp.close()\n        self.fp = None  # might be shared\n\n        if err < 0:\n            raise IOError(err)\n\n        self.load_end()\n\n        return Image.Image.load(self)\n\n    def _setup(self):\n        \"Setup this image object based on current tags\"\n\n        if 0xBC01 in self.tag_v2:\n            raise IOError(\"Windows Media Photo files not yet supported\")\n\n        # extract relevant tags\n        self._compression = COMPRESSION_INFO[self.tag_v2.get(COMPRESSION, 1)]\n        self._planar_configuration = self.tag_v2.get(PLANAR_CONFIGURATION, 1)\n\n        # photometric is a required tag, but not everyone is reading\n        # the specification\n        photo = self.tag_v2.get(PHOTOMETRIC_INTERPRETATION, 0)\n\n        fillorder = self.tag_v2.get(FILLORDER, 1)\n\n        if DEBUG:\n            print(\"*** Summary ***\")\n            print(\"- compression:\", self._compression)\n            print(\"- photometric_interpretation:\", photo)\n            print(\"- planar_configuration:\", self._planar_configuration)\n            print(\"- fill_order:\", fillorder)\n\n        # size\n        xsize = self.tag_v2.get(IMAGEWIDTH)\n        ysize = self.tag_v2.get(IMAGELENGTH)\n        self.size = xsize, ysize\n\n        if DEBUG:\n            print(\"- size:\", self.size)\n\n        sampleFormat = self.tag_v2.get(SAMPLEFORMAT, (1,))\n        if (len(sampleFormat) > 1\n            and max(sampleFormat) == min(sampleFormat) == 1):\n            # SAMPLEFORMAT is properly per band, so an RGB image will\n            # be (1,1,1).  But, we don't support per band pixel types,\n            # and anything more than one band is a uint8. So, just\n            # take the first element. Revisit this if adding support\n            # for more exotic images.\n            sampleFormat = (1,)\n\n        # mode: check photometric interpretation and bits per pixel\n        key = (\n            self.tag_v2.prefix, photo, sampleFormat, fillorder,\n            self.tag_v2.get(BITSPERSAMPLE, (1,)),\n            self.tag_v2.get(EXTRASAMPLES, ())\n            )\n        if DEBUG:\n            print(\"format key:\", key)\n        try:\n            self.mode, rawmode = OPEN_INFO[key]\n        except KeyError:\n            if DEBUG:\n                print(\"- unsupported format\")\n            raise SyntaxError(\"unknown pixel mode\")\n\n        if DEBUG:\n            print(\"- raw mode:\", rawmode)\n            print(\"- pil mode:\", self.mode)\n\n        self.info[\"compression\"] = self._compression\n\n        xres = self.tag_v2.get(X_RESOLUTION, 1)\n        yres = self.tag_v2.get(Y_RESOLUTION, 1)\n\n        if xres and yres:\n            resunit = self.tag_v2.get(RESOLUTION_UNIT, 1)\n            if resunit == 2:  # dots per inch\n                self.info[\"dpi\"] = xres, yres\n            elif resunit == 3:  # dots per centimeter. convert to dpi\n                self.info[\"dpi\"] = xres * 2.54, yres * 2.54\n            else:  # No absolute unit of measurement\n                self.info[\"resolution\"] = xres, yres\n\n        # build tile descriptors\n        x = y = l = 0\n        self.tile = []\n        self.use_load_libtiff = False\n        if STRIPOFFSETS in self.tag_v2:\n            # striped image\n            offsets = self.tag_v2[STRIPOFFSETS]\n            h = self.tag_v2.get(ROWSPERSTRIP, ysize)\n            w = self.size[0]\n            if READ_LIBTIFF or self._compression in [\"tiff_ccitt\", \"group3\",\n                                                     \"group4\", \"tiff_jpeg\",\n                                                     \"tiff_adobe_deflate\",\n                                                     \"tiff_thunderscan\",\n                                                     \"tiff_deflate\",\n                                                     \"tiff_sgilog\",\n                                                     \"tiff_sgilog24\",\n                                                     \"tiff_raw_16\"]:\n                # if DEBUG:\n                #     print(\"Activating g4 compression for whole file\")\n\n                # Decoder expects entire file as one tile.\n                # There's a buffer size limit in load (64k)\n                # so large g4 images will fail if we use that\n                # function.\n                #\n                # Setup the one tile for the whole image, then\n                # use the _load_libtiff function.\n\n                self.use_load_libtiff = True\n\n                # libtiff handles the fillmode for us, so 1;IR should\n                # actually be 1;I. Including the R double reverses the\n                # bits, so stripes of the image are reversed.  See\n                # https://github.com/python-pillow/Pillow/issues/279\n                if fillorder == 2:\n                    key = (\n                        self.tag_v2.prefix, photo, sampleFormat, 1,\n                        self.tag_v2.get(BITSPERSAMPLE, (1,)),\n                        self.tag_v2.get(EXTRASAMPLES, ())\n                        )\n                    if DEBUG:\n                        print(\"format key:\", key)\n                    # this should always work, since all the\n                    # fillorder==2 modes have a corresponding\n                    # fillorder=1 mode\n                    self.mode, rawmode = OPEN_INFO[key]\n                # libtiff always returns the bytes in native order.\n                # we're expecting image byte order. So, if the rawmode\n                # contains I;16, we need to convert from native to image\n                # byte order.\n                if self.mode in ('I;16B', 'I;16') and 'I;16' in rawmode:\n                    rawmode = 'I;16N'\n\n                # Offset in the tile tuple is 0, we go from 0,0 to\n                # w,h, and we only do this once -- eds\n                a = (rawmode, self._compression, False)\n                self.tile.append(\n                    (self._compression,\n                     (0, 0, w, ysize),\n                     0, a))\n                a = None\n\n            else:\n                for i, offset in enumerate(offsets):\n                    a = self._decoder(rawmode, l, i)\n                    self.tile.append(\n                        (self._compression,\n                            (0, min(y, ysize), w, min(y+h, ysize)),\n                            offset, a))\n                    if DEBUG:\n                        print(\"tiles: \", self.tile)\n                    y = y + h\n                    if y >= self.size[1]:\n                        x = y = 0\n                        l += 1\n                    a = None\n        elif TILEOFFSETS in self.tag_v2:\n            # tiled image\n            w = self.tag_v2.get(322)\n            h = self.tag_v2.get(323)\n            a = None\n            for o in self.tag_v2[TILEOFFSETS]:\n                if not a:\n                    a = self._decoder(rawmode, l)\n                # FIXME: this doesn't work if the image size\n                # is not a multiple of the tile size...\n                self.tile.append(\n                    (self._compression,\n                        (x, y, x+w, y+h),\n                        o, a))\n                x = x + w\n                if x >= self.size[0]:\n                    x, y = 0, y + h\n                    if y >= self.size[1]:\n                        x = y = 0\n                        l += 1\n                        a = None\n        else:\n            if DEBUG:\n                print(\"- unsupported data organization\")\n            raise SyntaxError(\"unknown data organization\")\n\n        # Fix up info.\n        if ICCPROFILE in self.tag_v2:\n            self.info['icc_profile'] = self.tag_v2[ICCPROFILE]\n\n        # fixup palette descriptor\n\n        if self.mode == \"P\":\n            palette = [o8(b // 256) for b in self.tag_v2[COLORMAP]]\n            self.palette = ImagePalette.raw(\"RGB;L\", b\"\".join(palette))",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 883,
                                "end_lineno": 1284,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "PIL/TiffImagePlugin.py",
                            "type": "class",
                            "name": "TiffImageFile",
                            "content": "class TiffImageFile(ImageFile.ImageFile):\n\n    format = \"TIFF\"\n    format_description = \"Adobe TIFF\"\n\n    def _open(self):\n        \"Open the first image in a TIFF file\"\n\n        # Header\n        ifh = self.fp.read(8)\n\n        # image file directory (tag dictionary)\n        self.tag_v2 = ImageFileDirectory_v2(ifh)\n\n        # legacy tag/ifd entries will be filled in later\n        self.tag = self.ifd = None\n\n        # setup frame pointers\n        self.__first = self.__next = self.tag_v2.next\n        self.__frame = -1\n        self.__fp = self.fp\n        self._frame_pos = []\n        self._n_frames = None\n        self._is_animated = None\n\n        if DEBUG:\n            print(\"*** TiffImageFile._open ***\")\n            print(\"- __first:\", self.__first)\n            print(\"- ifh: \", ifh)\n\n        # and load the first frame\n        self._seek(0)\n\n    @property\n    def n_frames(self):\n        if self._n_frames is None:\n            current = self.tell()\n            try:\n                while True:\n                    self._seek(self.tell() + 1)\n            except EOFError:\n                self._n_frames = self.tell() + 1\n            self.seek(current)\n        return self._n_frames\n\n    @property\n    def is_animated(self):\n        if self._is_animated is None:\n            current = self.tell()\n\n            try:\n                self.seek(1)\n                self._is_animated = True\n            except EOFError:\n                self._is_animated = False\n\n            self.seek(current)\n        return self._is_animated\n\n    def seek(self, frame):\n        \"Select a given frame as current image\"\n        self._seek(max(frame, 0))  # Questionable backwards compatibility.\n        # Create a new core image object on second and\n        # subsequent frames in the image. Image may be\n        # different size/mode.\n        Image._decompression_bomb_check(self.size)\n        self.im = Image.core.new(self.mode, self.size)\n\n    def _seek(self, frame):\n        self.fp = self.__fp\n        while len(self._frame_pos) <= frame:\n            if not self.__next:\n                raise EOFError(\"no more images in TIFF file\")\n            if DEBUG:\n                print(\"Seeking to frame %s, on frame %s, \"\n                      \"__next %s, location: %s\" %\n                      (frame, self.__frame, self.__next, self.fp.tell()))\n            # reset python3 buffered io handle in case fp\n            # was passed to libtiff, invalidating the buffer\n            self.fp.tell()\n            self.fp.seek(self.__next)\n            self._frame_pos.append(self.__next)\n            if DEBUG:\n                print(\"Loading tags, location: %s\" % self.fp.tell())\n            self.tag_v2.load(self.fp)\n            self.__next = self.tag_v2.next\n            self.__frame += 1\n        self.fp.seek(self._frame_pos[frame])\n        self.tag_v2.load(self.fp)\n        # fill the legacy tag/ifd entries\n        self.tag = self.ifd = ImageFileDirectory_v1.from_v2(self.tag_v2)\n        self.__frame = frame\n        self._setup()\n\n    def tell(self):\n        \"Return the current frame number\"\n        return self.__frame\n\n    def _decoder(self, rawmode, layer, tile=None):\n        \"Setup decoder contexts\"\n\n        args = None\n        if rawmode == \"RGB\" and self._planar_configuration == 2:\n            rawmode = rawmode[layer]\n        compression = self._compression\n        if compression == \"raw\":\n            args = (rawmode, 0, 1)\n        elif compression == \"jpeg\":\n            args = rawmode, \"\"\n            if JPEGTABLES in self.tag_v2:\n                # Hack to handle abbreviated JPEG headers\n                # FIXME This will fail with more than one value\n                self.tile_prefix, = self.tag_v2[JPEGTABLES]\n        elif compression == \"packbits\":\n            args = rawmode\n        elif compression == \"tiff_lzw\":\n            args = rawmode\n            if PREDICTOR in self.tag_v2:\n                # Section 14: Differencing Predictor\n                self.decoderconfig = (self.tag_v2[PREDICTOR],)\n\n        return args\n\n    def load(self):\n        if self.use_load_libtiff:\n            return self._load_libtiff()\n        return super(TiffImageFile, self).load()\n\n    def _load_libtiff(self):\n        \"\"\" Overload method triggered when we detect a compressed tiff\n            Calls out to libtiff \"\"\"\n\n        pixel = Image.Image.load(self)\n\n        if self.tile is None:\n            raise IOError(\"cannot load this image\")\n        if not self.tile:\n            return pixel\n\n        self.load_prepare()\n\n        if not len(self.tile) == 1:\n            raise IOError(\"Not exactly one tile\")\n\n        # (self._compression, (extents tuple),\n        #   0, (rawmode, self._compression, fp))\n        extents = self.tile[0][1]\n        args = list(self.tile[0][3]) + [self.tag_v2.offset]\n\n        # To be nice on memory footprint, if there's a\n        # file descriptor, use that instead of reading\n        # into a string in python.\n        # libtiff closes the file descriptor, so pass in a dup.\n        try:\n            fp = hasattr(self.fp, \"fileno\") and os.dup(self.fp.fileno())\n            # flush the file descriptor, prevents error on pypy 2.4+\n            # should also eliminate the need for fp.tell for py3\n            # in _seek\n            if hasattr(self.fp, \"flush\"):\n                self.fp.flush()\n        except IOError:\n            # io.BytesIO have a fileno, but returns an IOError if\n            # it doesn't use a file descriptor.\n            fp = False\n\n        if fp:\n            args[2] = fp\n\n        decoder = Image._getdecoder(self.mode, 'libtiff', tuple(args),\n                                    self.decoderconfig)\n        try:\n            decoder.setimage(self.im, extents)\n        except ValueError:\n            raise IOError(\"Couldn't set the image\")\n\n        if hasattr(self.fp, \"getvalue\"):\n            # We've got a stringio like thing passed in. Yay for all in memory.\n            # The decoder needs the entire file in one shot, so there's not\n            # a lot we can do here other than give it the entire file.\n            # unless we could do something like get the address of the\n            # underlying string for stringio.\n            #\n            # Rearranging for supporting byteio items, since they have a fileno\n            # that returns an IOError if there's no underlying fp. Easier to\n            # deal with here by reordering.\n            if DEBUG:\n                print(\"have getvalue. just sending in a string from getvalue\")\n            n, err = decoder.decode(self.fp.getvalue())\n        elif hasattr(self.fp, \"fileno\"):\n            # we've got a actual file on disk, pass in the fp.\n            if DEBUG:\n                print(\"have fileno, calling fileno version of the decoder.\")\n            self.fp.seek(0)\n            # 4 bytes, otherwise the trace might error out\n            n, err = decoder.decode(b\"fpfp\")\n        else:\n            # we have something else.\n            if DEBUG:\n                print(\"don't have fileno or getvalue. just reading\")\n            # UNDONE -- so much for that buffer size thing.\n            n, err = decoder.decode(self.fp.read())\n\n        self.tile = []\n        self.readonly = 0\n        # libtiff closed the fp in a, we need to close self.fp, if possible\n        if hasattr(self.fp, 'close'):\n            if not self.__next:\n                self.fp.close()\n        self.fp = None  # might be shared\n\n        if err < 0:\n            raise IOError(err)\n\n        self.load_end()\n\n        return Image.Image.load(self)\n\n    def _setup(self):\n        \"Setup this image object based on current tags\"\n\n        if 0xBC01 in self.tag_v2:\n            raise IOError(\"Windows Media Photo files not yet supported\")\n\n        # extract relevant tags\n        self._compression = COMPRESSION_INFO[self.tag_v2.get(COMPRESSION, 1)]\n        self._planar_configuration = self.tag_v2.get(PLANAR_CONFIGURATION, 1)\n\n        # photometric is a required tag, but not everyone is reading\n        # the specification\n        photo = self.tag_v2.get(PHOTOMETRIC_INTERPRETATION, 0)\n\n        fillorder = self.tag_v2.get(FILLORDER, 1)\n\n        if DEBUG:\n            print(\"*** Summary ***\")\n            print(\"- compression:\", self._compression)\n            print(\"- photometric_interpretation:\", photo)\n            print(\"- planar_configuration:\", self._planar_configuration)\n            print(\"- fill_order:\", fillorder)\n\n        # size\n        xsize = self.tag_v2.get(IMAGEWIDTH)\n        ysize = self.tag_v2.get(IMAGELENGTH)\n        self.size = xsize, ysize\n\n        if DEBUG:\n            print(\"- size:\", self.size)\n\n        sampleFormat = self.tag_v2.get(SAMPLEFORMAT, (1,))\n        if (len(sampleFormat) > 1\n            and max(sampleFormat) == min(sampleFormat) == 1):\n            # SAMPLEFORMAT is properly per band, so an RGB image will\n            # be (1,1,1).  But, we don't support per band pixel types,\n            # and anything more than one band is a uint8. So, just\n            # take the first element. Revisit this if adding support\n            # for more exotic images.\n            sampleFormat = (1,)\n\n        # mode: check photometric interpretation and bits per pixel\n        key = (\n            self.tag_v2.prefix, photo, sampleFormat, fillorder,\n            self.tag_v2.get(BITSPERSAMPLE, (1,)),\n            self.tag_v2.get(EXTRASAMPLES, ())\n            )\n        if DEBUG:\n            print(\"format key:\", key)\n        try:\n            self.mode, rawmode = OPEN_INFO[key]\n        except KeyError:\n            if DEBUG:\n                print(\"- unsupported format\")\n            raise SyntaxError(\"unknown pixel mode\")\n\n        if DEBUG:\n            print(\"- raw mode:\", rawmode)\n            print(\"- pil mode:\", self.mode)\n\n        self.info[\"compression\"] = self._compression\n\n        xres = self.tag_v2.get(X_RESOLUTION, 1)\n        yres = self.tag_v2.get(Y_RESOLUTION, 1)\n\n        if xres and yres:\n            resunit = self.tag_v2.get(RESOLUTION_UNIT, 1)\n            if resunit == 2:  # dots per inch\n                self.info[\"dpi\"] = xres, yres\n            elif resunit == 3:  # dots per centimeter. convert to dpi\n                self.info[\"dpi\"] = xres * 2.54, yres * 2.54\n            else:  # No absolute unit of measurement\n                self.info[\"resolution\"] = xres, yres\n\n        # build tile descriptors\n        x = y = l = 0\n        self.tile = []\n        self.use_load_libtiff = False\n        if STRIPOFFSETS in self.tag_v2:\n            # striped image\n            offsets = self.tag_v2[STRIPOFFSETS]\n            h = self.tag_v2.get(ROWSPERSTRIP, ysize)\n            w = self.size[0]\n            if READ_LIBTIFF or self._compression in [\"tiff_ccitt\", \"group3\",\n                                                     \"group4\", \"tiff_jpeg\",\n                                                     \"tiff_adobe_deflate\",\n                                                     \"tiff_thunderscan\",\n                                                     \"tiff_deflate\",\n                                                     \"tiff_sgilog\",\n                                                     \"tiff_sgilog24\",\n                                                     \"tiff_raw_16\"]:\n                # if DEBUG:\n                #     print(\"Activating g4 compression for whole file\")\n\n                # Decoder expects entire file as one tile.\n                # There's a buffer size limit in load (64k)\n                # so large g4 images will fail if we use that\n                # function.\n                #\n                # Setup the one tile for the whole image, then\n                # use the _load_libtiff function.\n\n                self.use_load_libtiff = True\n\n                # libtiff handles the fillmode for us, so 1;IR should\n                # actually be 1;I. Including the R double reverses the\n                # bits, so stripes of the image are reversed.  See\n                # https://github.com/python-pillow/Pillow/issues/279\n                if fillorder == 2:\n                    key = (\n                        self.tag_v2.prefix, photo, sampleFormat, 1,\n                        self.tag_v2.get(BITSPERSAMPLE, (1,)),\n                        self.tag_v2.get(EXTRASAMPLES, ())\n                        )\n                    if DEBUG:\n                        print(\"format key:\", key)\n                    # this should always work, since all the\n                    # fillorder==2 modes have a corresponding\n                    # fillorder=1 mode\n                    self.mode, rawmode = OPEN_INFO[key]\n                # libtiff always returns the bytes in native order.\n                # we're expecting image byte order. So, if the rawmode\n                # contains I;16, we need to convert from native to image\n                # byte order.\n                if self.mode in ('I;16B', 'I;16') and 'I;16' in rawmode:\n                    rawmode = 'I;16N'\n\n                # Offset in the tile tuple is 0, we go from 0,0 to\n                # w,h, and we only do this once -- eds\n                a = (rawmode, self._compression, False)\n                self.tile.append(\n                    (self._compression,\n                     (0, 0, w, ysize),\n                     0, a))\n                a = None\n\n            else:\n                for i, offset in enumerate(offsets):\n                    a = self._decoder(rawmode, l, i)\n                    self.tile.append(\n                        (self._compression,\n                            (0, min(y, ysize), w, min(y+h, ysize)),\n                            offset, a))\n                    if DEBUG:\n                        print(\"tiles: \", self.tile)\n                    y = y + h\n                    if y >= self.size[1]:\n                        x = y = 0\n                        l += 1\n                    a = None\n        elif TILEOFFSETS in self.tag_v2:\n            # tiled image\n            w = self.tag_v2.get(322)\n            h = self.tag_v2.get(323)\n            a = None\n            for o in self.tag_v2[TILEOFFSETS]:\n                if not a:\n                    a = self._decoder(rawmode, l)\n                # FIXME: this doesn't work if the image size\n                # is not a multiple of the tile size...\n                self.tile.append(\n                    (self._compression,\n                        (x, y, x+w, y+h),\n                        o, a))\n                x = x + w\n                if x >= self.size[0]:\n                    x, y = 0, y + h\n                    if y >= self.size[1]:\n                        x = y = 0\n                        l += 1\n                        a = None\n        else:\n            if DEBUG:\n                print(\"- unsupported data organization\")\n            raise SyntaxError(\"unknown data organization\")\n\n        # Fix up info.\n        if ICCPROFILE in self.tag_v2:\n            self.info['icc_profile'] = self.tag_v2[ICCPROFILE]\n\n        # fixup palette descriptor\n\n        if self.mode == \"P\":\n            palette = [o8(b // 256) for b in self.tag_v2[COLORMAP]]\n            self.palette = ImagePalette.raw(\"RGB;L\", b\"\".join(palette))",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 883,
                            "end_lineno": 1284,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "from __future__ import print_function\nimport logging\nfrom io import BytesIO\nimport struct\n\nfrom helper import unittest, PillowTestCase, hopper, py3\n\nfrom PIL import Image, TiffImagePlugin\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestFileTiff(PillowTestCase):\n\n    def test_sanity(self):\n\n        filename = self.tempfile(\"temp.tif\")\n\n        hopper(\"RGB\").save(filename)\n\n        im = Image.open(filename)\n        im.load()\n        self.assertEqual(im.mode, \"RGB\")\n        self.assertEqual(im.size, (128, 128))\n        self.assertEqual(im.format, \"TIFF\")\n\n        hopper(\"1\").save(filename)\n        im = Image.open(filename)\n\n        hopper(\"L\").save(filename)\n        im = Image.open(filename)\n\n        hopper(\"P\").save(filename)\n        im = Image.open(filename)\n\n        hopper(\"RGB\").save(filename)\n        im = Image.open(filename)\n\n        hopper(\"I\").save(filename)\n        im = Image.open(filename)\n\n    def test_mac_tiff(self):\n        # Read RGBa images from macOS [@PIL136]\n\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n\n        self.assertEqual(im.mode, \"RGBA\")\n        self.assertEqual(im.size, (55, 43))\n        self.assertEqual(im.tile, [('raw', (0, 0, 55, 43), 8, ('RGBa', 0, 1))])\n        im.load()\n\n    def test_gimp_tiff(self):\n        # Read TIFF JPEG images from GIMP [@PIL168]\n\n        codecs = dir(Image.core)\n        if \"jpeg_decoder\" not in codecs:\n            self.skipTest(\"jpeg support not available\")\n\n        filename = \"Tests/images/pil168.tif\"\n        im = Image.open(filename)\n\n        self.assertEqual(im.mode, \"RGB\")\n        self.assertEqual(im.size, (256, 256))\n        self.assertEqual(\n            im.tile, [\n                ('jpeg', (0, 0, 256, 64), 8, ('RGB', '')),\n                ('jpeg', (0, 64, 256, 128), 1215, ('RGB', '')),\n                ('jpeg', (0, 128, 256, 192), 2550, ('RGB', '')),\n                ('jpeg', (0, 192, 256, 256), 3890, ('RGB', '')),\n                ])\n        im.load()\n\n    def test_sampleformat(self):\n        # https://github.com/python-pillow/Pillow/issues/1466\n        im = Image.open(\"Tests/images/copyleft.tiff\")\n        self.assertEqual(im.mode, 'RGB')\n\n    def test_xyres_tiff(self):\n        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION\n        filename = \"Tests/images/pil168.tif\"\n        im = Image.open(filename)\n\n        # legacy api\n        self.assertIsInstance(im.tag[X_RESOLUTION][0], tuple)\n        self.assertIsInstance(im.tag[Y_RESOLUTION][0], tuple)\n\n        # v2 api\n        self.assertIsInstance(im.tag_v2[X_RESOLUTION],\n                              TiffImagePlugin.IFDRational)\n        self.assertIsInstance(im.tag_v2[Y_RESOLUTION],\n                              TiffImagePlugin.IFDRational)\n\n        self.assertEqual(im.info['dpi'], (72., 72.))\n\n    def test_int_resolution(self):\n        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION\n        filename = \"Tests/images/pil168.tif\"\n        im = Image.open(filename)\n\n        # Try to read a file where X,Y_RESOLUTION are ints\n        im.tag_v2[X_RESOLUTION] = 71\n        im.tag_v2[Y_RESOLUTION] = 71\n        im._setup()\n        self.assertEqual(im.info['dpi'], (71., 71.))\n\n    def test_save_setting_missing_resolution(self):\n        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION\n        b = BytesIO()\n        Image.open(\"Tests/images/10ct_32bit_128.tiff\").save(\n            b, format=\"tiff\", resolution=123.45)\n        im = Image.open(b)\n        self.assertEqual(float(im.tag_v2[X_RESOLUTION]), 123.45)\n        self.assertEqual(float(im.tag_v2[Y_RESOLUTION]), 123.45)\n\n    def test_invalid_file(self):\n        invalid_file = \"Tests/images/flower.jpg\"\n\n        self.assertRaises(SyntaxError,\n                          lambda: TiffImagePlugin.TiffImageFile(invalid_file))\n\n        TiffImagePlugin.PREFIXES.append(b\"\\xff\\xd8\\xff\\xe0\")\n        self.assertRaises(SyntaxError,\n                          lambda: TiffImagePlugin.TiffImageFile(invalid_file))\n        TiffImagePlugin.PREFIXES.pop()\n\n    def test_bad_exif(self):\n        i = Image.open('Tests/images/hopper_bad_exif.jpg')\n        try:\n            self.assert_warning(UserWarning, i._getexif)\n        except struct.error:\n            self.fail(\n                \"Bad EXIF data passed incorrect values to _binary unpack\")\n\n    def test_save_rgba(self):\n        im = hopper(\"RGBA\")\n        outfile = self.tempfile(\"temp.tif\")\n        im.save(outfile)\n\n    def test_save_unsupported_mode(self):\n        im = hopper(\"HSV\")\n        outfile = self.tempfile(\"temp.tif\")\n        self.assertRaises(IOError, lambda: im.save(outfile))\n\n    def test_little_endian(self):\n        im = Image.open('Tests/images/16bit.cropped.tif')\n        self.assertEqual(im.getpixel((0, 0)), 480)\n        self.assertEqual(im.mode, 'I;16')\n\n        b = im.tobytes()\n        # Bytes are in image native order (little endian)\n        if py3:\n            self.assertEqual(b[0], ord(b'\\xe0'))\n            self.assertEqual(b[1], ord(b'\\x01'))\n        else:\n            self.assertEqual(b[0], b'\\xe0')\n            self.assertEqual(b[1], b'\\x01')\n\n    def test_big_endian(self):\n        im = Image.open('Tests/images/16bit.MM.cropped.tif')\n        self.assertEqual(im.getpixel((0, 0)), 480)\n        self.assertEqual(im.mode, 'I;16B')\n\n        b = im.tobytes()\n\n        # Bytes are in image native order (big endian)\n        if py3:\n            self.assertEqual(b[0], ord(b'\\x01'))\n            self.assertEqual(b[1], ord(b'\\xe0'))\n        else:\n            self.assertEqual(b[0], b'\\x01')\n            self.assertEqual(b[1], b'\\xe0')\n\n    def test_12bit_rawmode(self):\n        \"\"\" Are we generating the same interpretation\n        of the image as Imagemagick is? \"\"\"\n\n        im = Image.open('Tests/images/12bit.cropped.tif')\n\n        # to make the target --\n        # convert 12bit.cropped.tif -depth 16 tmp.tif\n        # convert tmp.tif -evaluate RightShift 4 12in16bit2.tif\n        # imagemagick will auto scale so that a 12bit FFF is 16bit FFF0,\n        # so we need to unshift so that the integer values are the same.\n\n        im2 = Image.open('Tests/images/12in16bit.tif')\n\n        logger.debug(\"%s\", [img.getpixel((0, idx))\n                            for img in [im, im2] for idx in range(3)])\n\n        self.assert_image_equal(im, im2)\n\n    def test_32bit_float(self):\n        # Issue 614, specific 32-bit float format\n        path = 'Tests/images/10ct_32bit_128.tiff'\n        im = Image.open(path)\n        im.load()\n\n        self.assertEqual(im.getpixel((0, 0)), -0.4526388943195343)\n        self.assertEqual(\n            im.getextrema(), (-3.140936851501465, 3.140684127807617))\n\n    def test_n_frames(self):\n        im = Image.open('Tests/images/multipage-lastframe.tif')\n        self.assertEqual(im.n_frames, 1)\n        self.assertFalse(im.is_animated)\n\n        im = Image.open('Tests/images/multipage.tiff')\n        self.assertEqual(im.n_frames, 3)\n        self.assertTrue(im.is_animated)\n\n    def test_eoferror(self):\n        im = Image.open('Tests/images/multipage-lastframe.tif')\n\n        n_frames = im.n_frames\n        while True:\n            n_frames -= 1\n            try:\n                im.seek(n_frames)\n                break\n            except EOFError:\n                self.assertTrue(im.tell() < n_frames)\n\n    def test_multipage(self):\n        # issue #862\n        im = Image.open('Tests/images/multipage.tiff')\n        # file is a multipage tiff: 10x10 green, 10x10 red, 20x20 blue\n\n        im.seek(0)\n        self.assertEqual(im.size, (10, 10))\n        self.assertEqual(im.convert('RGB').getpixel((0, 0)), (0, 128, 0))\n\n        im.seek(1)\n        im.load()\n        self.assertEqual(im.size, (10, 10))\n        self.assertEqual(im.convert('RGB').getpixel((0, 0)), (255, 0, 0))\n\n        im.seek(2)\n        im.load()\n        self.assertEqual(im.size, (20, 20))\n        self.assertEqual(im.convert('RGB').getpixel((0, 0)), (0, 0, 255))\n\n    def test_multipage_last_frame(self):\n        im = Image.open('Tests/images/multipage-lastframe.tif')\n        im.load()\n        self.assertEqual(im.size, (20, 20))\n        self.assertEqual(im.convert('RGB').getpixel((0, 0)), (0, 0, 255))\n\n    def test___str__(self):\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n\n        # Act\n        ret = str(im.ifd)\n\n        # Assert\n        self.assertIsInstance(ret, str)\n\n    def test_as_dict_deprecation(self):\n        # Arrange\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n\n        self.assert_warning(DeprecationWarning, im.tag_v2.as_dict)\n        self.assert_warning(DeprecationWarning, im.tag.as_dict)\n        self.assertEqual(dict(im.tag_v2), im.tag_v2.as_dict())\n        self.assertEqual(dict(im.tag), im.tag.as_dict())\n\n    def test_dict(self):\n        # Arrange\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n\n        # v2 interface\n        v2_tags = {256: 55, 257: 43, 258: (8, 8, 8, 8), 259: 1,\n                   262: 2, 296: 2, 273: (8,), 338: (1,), 277: 4,\n                   279: (9460,), 282: 72.0, 283: 72.0, 284: 1}\n        self.assertEqual(dict(im.tag_v2), v2_tags)\n\n        # legacy interface\n        legacy_tags = {256: (55,), 257: (43,), 258: (8, 8, 8, 8), 259: (1,),\n                       262: (2,), 296: (2,), 273: (8,), 338: (1,), 277: (4,),\n                       279: (9460,), 282: ((720000, 10000),),\n                       283: ((720000, 10000),), 284: (1,)}\n        self.assertEqual(dict(im.tag), legacy_tags)\n\n    def test__delitem__(self):\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n        len_before = len(dict(im.ifd))\n        del im.ifd[256]\n        len_after = len(dict(im.ifd))\n        self.assertEqual(len_before, len_after + 1)\n\n    def test_load_byte(self):\n        for legacy_api in [False, True]:\n            ifd = TiffImagePlugin.ImageFileDirectory_v2()\n            data = b\"abc\"\n            ret = ifd.load_byte(data, legacy_api)\n            self.assertEqual(ret, b\"abc\")\n\n    def test_load_string(self):\n        ifd = TiffImagePlugin.ImageFileDirectory_v2()\n        data = b\"abc\\0\"\n        ret = ifd.load_string(data, False)\n        self.assertEqual(ret, \"abc\")\n\n    def test_load_float(self):\n        ifd = TiffImagePlugin.ImageFileDirectory_v2()\n        data = b\"abcdabcd\"\n        ret = ifd.load_float(data, False)\n        self.assertEqual(ret, (1.6777999408082104e+22, 1.6777999408082104e+22))\n\n    def test_load_double(self):\n        ifd = TiffImagePlugin.ImageFileDirectory_v2()\n        data = b\"abcdefghabcdefgh\"\n        ret = ifd.load_double(data, False)\n        self.assertEqual(ret, (8.540883223036124e+194, 8.540883223036124e+194))\n\n    def test_seek(self):\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n        im.seek(-1)\n        self.assertEqual(im.tell(), 0)\n\n    def test_seek_eof(self):\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n        self.assertEqual(im.tell(), 0)\n        self.assertRaises(EOFError, lambda: im.seek(1))\n\n    def test__limit_rational_int(self):\n        from PIL.TiffImagePlugin import _limit_rational\n        value = 34\n        ret = _limit_rational(value, 65536)\n        self.assertEqual(ret, (34, 1))\n\n    def test__limit_rational_float(self):\n        from PIL.TiffImagePlugin import _limit_rational\n        value = 22.3\n        ret = _limit_rational(value, 65536)\n        self.assertEqual(ret, (223, 10))\n\n    def test_4bit(self):\n        test_file = \"Tests/images/hopper_gray_4bpp.tif\"\n        original = hopper(\"L\")\n        im = Image.open(test_file)\n        self.assertEqual(im.size, (128, 128))\n        self.assertEqual(im.mode, \"L\")\n        self.assert_image_similar(im, original, 7.3)\n\n    def test_gray_semibyte_per_pixel(self):\n        test_files = (\n            (\n                24.8,  # epsilon\n                (  # group\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper2.tif\",\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper2I.tif\",\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper2R.tif\",\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper2IR.tif\",\n                )\n            ),\n            (\n                7.3,  # epsilon\n                (  # group\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper4.tif\",\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper4I.tif\",\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper4R.tif\",\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper4IR.tif\",\n                )\n            ),\n        )\n        original = hopper(\"L\")\n        for epsilon, group in test_files:\n            im = Image.open(group[0])\n            self.assertEqual(im.size, (128, 128))\n            self.assertEqual(im.mode, \"L\")\n            self.assert_image_similar(im, original, epsilon)\n            for file in group[1:]:\n                im2 = Image.open(file)\n                self.assertEqual(im2.size, (128, 128))\n                self.assertEqual(im2.mode, \"L\")\n                self.assert_image_equal(im, im2)\n\n    def test_with_underscores(self):\n        kwargs = {'resolution_unit': 'inch',\n                  'x_resolution': 72,\n                  'y_resolution': 36}\n        filename = self.tempfile(\"temp.tif\")\n        hopper(\"RGB\").save(filename, **kwargs)\n        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION\n        im = Image.open(filename)\n\n        # legacy interface\n        self.assertEqual(im.tag[X_RESOLUTION][0][0], 72)\n        self.assertEqual(im.tag[Y_RESOLUTION][0][0], 36)\n\n        # v2 interface\n        self.assertEqual(im.tag_v2[X_RESOLUTION], 72)\n        self.assertEqual(im.tag_v2[Y_RESOLUTION], 36)\n\n    def test_deprecation_warning_with_spaces(self):\n        kwargs = {'resolution unit': 'inch',\n                  'x resolution': 36,\n                  'y resolution': 72}\n        filename = self.tempfile(\"temp.tif\")\n        self.assert_warning(DeprecationWarning,\n                            lambda: hopper(\"RGB\").save(filename, **kwargs))\n        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION\n\n        im = Image.open(filename)\n\n        # legacy interface\n        self.assertEqual(im.tag[X_RESOLUTION][0][0], 36)\n        self.assertEqual(im.tag[Y_RESOLUTION][0][0], 72)\n\n        # v2 interface\n        self.assertEqual(im.tag_v2[X_RESOLUTION], 36)\n        self.assertEqual(im.tag_v2[Y_RESOLUTION], 72)\n\n    def test_lzw(self):\n        # Act\n        im = Image.open(\"Tests/images/hopper_lzw.tif\")\n\n        # Assert\n        self.assertEqual(im.mode, 'RGB')\n        self.assertEqual(im.size, (128, 128))\n        self.assertEqual(im.format, \"TIFF\")\n        im2 = hopper()\n        self.assert_image_similar(im, im2, 5)\n\n    def test_roundtrip_tiff_uint16(self):\n        # Test an image of all '0' values\n        pixel_value = 0x1234\n        infile = \"Tests/images/uint16_1_4660.tif\"\n        im = Image.open(infile)\n        self.assertEqual(im.getpixel((0, 0)), pixel_value)\n\n        tmpfile = self.tempfile(\"temp.tif\")\n        im.save(tmpfile)\n\n        reloaded = Image.open(tmpfile)\n\n        self.assert_image_equal(im, reloaded)\n\n    def test_tiff_save_all(self):\n        import io\n        import os\n\n        mp = io.BytesIO()\n        with Image.open(\"Tests/images/multipage.tiff\") as im:\n            im.save(mp, format=\"tiff\", save_all=True)\n\n        mp.seek(0, os.SEEK_SET)\n        with Image.open(mp) as im:\n            self.assertEqual(im.n_frames, 3)\n\n    def test_saving_icc_profile(self):\n        # Tests saving TIFF with icc_profile set.\n        # At the time of writing this will only work for non-compressed tiffs\n        # as libtiff does not support embedded ICC profiles, ImageFile._save(..)\n        # however does.\n        im = Image.new('RGB', (1, 1))\n        im.info['icc_profile'] = 'Dummy value'\n        \n        # Try save-load round trip to make sure both handle icc_profile.\n        tmpfile = self.tempfile('temp.tif')\n        im.save(tmpfile, 'TIFF', compression='raw')\n        reloaded = Image.open(tmpfile)\n        \n        self.assertEqual(b'Dummy value', reloaded.info['icc_profile'])\n\n\nif __name__ == '__main__':\n    unittest.main()\n",
            "new_file_content": "from __future__ import print_function\nimport logging\nfrom io import BytesIO\nimport struct\n\nfrom helper import unittest, PillowTestCase, hopper, py3\n\nfrom PIL import Image, TiffImagePlugin\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestFileTiff(PillowTestCase):\n\n    def test_sanity(self):\n\n        filename = self.tempfile(\"temp.tif\")\n\n        hopper(\"RGB\").save(filename)\n\n        im = Image.open(filename)\n        im.load()\n        self.assertEqual(im.mode, \"RGB\")\n        self.assertEqual(im.size, (128, 128))\n        self.assertEqual(im.format, \"TIFF\")\n\n        hopper(\"1\").save(filename)\n        im = Image.open(filename)\n\n        hopper(\"L\").save(filename)\n        im = Image.open(filename)\n\n        hopper(\"P\").save(filename)\n        im = Image.open(filename)\n\n        hopper(\"RGB\").save(filename)\n        im = Image.open(filename)\n\n        hopper(\"I\").save(filename)\n        im = Image.open(filename)\n\n    def test_mac_tiff(self):\n        # Read RGBa images from macOS [@PIL136]\n\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n\n        self.assertEqual(im.mode, \"RGBA\")\n        self.assertEqual(im.size, (55, 43))\n        self.assertEqual(im.tile, [('raw', (0, 0, 55, 43), 8, ('RGBa', 0, 1))])\n        im.load()\n\n    def test_gimp_tiff(self):\n        # Read TIFF JPEG images from GIMP [@PIL168]\n\n        codecs = dir(Image.core)\n        if \"jpeg_decoder\" not in codecs:\n            self.skipTest(\"jpeg support not available\")\n\n        filename = \"Tests/images/pil168.tif\"\n        im = Image.open(filename)\n\n        self.assertEqual(im.mode, \"RGB\")\n        self.assertEqual(im.size, (256, 256))\n        self.assertEqual(\n            im.tile, [\n                ('jpeg', (0, 0, 256, 64), 8, ('RGB', '')),\n                ('jpeg', (0, 64, 256, 128), 1215, ('RGB', '')),\n                ('jpeg', (0, 128, 256, 192), 2550, ('RGB', '')),\n                ('jpeg', (0, 192, 256, 256), 3890, ('RGB', '')),\n                ])\n        im.load()\n\n    def test_sampleformat(self):\n        # https://github.com/python-pillow/Pillow/issues/1466\n        im = Image.open(\"Tests/images/copyleft.tiff\")\n        self.assertEqual(im.mode, 'RGB')\n\n    def test_xyres_tiff(self):\n        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION\n        filename = \"Tests/images/pil168.tif\"\n        im = Image.open(filename)\n\n        # legacy api\n        self.assertIsInstance(im.tag[X_RESOLUTION][0], tuple)\n        self.assertIsInstance(im.tag[Y_RESOLUTION][0], tuple)\n\n        # v2 api\n        self.assertIsInstance(im.tag_v2[X_RESOLUTION],\n                              TiffImagePlugin.IFDRational)\n        self.assertIsInstance(im.tag_v2[Y_RESOLUTION],\n                              TiffImagePlugin.IFDRational)\n\n        self.assertEqual(im.info['dpi'], (72., 72.))\n\n    def test_xyres_fallback_tiff(self):\n        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION, RESOLUTION_UNIT\n        filename = \"Tests/images/compression.tif\"\n        im = Image.open(filename)\n\n        # v2 api\n        self.assertIsInstance(im.tag_v2[X_RESOLUTION],\n                              TiffImagePlugin.IFDRational)\n        self.assertIsInstance(im.tag_v2[Y_RESOLUTION],\n                              TiffImagePlugin.IFDRational)\n        self.assertRaises(KeyError,\n                          lambda: im.tag_v2[RESOLUTION_UNIT])\n\n        # Legacy.\n        self.assertEqual(im.info['resolution'], (100., 100.))\n        # Fallback \"inch\".\n        self.assertEqual(im.info['dpi'], (100., 100.))\n\n    def test_int_resolution(self):\n        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION\n        filename = \"Tests/images/pil168.tif\"\n        im = Image.open(filename)\n\n        # Try to read a file where X,Y_RESOLUTION are ints\n        im.tag_v2[X_RESOLUTION] = 71\n        im.tag_v2[Y_RESOLUTION] = 71\n        im._setup()\n        self.assertEqual(im.info['dpi'], (71., 71.))\n\n    def test_save_setting_missing_resolution(self):\n        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION\n        b = BytesIO()\n        Image.open(\"Tests/images/10ct_32bit_128.tiff\").save(\n            b, format=\"tiff\", resolution=123.45)\n        im = Image.open(b)\n        self.assertEqual(float(im.tag_v2[X_RESOLUTION]), 123.45)\n        self.assertEqual(float(im.tag_v2[Y_RESOLUTION]), 123.45)\n\n    def test_invalid_file(self):\n        invalid_file = \"Tests/images/flower.jpg\"\n\n        self.assertRaises(SyntaxError,\n                          lambda: TiffImagePlugin.TiffImageFile(invalid_file))\n\n        TiffImagePlugin.PREFIXES.append(b\"\\xff\\xd8\\xff\\xe0\")\n        self.assertRaises(SyntaxError,\n                          lambda: TiffImagePlugin.TiffImageFile(invalid_file))\n        TiffImagePlugin.PREFIXES.pop()\n\n    def test_bad_exif(self):\n        i = Image.open('Tests/images/hopper_bad_exif.jpg')\n        try:\n            self.assert_warning(UserWarning, i._getexif)\n        except struct.error:\n            self.fail(\n                \"Bad EXIF data passed incorrect values to _binary unpack\")\n\n    def test_save_rgba(self):\n        im = hopper(\"RGBA\")\n        outfile = self.tempfile(\"temp.tif\")\n        im.save(outfile)\n\n    def test_save_unsupported_mode(self):\n        im = hopper(\"HSV\")\n        outfile = self.tempfile(\"temp.tif\")\n        self.assertRaises(IOError, lambda: im.save(outfile))\n\n    def test_little_endian(self):\n        im = Image.open('Tests/images/16bit.cropped.tif')\n        self.assertEqual(im.getpixel((0, 0)), 480)\n        self.assertEqual(im.mode, 'I;16')\n\n        b = im.tobytes()\n        # Bytes are in image native order (little endian)\n        if py3:\n            self.assertEqual(b[0], ord(b'\\xe0'))\n            self.assertEqual(b[1], ord(b'\\x01'))\n        else:\n            self.assertEqual(b[0], b'\\xe0')\n            self.assertEqual(b[1], b'\\x01')\n\n    def test_big_endian(self):\n        im = Image.open('Tests/images/16bit.MM.cropped.tif')\n        self.assertEqual(im.getpixel((0, 0)), 480)\n        self.assertEqual(im.mode, 'I;16B')\n\n        b = im.tobytes()\n\n        # Bytes are in image native order (big endian)\n        if py3:\n            self.assertEqual(b[0], ord(b'\\x01'))\n            self.assertEqual(b[1], ord(b'\\xe0'))\n        else:\n            self.assertEqual(b[0], b'\\x01')\n            self.assertEqual(b[1], b'\\xe0')\n\n    def test_12bit_rawmode(self):\n        \"\"\" Are we generating the same interpretation\n        of the image as Imagemagick is? \"\"\"\n\n        im = Image.open('Tests/images/12bit.cropped.tif')\n\n        # to make the target --\n        # convert 12bit.cropped.tif -depth 16 tmp.tif\n        # convert tmp.tif -evaluate RightShift 4 12in16bit2.tif\n        # imagemagick will auto scale so that a 12bit FFF is 16bit FFF0,\n        # so we need to unshift so that the integer values are the same.\n\n        im2 = Image.open('Tests/images/12in16bit.tif')\n\n        logger.debug(\"%s\", [img.getpixel((0, idx))\n                            for img in [im, im2] for idx in range(3)])\n\n        self.assert_image_equal(im, im2)\n\n    def test_32bit_float(self):\n        # Issue 614, specific 32-bit float format\n        path = 'Tests/images/10ct_32bit_128.tiff'\n        im = Image.open(path)\n        im.load()\n\n        self.assertEqual(im.getpixel((0, 0)), -0.4526388943195343)\n        self.assertEqual(\n            im.getextrema(), (-3.140936851501465, 3.140684127807617))\n\n    def test_n_frames(self):\n        im = Image.open('Tests/images/multipage-lastframe.tif')\n        self.assertEqual(im.n_frames, 1)\n        self.assertFalse(im.is_animated)\n\n        im = Image.open('Tests/images/multipage.tiff')\n        self.assertEqual(im.n_frames, 3)\n        self.assertTrue(im.is_animated)\n\n    def test_eoferror(self):\n        im = Image.open('Tests/images/multipage-lastframe.tif')\n\n        n_frames = im.n_frames\n        while True:\n            n_frames -= 1\n            try:\n                im.seek(n_frames)\n                break\n            except EOFError:\n                self.assertTrue(im.tell() < n_frames)\n\n    def test_multipage(self):\n        # issue #862\n        im = Image.open('Tests/images/multipage.tiff')\n        # file is a multipage tiff: 10x10 green, 10x10 red, 20x20 blue\n\n        im.seek(0)\n        self.assertEqual(im.size, (10, 10))\n        self.assertEqual(im.convert('RGB').getpixel((0, 0)), (0, 128, 0))\n\n        im.seek(1)\n        im.load()\n        self.assertEqual(im.size, (10, 10))\n        self.assertEqual(im.convert('RGB').getpixel((0, 0)), (255, 0, 0))\n\n        im.seek(2)\n        im.load()\n        self.assertEqual(im.size, (20, 20))\n        self.assertEqual(im.convert('RGB').getpixel((0, 0)), (0, 0, 255))\n\n    def test_multipage_last_frame(self):\n        im = Image.open('Tests/images/multipage-lastframe.tif')\n        im.load()\n        self.assertEqual(im.size, (20, 20))\n        self.assertEqual(im.convert('RGB').getpixel((0, 0)), (0, 0, 255))\n\n    def test___str__(self):\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n\n        # Act\n        ret = str(im.ifd)\n\n        # Assert\n        self.assertIsInstance(ret, str)\n\n    def test_as_dict_deprecation(self):\n        # Arrange\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n\n        self.assert_warning(DeprecationWarning, im.tag_v2.as_dict)\n        self.assert_warning(DeprecationWarning, im.tag.as_dict)\n        self.assertEqual(dict(im.tag_v2), im.tag_v2.as_dict())\n        self.assertEqual(dict(im.tag), im.tag.as_dict())\n\n    def test_dict(self):\n        # Arrange\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n\n        # v2 interface\n        v2_tags = {256: 55, 257: 43, 258: (8, 8, 8, 8), 259: 1,\n                   262: 2, 296: 2, 273: (8,), 338: (1,), 277: 4,\n                   279: (9460,), 282: 72.0, 283: 72.0, 284: 1}\n        self.assertEqual(dict(im.tag_v2), v2_tags)\n\n        # legacy interface\n        legacy_tags = {256: (55,), 257: (43,), 258: (8, 8, 8, 8), 259: (1,),\n                       262: (2,), 296: (2,), 273: (8,), 338: (1,), 277: (4,),\n                       279: (9460,), 282: ((720000, 10000),),\n                       283: ((720000, 10000),), 284: (1,)}\n        self.assertEqual(dict(im.tag), legacy_tags)\n\n    def test__delitem__(self):\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n        len_before = len(dict(im.ifd))\n        del im.ifd[256]\n        len_after = len(dict(im.ifd))\n        self.assertEqual(len_before, len_after + 1)\n\n    def test_load_byte(self):\n        for legacy_api in [False, True]:\n            ifd = TiffImagePlugin.ImageFileDirectory_v2()\n            data = b\"abc\"\n            ret = ifd.load_byte(data, legacy_api)\n            self.assertEqual(ret, b\"abc\")\n\n    def test_load_string(self):\n        ifd = TiffImagePlugin.ImageFileDirectory_v2()\n        data = b\"abc\\0\"\n        ret = ifd.load_string(data, False)\n        self.assertEqual(ret, \"abc\")\n\n    def test_load_float(self):\n        ifd = TiffImagePlugin.ImageFileDirectory_v2()\n        data = b\"abcdabcd\"\n        ret = ifd.load_float(data, False)\n        self.assertEqual(ret, (1.6777999408082104e+22, 1.6777999408082104e+22))\n\n    def test_load_double(self):\n        ifd = TiffImagePlugin.ImageFileDirectory_v2()\n        data = b\"abcdefghabcdefgh\"\n        ret = ifd.load_double(data, False)\n        self.assertEqual(ret, (8.540883223036124e+194, 8.540883223036124e+194))\n\n    def test_seek(self):\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n        im.seek(-1)\n        self.assertEqual(im.tell(), 0)\n\n    def test_seek_eof(self):\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n        self.assertEqual(im.tell(), 0)\n        self.assertRaises(EOFError, lambda: im.seek(1))\n\n    def test__limit_rational_int(self):\n        from PIL.TiffImagePlugin import _limit_rational\n        value = 34\n        ret = _limit_rational(value, 65536)\n        self.assertEqual(ret, (34, 1))\n\n    def test__limit_rational_float(self):\n        from PIL.TiffImagePlugin import _limit_rational\n        value = 22.3\n        ret = _limit_rational(value, 65536)\n        self.assertEqual(ret, (223, 10))\n\n    def test_4bit(self):\n        test_file = \"Tests/images/hopper_gray_4bpp.tif\"\n        original = hopper(\"L\")\n        im = Image.open(test_file)\n        self.assertEqual(im.size, (128, 128))\n        self.assertEqual(im.mode, \"L\")\n        self.assert_image_similar(im, original, 7.3)\n\n    def test_gray_semibyte_per_pixel(self):\n        test_files = (\n            (\n                24.8,  # epsilon\n                (  # group\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper2.tif\",\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper2I.tif\",\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper2R.tif\",\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper2IR.tif\",\n                )\n            ),\n            (\n                7.3,  # epsilon\n                (  # group\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper4.tif\",\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper4I.tif\",\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper4R.tif\",\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper4IR.tif\",\n                )\n            ),\n        )\n        original = hopper(\"L\")\n        for epsilon, group in test_files:\n            im = Image.open(group[0])\n            self.assertEqual(im.size, (128, 128))\n            self.assertEqual(im.mode, \"L\")\n            self.assert_image_similar(im, original, epsilon)\n            for file in group[1:]:\n                im2 = Image.open(file)\n                self.assertEqual(im2.size, (128, 128))\n                self.assertEqual(im2.mode, \"L\")\n                self.assert_image_equal(im, im2)\n\n    def test_with_underscores(self):\n        kwargs = {'resolution_unit': 'inch',\n                  'x_resolution': 72,\n                  'y_resolution': 36}\n        filename = self.tempfile(\"temp.tif\")\n        hopper(\"RGB\").save(filename, **kwargs)\n        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION\n        im = Image.open(filename)\n\n        # legacy interface\n        self.assertEqual(im.tag[X_RESOLUTION][0][0], 72)\n        self.assertEqual(im.tag[Y_RESOLUTION][0][0], 36)\n\n        # v2 interface\n        self.assertEqual(im.tag_v2[X_RESOLUTION], 72)\n        self.assertEqual(im.tag_v2[Y_RESOLUTION], 36)\n\n    def test_deprecation_warning_with_spaces(self):\n        kwargs = {'resolution unit': 'inch',\n                  'x resolution': 36,\n                  'y resolution': 72}\n        filename = self.tempfile(\"temp.tif\")\n        self.assert_warning(DeprecationWarning,\n                            lambda: hopper(\"RGB\").save(filename, **kwargs))\n        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION\n\n        im = Image.open(filename)\n\n        # legacy interface\n        self.assertEqual(im.tag[X_RESOLUTION][0][0], 36)\n        self.assertEqual(im.tag[Y_RESOLUTION][0][0], 72)\n\n        # v2 interface\n        self.assertEqual(im.tag_v2[X_RESOLUTION], 36)\n        self.assertEqual(im.tag_v2[Y_RESOLUTION], 72)\n\n    def test_lzw(self):\n        # Act\n        im = Image.open(\"Tests/images/hopper_lzw.tif\")\n\n        # Assert\n        self.assertEqual(im.mode, 'RGB')\n        self.assertEqual(im.size, (128, 128))\n        self.assertEqual(im.format, \"TIFF\")\n        im2 = hopper()\n        self.assert_image_similar(im, im2, 5)\n\n    def test_roundtrip_tiff_uint16(self):\n        # Test an image of all '0' values\n        pixel_value = 0x1234\n        infile = \"Tests/images/uint16_1_4660.tif\"\n        im = Image.open(infile)\n        self.assertEqual(im.getpixel((0, 0)), pixel_value)\n\n        tmpfile = self.tempfile(\"temp.tif\")\n        im.save(tmpfile)\n\n        reloaded = Image.open(tmpfile)\n\n        self.assert_image_equal(im, reloaded)\n\n    def test_tiff_save_all(self):\n        import io\n        import os\n\n        mp = io.BytesIO()\n        with Image.open(\"Tests/images/multipage.tiff\") as im:\n            im.save(mp, format=\"tiff\", save_all=True)\n\n        mp.seek(0, os.SEEK_SET)\n        with Image.open(mp) as im:\n            self.assertEqual(im.n_frames, 3)\n\n    def test_saving_icc_profile(self):\n        # Tests saving TIFF with icc_profile set.\n        # At the time of writing this will only work for non-compressed tiffs\n        # as libtiff does not support embedded ICC profiles, ImageFile._save(..)\n        # however does.\n        im = Image.new('RGB', (1, 1))\n        im.info['icc_profile'] = 'Dummy value'\n        \n        # Try save-load round trip to make sure both handle icc_profile.\n        tmpfile = self.tempfile('temp.tif')\n        im.save(tmpfile, 'TIFF', compression='raw')\n        reloaded = Image.open(tmpfile)\n        \n        self.assertEqual(b'Dummy value', reloaded.info['icc_profile'])\n\n\nif __name__ == '__main__':\n    unittest.main()\n",
            "header": {
                "file": {
                    "path": "Tests/test_file_tiff.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "bf19947a1",
                "new_commit_hash": "1fe3ad45e",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/Tests/test_file_tiff.py"
            },
            "plus_file": {
                "path": "b/Tests/test_file_tiff.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 93,
                            "length": 6
                        },
                        "new_range": {
                            "start": 93,
                            "length": 24
                        },
                        "section": "class TestFileTiff(PillowTestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertEqual(im.info['dpi'], (72., 72.))",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def test_xyres_fallback_tiff(self):",
                                "type": "added"
                            },
                            {
                                "content": "        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION, RESOLUTION_UNIT",
                                "type": "added"
                            },
                            {
                                "content": "        filename = \"Tests/images/compression.tif\"",
                                "type": "added"
                            },
                            {
                                "content": "        im = Image.open(filename)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        # v2 api",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertIsInstance(im.tag_v2[X_RESOLUTION],",
                                "type": "added"
                            },
                            {
                                "content": "                              TiffImagePlugin.IFDRational)",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertIsInstance(im.tag_v2[Y_RESOLUTION],",
                                "type": "added"
                            },
                            {
                                "content": "                              TiffImagePlugin.IFDRational)",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertRaises(KeyError,",
                                "type": "added"
                            },
                            {
                                "content": "                          lambda: im.tag_v2[RESOLUTION_UNIT])",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        # Legacy.",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(im.info['resolution'], (100., 100.))",
                                "type": "added"
                            },
                            {
                                "content": "        # Fallback \"inch\".",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(im.info['dpi'], (100., 100.))",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def test_int_resolution(self):",
                                "type": "context"
                            },
                            {
                                "content": "        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION",
                                "type": "context"
                            },
                            {
                                "content": "        filename = \"Tests/images/pil168.tif\"",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Tests/test_file_tiff.py",
                            "type": "class",
                            "name": "TestFileTiff",
                            "content": "class TestFileTiff(PillowTestCase):\n\n    def test_sanity(self):\n\n        filename = self.tempfile(\"temp.tif\")\n\n        hopper(\"RGB\").save(filename)\n\n        im = Image.open(filename)\n        im.load()\n        self.assertEqual(im.mode, \"RGB\")\n        self.assertEqual(im.size, (128, 128))\n        self.assertEqual(im.format, \"TIFF\")\n\n        hopper(\"1\").save(filename)\n        im = Image.open(filename)\n\n        hopper(\"L\").save(filename)\n        im = Image.open(filename)\n\n        hopper(\"P\").save(filename)\n        im = Image.open(filename)\n\n        hopper(\"RGB\").save(filename)\n        im = Image.open(filename)\n\n        hopper(\"I\").save(filename)\n        im = Image.open(filename)\n\n    def test_mac_tiff(self):\n        # Read RGBa images from macOS [@PIL136]\n\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n\n        self.assertEqual(im.mode, \"RGBA\")\n        self.assertEqual(im.size, (55, 43))\n        self.assertEqual(im.tile, [('raw', (0, 0, 55, 43), 8, ('RGBa', 0, 1))])\n        im.load()\n\n    def test_gimp_tiff(self):\n        # Read TIFF JPEG images from GIMP [@PIL168]\n\n        codecs = dir(Image.core)\n        if \"jpeg_decoder\" not in codecs:\n            self.skipTest(\"jpeg support not available\")\n\n        filename = \"Tests/images/pil168.tif\"\n        im = Image.open(filename)\n\n        self.assertEqual(im.mode, \"RGB\")\n        self.assertEqual(im.size, (256, 256))\n        self.assertEqual(\n            im.tile, [\n                ('jpeg', (0, 0, 256, 64), 8, ('RGB', '')),\n                ('jpeg', (0, 64, 256, 128), 1215, ('RGB', '')),\n                ('jpeg', (0, 128, 256, 192), 2550, ('RGB', '')),\n                ('jpeg', (0, 192, 256, 256), 3890, ('RGB', '')),\n                ])\n        im.load()\n\n    def test_sampleformat(self):\n        # https://github.com/python-pillow/Pillow/issues/1466\n        im = Image.open(\"Tests/images/copyleft.tiff\")\n        self.assertEqual(im.mode, 'RGB')\n\n    def test_xyres_tiff(self):\n        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION\n        filename = \"Tests/images/pil168.tif\"\n        im = Image.open(filename)\n\n        # legacy api\n        self.assertIsInstance(im.tag[X_RESOLUTION][0], tuple)\n        self.assertIsInstance(im.tag[Y_RESOLUTION][0], tuple)\n\n        # v2 api\n        self.assertIsInstance(im.tag_v2[X_RESOLUTION],\n                              TiffImagePlugin.IFDRational)\n        self.assertIsInstance(im.tag_v2[Y_RESOLUTION],\n                              TiffImagePlugin.IFDRational)\n\n        self.assertEqual(im.info['dpi'], (72., 72.))\n\n    def test_xyres_fallback_tiff(self):\n        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION, RESOLUTION_UNIT\n        filename = \"Tests/images/compression.tif\"\n        im = Image.open(filename)\n\n        # v2 api\n        self.assertIsInstance(im.tag_v2[X_RESOLUTION],\n                              TiffImagePlugin.IFDRational)\n        self.assertIsInstance(im.tag_v2[Y_RESOLUTION],\n                              TiffImagePlugin.IFDRational)\n        self.assertRaises(KeyError,\n                          lambda: im.tag_v2[RESOLUTION_UNIT])\n\n        # Legacy.\n        self.assertEqual(im.info['resolution'], (100., 100.))\n        # Fallback \"inch\".\n        self.assertEqual(im.info['dpi'], (100., 100.))\n\n    def test_int_resolution(self):\n        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION\n        filename = \"Tests/images/pil168.tif\"\n        im = Image.open(filename)\n\n        # Try to read a file where X,Y_RESOLUTION are ints\n        im.tag_v2[X_RESOLUTION] = 71\n        im.tag_v2[Y_RESOLUTION] = 71\n        im._setup()\n        self.assertEqual(im.info['dpi'], (71., 71.))\n\n    def test_save_setting_missing_resolution(self):\n        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION\n        b = BytesIO()\n        Image.open(\"Tests/images/10ct_32bit_128.tiff\").save(\n            b, format=\"tiff\", resolution=123.45)\n        im = Image.open(b)\n        self.assertEqual(float(im.tag_v2[X_RESOLUTION]), 123.45)\n        self.assertEqual(float(im.tag_v2[Y_RESOLUTION]), 123.45)\n\n    def test_invalid_file(self):\n        invalid_file = \"Tests/images/flower.jpg\"\n\n        self.assertRaises(SyntaxError,\n                          lambda: TiffImagePlugin.TiffImageFile(invalid_file))\n\n        TiffImagePlugin.PREFIXES.append(b\"\\xff\\xd8\\xff\\xe0\")\n        self.assertRaises(SyntaxError,\n                          lambda: TiffImagePlugin.TiffImageFile(invalid_file))\n        TiffImagePlugin.PREFIXES.pop()\n\n    def test_bad_exif(self):\n        i = Image.open('Tests/images/hopper_bad_exif.jpg')\n        try:\n            self.assert_warning(UserWarning, i._getexif)\n        except struct.error:\n            self.fail(\n                \"Bad EXIF data passed incorrect values to _binary unpack\")\n\n    def test_save_rgba(self):\n        im = hopper(\"RGBA\")\n        outfile = self.tempfile(\"temp.tif\")\n        im.save(outfile)\n\n    def test_save_unsupported_mode(self):\n        im = hopper(\"HSV\")\n        outfile = self.tempfile(\"temp.tif\")\n        self.assertRaises(IOError, lambda: im.save(outfile))\n\n    def test_little_endian(self):\n        im = Image.open('Tests/images/16bit.cropped.tif')\n        self.assertEqual(im.getpixel((0, 0)), 480)\n        self.assertEqual(im.mode, 'I;16')\n\n        b = im.tobytes()\n        # Bytes are in image native order (little endian)\n        if py3:\n            self.assertEqual(b[0], ord(b'\\xe0'))\n            self.assertEqual(b[1], ord(b'\\x01'))\n        else:\n            self.assertEqual(b[0], b'\\xe0')\n            self.assertEqual(b[1], b'\\x01')\n\n    def test_big_endian(self):\n        im = Image.open('Tests/images/16bit.MM.cropped.tif')\n        self.assertEqual(im.getpixel((0, 0)), 480)\n        self.assertEqual(im.mode, 'I;16B')\n\n        b = im.tobytes()\n\n        # Bytes are in image native order (big endian)\n        if py3:\n            self.assertEqual(b[0], ord(b'\\x01'))\n            self.assertEqual(b[1], ord(b'\\xe0'))\n        else:\n            self.assertEqual(b[0], b'\\x01')\n            self.assertEqual(b[1], b'\\xe0')\n\n    def test_12bit_rawmode(self):\n        \"\"\" Are we generating the same interpretation\n        of the image as Imagemagick is? \"\"\"\n\n        im = Image.open('Tests/images/12bit.cropped.tif')\n\n        # to make the target --\n        # convert 12bit.cropped.tif -depth 16 tmp.tif\n        # convert tmp.tif -evaluate RightShift 4 12in16bit2.tif\n        # imagemagick will auto scale so that a 12bit FFF is 16bit FFF0,\n        # so we need to unshift so that the integer values are the same.\n\n        im2 = Image.open('Tests/images/12in16bit.tif')\n\n        logger.debug(\"%s\", [img.getpixel((0, idx))\n                            for img in [im, im2] for idx in range(3)])\n\n        self.assert_image_equal(im, im2)\n\n    def test_32bit_float(self):\n        # Issue 614, specific 32-bit float format\n        path = 'Tests/images/10ct_32bit_128.tiff'\n        im = Image.open(path)\n        im.load()\n\n        self.assertEqual(im.getpixel((0, 0)), -0.4526388943195343)\n        self.assertEqual(\n            im.getextrema(), (-3.140936851501465, 3.140684127807617))\n\n    def test_n_frames(self):\n        im = Image.open('Tests/images/multipage-lastframe.tif')\n        self.assertEqual(im.n_frames, 1)\n        self.assertFalse(im.is_animated)\n\n        im = Image.open('Tests/images/multipage.tiff')\n        self.assertEqual(im.n_frames, 3)\n        self.assertTrue(im.is_animated)\n\n    def test_eoferror(self):\n        im = Image.open('Tests/images/multipage-lastframe.tif')\n\n        n_frames = im.n_frames\n        while True:\n            n_frames -= 1\n            try:\n                im.seek(n_frames)\n                break\n            except EOFError:\n                self.assertTrue(im.tell() < n_frames)\n\n    def test_multipage(self):\n        # issue #862\n        im = Image.open('Tests/images/multipage.tiff')\n        # file is a multipage tiff: 10x10 green, 10x10 red, 20x20 blue\n\n        im.seek(0)\n        self.assertEqual(im.size, (10, 10))\n        self.assertEqual(im.convert('RGB').getpixel((0, 0)), (0, 128, 0))\n\n        im.seek(1)\n        im.load()\n        self.assertEqual(im.size, (10, 10))\n        self.assertEqual(im.convert('RGB').getpixel((0, 0)), (255, 0, 0))\n\n        im.seek(2)\n        im.load()\n        self.assertEqual(im.size, (20, 20))\n        self.assertEqual(im.convert('RGB').getpixel((0, 0)), (0, 0, 255))\n\n    def test_multipage_last_frame(self):\n        im = Image.open('Tests/images/multipage-lastframe.tif')\n        im.load()\n        self.assertEqual(im.size, (20, 20))\n        self.assertEqual(im.convert('RGB').getpixel((0, 0)), (0, 0, 255))\n\n    def test___str__(self):\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n\n        # Act\n        ret = str(im.ifd)\n\n        # Assert\n        self.assertIsInstance(ret, str)\n\n    def test_as_dict_deprecation(self):\n        # Arrange\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n\n        self.assert_warning(DeprecationWarning, im.tag_v2.as_dict)\n        self.assert_warning(DeprecationWarning, im.tag.as_dict)\n        self.assertEqual(dict(im.tag_v2), im.tag_v2.as_dict())\n        self.assertEqual(dict(im.tag), im.tag.as_dict())\n\n    def test_dict(self):\n        # Arrange\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n\n        # v2 interface\n        v2_tags = {256: 55, 257: 43, 258: (8, 8, 8, 8), 259: 1,\n                   262: 2, 296: 2, 273: (8,), 338: (1,), 277: 4,\n                   279: (9460,), 282: 72.0, 283: 72.0, 284: 1}\n        self.assertEqual(dict(im.tag_v2), v2_tags)\n\n        # legacy interface\n        legacy_tags = {256: (55,), 257: (43,), 258: (8, 8, 8, 8), 259: (1,),\n                       262: (2,), 296: (2,), 273: (8,), 338: (1,), 277: (4,),\n                       279: (9460,), 282: ((720000, 10000),),\n                       283: ((720000, 10000),), 284: (1,)}\n        self.assertEqual(dict(im.tag), legacy_tags)\n\n    def test__delitem__(self):\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n        len_before = len(dict(im.ifd))\n        del im.ifd[256]\n        len_after = len(dict(im.ifd))\n        self.assertEqual(len_before, len_after + 1)\n\n    def test_load_byte(self):\n        for legacy_api in [False, True]:\n            ifd = TiffImagePlugin.ImageFileDirectory_v2()\n            data = b\"abc\"\n            ret = ifd.load_byte(data, legacy_api)\n            self.assertEqual(ret, b\"abc\")\n\n    def test_load_string(self):\n        ifd = TiffImagePlugin.ImageFileDirectory_v2()\n        data = b\"abc\\0\"\n        ret = ifd.load_string(data, False)\n        self.assertEqual(ret, \"abc\")\n\n    def test_load_float(self):\n        ifd = TiffImagePlugin.ImageFileDirectory_v2()\n        data = b\"abcdabcd\"\n        ret = ifd.load_float(data, False)\n        self.assertEqual(ret, (1.6777999408082104e+22, 1.6777999408082104e+22))\n\n    def test_load_double(self):\n        ifd = TiffImagePlugin.ImageFileDirectory_v2()\n        data = b\"abcdefghabcdefgh\"\n        ret = ifd.load_double(data, False)\n        self.assertEqual(ret, (8.540883223036124e+194, 8.540883223036124e+194))\n\n    def test_seek(self):\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n        im.seek(-1)\n        self.assertEqual(im.tell(), 0)\n\n    def test_seek_eof(self):\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n        self.assertEqual(im.tell(), 0)\n        self.assertRaises(EOFError, lambda: im.seek(1))\n\n    def test__limit_rational_int(self):\n        from PIL.TiffImagePlugin import _limit_rational\n        value = 34\n        ret = _limit_rational(value, 65536)\n        self.assertEqual(ret, (34, 1))\n\n    def test__limit_rational_float(self):\n        from PIL.TiffImagePlugin import _limit_rational\n        value = 22.3\n        ret = _limit_rational(value, 65536)\n        self.assertEqual(ret, (223, 10))\n\n    def test_4bit(self):\n        test_file = \"Tests/images/hopper_gray_4bpp.tif\"\n        original = hopper(\"L\")\n        im = Image.open(test_file)\n        self.assertEqual(im.size, (128, 128))\n        self.assertEqual(im.mode, \"L\")\n        self.assert_image_similar(im, original, 7.3)\n\n    def test_gray_semibyte_per_pixel(self):\n        test_files = (\n            (\n                24.8,  # epsilon\n                (  # group\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper2.tif\",\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper2I.tif\",\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper2R.tif\",\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper2IR.tif\",\n                )\n            ),\n            (\n                7.3,  # epsilon\n                (  # group\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper4.tif\",\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper4I.tif\",\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper4R.tif\",\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper4IR.tif\",\n                )\n            ),\n        )\n        original = hopper(\"L\")\n        for epsilon, group in test_files:\n            im = Image.open(group[0])\n            self.assertEqual(im.size, (128, 128))\n            self.assertEqual(im.mode, \"L\")\n            self.assert_image_similar(im, original, epsilon)\n            for file in group[1:]:\n                im2 = Image.open(file)\n                self.assertEqual(im2.size, (128, 128))\n                self.assertEqual(im2.mode, \"L\")\n                self.assert_image_equal(im, im2)\n\n    def test_with_underscores(self):\n        kwargs = {'resolution_unit': 'inch',\n                  'x_resolution': 72,\n                  'y_resolution': 36}\n        filename = self.tempfile(\"temp.tif\")\n        hopper(\"RGB\").save(filename, **kwargs)\n        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION\n        im = Image.open(filename)\n\n        # legacy interface\n        self.assertEqual(im.tag[X_RESOLUTION][0][0], 72)\n        self.assertEqual(im.tag[Y_RESOLUTION][0][0], 36)\n\n        # v2 interface\n        self.assertEqual(im.tag_v2[X_RESOLUTION], 72)\n        self.assertEqual(im.tag_v2[Y_RESOLUTION], 36)\n\n    def test_deprecation_warning_with_spaces(self):\n        kwargs = {'resolution unit': 'inch',\n                  'x resolution': 36,\n                  'y resolution': 72}\n        filename = self.tempfile(\"temp.tif\")\n        self.assert_warning(DeprecationWarning,\n                            lambda: hopper(\"RGB\").save(filename, **kwargs))\n        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION\n\n        im = Image.open(filename)\n\n        # legacy interface\n        self.assertEqual(im.tag[X_RESOLUTION][0][0], 36)\n        self.assertEqual(im.tag[Y_RESOLUTION][0][0], 72)\n\n        # v2 interface\n        self.assertEqual(im.tag_v2[X_RESOLUTION], 36)\n        self.assertEqual(im.tag_v2[Y_RESOLUTION], 72)\n\n    def test_lzw(self):\n        # Act\n        im = Image.open(\"Tests/images/hopper_lzw.tif\")\n\n        # Assert\n        self.assertEqual(im.mode, 'RGB')\n        self.assertEqual(im.size, (128, 128))\n        self.assertEqual(im.format, \"TIFF\")\n        im2 = hopper()\n        self.assert_image_similar(im, im2, 5)\n\n    def test_roundtrip_tiff_uint16(self):\n        # Test an image of all '0' values\n        pixel_value = 0x1234\n        infile = \"Tests/images/uint16_1_4660.tif\"\n        im = Image.open(infile)\n        self.assertEqual(im.getpixel((0, 0)), pixel_value)\n\n        tmpfile = self.tempfile(\"temp.tif\")\n        im.save(tmpfile)\n\n        reloaded = Image.open(tmpfile)\n\n        self.assert_image_equal(im, reloaded)\n\n    def test_tiff_save_all(self):\n        import io\n        import os\n\n        mp = io.BytesIO()\n        with Image.open(\"Tests/images/multipage.tiff\") as im:\n            im.save(mp, format=\"tiff\", save_all=True)\n\n        mp.seek(0, os.SEEK_SET)\n        with Image.open(mp) as im:\n            self.assertEqual(im.n_frames, 3)\n\n    def test_saving_icc_profile(self):\n        # Tests saving TIFF with icc_profile set.\n        # At the time of writing this will only work for non-compressed tiffs\n        # as libtiff does not support embedded ICC profiles, ImageFile._save(..)\n        # however does.\n        im = Image.new('RGB', (1, 1))\n        im.info['icc_profile'] = 'Dummy value'\n        \n        # Try save-load round trip to make sure both handle icc_profile.\n        tmpfile = self.tempfile('temp.tif')\n        im.save(tmpfile, 'TIFF', compression='raw')\n        reloaded = Image.open(tmpfile)\n        \n        self.assertEqual(b'Dummy value', reloaded.info['icc_profile'])",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 13,
                            "end_lineno": 489,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "Tests/test_file_tiff.py",
                            "type": "method",
                            "name": "TestFileTiff.test_xyres_fallback_tiff",
                            "content": "class TestFileTiff(PillowTestCase):\n\n    def test_sanity(self):\n\n        filename = self.tempfile(\"temp.tif\")\n\n        hopper(\"RGB\").save(filename)\n\n        im = Image.open(filename)\n        im.load()\n        self.assertEqual(im.mode, \"RGB\")\n        self.assertEqual(im.size, (128, 128))\n        self.assertEqual(im.format, \"TIFF\")\n\n        hopper(\"1\").save(filename)\n        im = Image.open(filename)\n\n        hopper(\"L\").save(filename)\n        im = Image.open(filename)\n\n        hopper(\"P\").save(filename)\n        im = Image.open(filename)\n\n        hopper(\"RGB\").save(filename)\n        im = Image.open(filename)\n\n        hopper(\"I\").save(filename)\n        im = Image.open(filename)\n\n    def test_mac_tiff(self):\n        # Read RGBa images from macOS [@PIL136]\n\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n\n        self.assertEqual(im.mode, \"RGBA\")\n        self.assertEqual(im.size, (55, 43))\n        self.assertEqual(im.tile, [('raw', (0, 0, 55, 43), 8, ('RGBa', 0, 1))])\n        im.load()\n\n    def test_gimp_tiff(self):\n        # Read TIFF JPEG images from GIMP [@PIL168]\n\n        codecs = dir(Image.core)\n        if \"jpeg_decoder\" not in codecs:\n            self.skipTest(\"jpeg support not available\")\n\n        filename = \"Tests/images/pil168.tif\"\n        im = Image.open(filename)\n\n        self.assertEqual(im.mode, \"RGB\")\n        self.assertEqual(im.size, (256, 256))\n        self.assertEqual(\n            im.tile, [\n                ('jpeg', (0, 0, 256, 64), 8, ('RGB', '')),\n                ('jpeg', (0, 64, 256, 128), 1215, ('RGB', '')),\n                ('jpeg', (0, 128, 256, 192), 2550, ('RGB', '')),\n                ('jpeg', (0, 192, 256, 256), 3890, ('RGB', '')),\n                ])\n        im.load()\n\n    def test_sampleformat(self):\n        # https://github.com/python-pillow/Pillow/issues/1466\n        im = Image.open(\"Tests/images/copyleft.tiff\")\n        self.assertEqual(im.mode, 'RGB')\n\n    def test_xyres_tiff(self):\n        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION\n        filename = \"Tests/images/pil168.tif\"\n        im = Image.open(filename)\n\n        # legacy api\n        self.assertIsInstance(im.tag[X_RESOLUTION][0], tuple)\n        self.assertIsInstance(im.tag[Y_RESOLUTION][0], tuple)\n\n        # v2 api\n        self.assertIsInstance(im.tag_v2[X_RESOLUTION],\n                              TiffImagePlugin.IFDRational)\n        self.assertIsInstance(im.tag_v2[Y_RESOLUTION],\n                              TiffImagePlugin.IFDRational)\n\n        self.assertEqual(im.info['dpi'], (72., 72.))\n\n    def test_xyres_fallback_tiff(self):\n        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION, RESOLUTION_UNIT\n        filename = \"Tests/images/compression.tif\"\n        im = Image.open(filename)\n\n        # v2 api\n        self.assertIsInstance(im.tag_v2[X_RESOLUTION],\n                              TiffImagePlugin.IFDRational)\n        self.assertIsInstance(im.tag_v2[Y_RESOLUTION],\n                              TiffImagePlugin.IFDRational)\n        self.assertRaises(KeyError,\n                          lambda: im.tag_v2[RESOLUTION_UNIT])\n\n        # Legacy.\n        self.assertEqual(im.info['resolution'], (100., 100.))\n        # Fallback \"inch\".\n        self.assertEqual(im.info['dpi'], (100., 100.))\n\n    def test_int_resolution(self):\n        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION\n        filename = \"Tests/images/pil168.tif\"\n        im = Image.open(filename)\n\n        # Try to read a file where X,Y_RESOLUTION are ints\n        im.tag_v2[X_RESOLUTION] = 71\n        im.tag_v2[Y_RESOLUTION] = 71\n        im._setup()\n        self.assertEqual(im.info['dpi'], (71., 71.))\n\n    def test_save_setting_missing_resolution(self):\n        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION\n        b = BytesIO()\n        Image.open(\"Tests/images/10ct_32bit_128.tiff\").save(\n            b, format=\"tiff\", resolution=123.45)\n        im = Image.open(b)\n        self.assertEqual(float(im.tag_v2[X_RESOLUTION]), 123.45)\n        self.assertEqual(float(im.tag_v2[Y_RESOLUTION]), 123.45)\n\n    def test_invalid_file(self):\n        invalid_file = \"Tests/images/flower.jpg\"\n\n        self.assertRaises(SyntaxError,\n                          lambda: TiffImagePlugin.TiffImageFile(invalid_file))\n\n        TiffImagePlugin.PREFIXES.append(b\"\\xff\\xd8\\xff\\xe0\")\n        self.assertRaises(SyntaxError,\n                          lambda: TiffImagePlugin.TiffImageFile(invalid_file))\n        TiffImagePlugin.PREFIXES.pop()\n\n    def test_bad_exif(self):\n        i = Image.open('Tests/images/hopper_bad_exif.jpg')\n        try:\n            self.assert_warning(UserWarning, i._getexif)\n        except struct.error:\n            self.fail(\n                \"Bad EXIF data passed incorrect values to _binary unpack\")\n\n    def test_save_rgba(self):\n        im = hopper(\"RGBA\")\n        outfile = self.tempfile(\"temp.tif\")\n        im.save(outfile)\n\n    def test_save_unsupported_mode(self):\n        im = hopper(\"HSV\")\n        outfile = self.tempfile(\"temp.tif\")\n        self.assertRaises(IOError, lambda: im.save(outfile))\n\n    def test_little_endian(self):\n        im = Image.open('Tests/images/16bit.cropped.tif')\n        self.assertEqual(im.getpixel((0, 0)), 480)\n        self.assertEqual(im.mode, 'I;16')\n\n        b = im.tobytes()\n        # Bytes are in image native order (little endian)\n        if py3:\n            self.assertEqual(b[0], ord(b'\\xe0'))\n            self.assertEqual(b[1], ord(b'\\x01'))\n        else:\n            self.assertEqual(b[0], b'\\xe0')\n            self.assertEqual(b[1], b'\\x01')\n\n    def test_big_endian(self):\n        im = Image.open('Tests/images/16bit.MM.cropped.tif')\n        self.assertEqual(im.getpixel((0, 0)), 480)\n        self.assertEqual(im.mode, 'I;16B')\n\n        b = im.tobytes()\n\n        # Bytes are in image native order (big endian)\n        if py3:\n            self.assertEqual(b[0], ord(b'\\x01'))\n            self.assertEqual(b[1], ord(b'\\xe0'))\n        else:\n            self.assertEqual(b[0], b'\\x01')\n            self.assertEqual(b[1], b'\\xe0')\n\n    def test_12bit_rawmode(self):\n        \"\"\" Are we generating the same interpretation\n        of the image as Imagemagick is? \"\"\"\n\n        im = Image.open('Tests/images/12bit.cropped.tif')\n\n        # to make the target --\n        # convert 12bit.cropped.tif -depth 16 tmp.tif\n        # convert tmp.tif -evaluate RightShift 4 12in16bit2.tif\n        # imagemagick will auto scale so that a 12bit FFF is 16bit FFF0,\n        # so we need to unshift so that the integer values are the same.\n\n        im2 = Image.open('Tests/images/12in16bit.tif')\n\n        logger.debug(\"%s\", [img.getpixel((0, idx))\n                            for img in [im, im2] for idx in range(3)])\n\n        self.assert_image_equal(im, im2)\n\n    def test_32bit_float(self):\n        # Issue 614, specific 32-bit float format\n        path = 'Tests/images/10ct_32bit_128.tiff'\n        im = Image.open(path)\n        im.load()\n\n        self.assertEqual(im.getpixel((0, 0)), -0.4526388943195343)\n        self.assertEqual(\n            im.getextrema(), (-3.140936851501465, 3.140684127807617))\n\n    def test_n_frames(self):\n        im = Image.open('Tests/images/multipage-lastframe.tif')\n        self.assertEqual(im.n_frames, 1)\n        self.assertFalse(im.is_animated)\n\n        im = Image.open('Tests/images/multipage.tiff')\n        self.assertEqual(im.n_frames, 3)\n        self.assertTrue(im.is_animated)\n\n    def test_eoferror(self):\n        im = Image.open('Tests/images/multipage-lastframe.tif')\n\n        n_frames = im.n_frames\n        while True:\n            n_frames -= 1\n            try:\n                im.seek(n_frames)\n                break\n            except EOFError:\n                self.assertTrue(im.tell() < n_frames)\n\n    def test_multipage(self):\n        # issue #862\n        im = Image.open('Tests/images/multipage.tiff')\n        # file is a multipage tiff: 10x10 green, 10x10 red, 20x20 blue\n\n        im.seek(0)\n        self.assertEqual(im.size, (10, 10))\n        self.assertEqual(im.convert('RGB').getpixel((0, 0)), (0, 128, 0))\n\n        im.seek(1)\n        im.load()\n        self.assertEqual(im.size, (10, 10))\n        self.assertEqual(im.convert('RGB').getpixel((0, 0)), (255, 0, 0))\n\n        im.seek(2)\n        im.load()\n        self.assertEqual(im.size, (20, 20))\n        self.assertEqual(im.convert('RGB').getpixel((0, 0)), (0, 0, 255))\n\n    def test_multipage_last_frame(self):\n        im = Image.open('Tests/images/multipage-lastframe.tif')\n        im.load()\n        self.assertEqual(im.size, (20, 20))\n        self.assertEqual(im.convert('RGB').getpixel((0, 0)), (0, 0, 255))\n\n    def test___str__(self):\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n\n        # Act\n        ret = str(im.ifd)\n\n        # Assert\n        self.assertIsInstance(ret, str)\n\n    def test_as_dict_deprecation(self):\n        # Arrange\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n\n        self.assert_warning(DeprecationWarning, im.tag_v2.as_dict)\n        self.assert_warning(DeprecationWarning, im.tag.as_dict)\n        self.assertEqual(dict(im.tag_v2), im.tag_v2.as_dict())\n        self.assertEqual(dict(im.tag), im.tag.as_dict())\n\n    def test_dict(self):\n        # Arrange\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n\n        # v2 interface\n        v2_tags = {256: 55, 257: 43, 258: (8, 8, 8, 8), 259: 1,\n                   262: 2, 296: 2, 273: (8,), 338: (1,), 277: 4,\n                   279: (9460,), 282: 72.0, 283: 72.0, 284: 1}\n        self.assertEqual(dict(im.tag_v2), v2_tags)\n\n        # legacy interface\n        legacy_tags = {256: (55,), 257: (43,), 258: (8, 8, 8, 8), 259: (1,),\n                       262: (2,), 296: (2,), 273: (8,), 338: (1,), 277: (4,),\n                       279: (9460,), 282: ((720000, 10000),),\n                       283: ((720000, 10000),), 284: (1,)}\n        self.assertEqual(dict(im.tag), legacy_tags)\n\n    def test__delitem__(self):\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n        len_before = len(dict(im.ifd))\n        del im.ifd[256]\n        len_after = len(dict(im.ifd))\n        self.assertEqual(len_before, len_after + 1)\n\n    def test_load_byte(self):\n        for legacy_api in [False, True]:\n            ifd = TiffImagePlugin.ImageFileDirectory_v2()\n            data = b\"abc\"\n            ret = ifd.load_byte(data, legacy_api)\n            self.assertEqual(ret, b\"abc\")\n\n    def test_load_string(self):\n        ifd = TiffImagePlugin.ImageFileDirectory_v2()\n        data = b\"abc\\0\"\n        ret = ifd.load_string(data, False)\n        self.assertEqual(ret, \"abc\")\n\n    def test_load_float(self):\n        ifd = TiffImagePlugin.ImageFileDirectory_v2()\n        data = b\"abcdabcd\"\n        ret = ifd.load_float(data, False)\n        self.assertEqual(ret, (1.6777999408082104e+22, 1.6777999408082104e+22))\n\n    def test_load_double(self):\n        ifd = TiffImagePlugin.ImageFileDirectory_v2()\n        data = b\"abcdefghabcdefgh\"\n        ret = ifd.load_double(data, False)\n        self.assertEqual(ret, (8.540883223036124e+194, 8.540883223036124e+194))\n\n    def test_seek(self):\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n        im.seek(-1)\n        self.assertEqual(im.tell(), 0)\n\n    def test_seek_eof(self):\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n        self.assertEqual(im.tell(), 0)\n        self.assertRaises(EOFError, lambda: im.seek(1))\n\n    def test__limit_rational_int(self):\n        from PIL.TiffImagePlugin import _limit_rational\n        value = 34\n        ret = _limit_rational(value, 65536)\n        self.assertEqual(ret, (34, 1))\n\n    def test__limit_rational_float(self):\n        from PIL.TiffImagePlugin import _limit_rational\n        value = 22.3\n        ret = _limit_rational(value, 65536)\n        self.assertEqual(ret, (223, 10))\n\n    def test_4bit(self):\n        test_file = \"Tests/images/hopper_gray_4bpp.tif\"\n        original = hopper(\"L\")\n        im = Image.open(test_file)\n        self.assertEqual(im.size, (128, 128))\n        self.assertEqual(im.mode, \"L\")\n        self.assert_image_similar(im, original, 7.3)\n\n    def test_gray_semibyte_per_pixel(self):\n        test_files = (\n            (\n                24.8,  # epsilon\n                (  # group\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper2.tif\",\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper2I.tif\",\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper2R.tif\",\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper2IR.tif\",\n                )\n            ),\n            (\n                7.3,  # epsilon\n                (  # group\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper4.tif\",\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper4I.tif\",\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper4R.tif\",\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper4IR.tif\",\n                )\n            ),\n        )\n        original = hopper(\"L\")\n        for epsilon, group in test_files:\n            im = Image.open(group[0])\n            self.assertEqual(im.size, (128, 128))\n            self.assertEqual(im.mode, \"L\")\n            self.assert_image_similar(im, original, epsilon)\n            for file in group[1:]:\n                im2 = Image.open(file)\n                self.assertEqual(im2.size, (128, 128))\n                self.assertEqual(im2.mode, \"L\")\n                self.assert_image_equal(im, im2)\n\n    def test_with_underscores(self):\n        kwargs = {'resolution_unit': 'inch',\n                  'x_resolution': 72,\n                  'y_resolution': 36}\n        filename = self.tempfile(\"temp.tif\")\n        hopper(\"RGB\").save(filename, **kwargs)\n        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION\n        im = Image.open(filename)\n\n        # legacy interface\n        self.assertEqual(im.tag[X_RESOLUTION][0][0], 72)\n        self.assertEqual(im.tag[Y_RESOLUTION][0][0], 36)\n\n        # v2 interface\n        self.assertEqual(im.tag_v2[X_RESOLUTION], 72)\n        self.assertEqual(im.tag_v2[Y_RESOLUTION], 36)\n\n    def test_deprecation_warning_with_spaces(self):\n        kwargs = {'resolution unit': 'inch',\n                  'x resolution': 36,\n                  'y resolution': 72}\n        filename = self.tempfile(\"temp.tif\")\n        self.assert_warning(DeprecationWarning,\n                            lambda: hopper(\"RGB\").save(filename, **kwargs))\n        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION\n\n        im = Image.open(filename)\n\n        # legacy interface\n        self.assertEqual(im.tag[X_RESOLUTION][0][0], 36)\n        self.assertEqual(im.tag[Y_RESOLUTION][0][0], 72)\n\n        # v2 interface\n        self.assertEqual(im.tag_v2[X_RESOLUTION], 36)\n        self.assertEqual(im.tag_v2[Y_RESOLUTION], 72)\n\n    def test_lzw(self):\n        # Act\n        im = Image.open(\"Tests/images/hopper_lzw.tif\")\n\n        # Assert\n        self.assertEqual(im.mode, 'RGB')\n        self.assertEqual(im.size, (128, 128))\n        self.assertEqual(im.format, \"TIFF\")\n        im2 = hopper()\n        self.assert_image_similar(im, im2, 5)\n\n    def test_roundtrip_tiff_uint16(self):\n        # Test an image of all '0' values\n        pixel_value = 0x1234\n        infile = \"Tests/images/uint16_1_4660.tif\"\n        im = Image.open(infile)\n        self.assertEqual(im.getpixel((0, 0)), pixel_value)\n\n        tmpfile = self.tempfile(\"temp.tif\")\n        im.save(tmpfile)\n\n        reloaded = Image.open(tmpfile)\n\n        self.assert_image_equal(im, reloaded)\n\n    def test_tiff_save_all(self):\n        import io\n        import os\n\n        mp = io.BytesIO()\n        with Image.open(\"Tests/images/multipage.tiff\") as im:\n            im.save(mp, format=\"tiff\", save_all=True)\n\n        mp.seek(0, os.SEEK_SET)\n        with Image.open(mp) as im:\n            self.assertEqual(im.n_frames, 3)\n\n    def test_saving_icc_profile(self):\n        # Tests saving TIFF with icc_profile set.\n        # At the time of writing this will only work for non-compressed tiffs\n        # as libtiff does not support embedded ICC profiles, ImageFile._save(..)\n        # however does.\n        im = Image.new('RGB', (1, 1))\n        im.info['icc_profile'] = 'Dummy value'\n        \n        # Try save-load round trip to make sure both handle icc_profile.\n        tmpfile = self.tempfile('temp.tif')\n        im.save(tmpfile, 'TIFF', compression='raw')\n        reloaded = Image.open(tmpfile)\n        \n        self.assertEqual(b'Dummy value', reloaded.info['icc_profile'])",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 96,
                            "end_lineno": 112,
                            "parent": {
                                "file_name": "Tests/test_file_tiff.py",
                                "type": "class",
                                "name": "TestFileTiff",
                                "content": "class TestFileTiff(PillowTestCase):\n\n    def test_sanity(self):\n\n        filename = self.tempfile(\"temp.tif\")\n\n        hopper(\"RGB\").save(filename)\n\n        im = Image.open(filename)\n        im.load()\n        self.assertEqual(im.mode, \"RGB\")\n        self.assertEqual(im.size, (128, 128))\n        self.assertEqual(im.format, \"TIFF\")\n\n        hopper(\"1\").save(filename)\n        im = Image.open(filename)\n\n        hopper(\"L\").save(filename)\n        im = Image.open(filename)\n\n        hopper(\"P\").save(filename)\n        im = Image.open(filename)\n\n        hopper(\"RGB\").save(filename)\n        im = Image.open(filename)\n\n        hopper(\"I\").save(filename)\n        im = Image.open(filename)\n\n    def test_mac_tiff(self):\n        # Read RGBa images from macOS [@PIL136]\n\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n\n        self.assertEqual(im.mode, \"RGBA\")\n        self.assertEqual(im.size, (55, 43))\n        self.assertEqual(im.tile, [('raw', (0, 0, 55, 43), 8, ('RGBa', 0, 1))])\n        im.load()\n\n    def test_gimp_tiff(self):\n        # Read TIFF JPEG images from GIMP [@PIL168]\n\n        codecs = dir(Image.core)\n        if \"jpeg_decoder\" not in codecs:\n            self.skipTest(\"jpeg support not available\")\n\n        filename = \"Tests/images/pil168.tif\"\n        im = Image.open(filename)\n\n        self.assertEqual(im.mode, \"RGB\")\n        self.assertEqual(im.size, (256, 256))\n        self.assertEqual(\n            im.tile, [\n                ('jpeg', (0, 0, 256, 64), 8, ('RGB', '')),\n                ('jpeg', (0, 64, 256, 128), 1215, ('RGB', '')),\n                ('jpeg', (0, 128, 256, 192), 2550, ('RGB', '')),\n                ('jpeg', (0, 192, 256, 256), 3890, ('RGB', '')),\n                ])\n        im.load()\n\n    def test_sampleformat(self):\n        # https://github.com/python-pillow/Pillow/issues/1466\n        im = Image.open(\"Tests/images/copyleft.tiff\")\n        self.assertEqual(im.mode, 'RGB')\n\n    def test_xyres_tiff(self):\n        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION\n        filename = \"Tests/images/pil168.tif\"\n        im = Image.open(filename)\n\n        # legacy api\n        self.assertIsInstance(im.tag[X_RESOLUTION][0], tuple)\n        self.assertIsInstance(im.tag[Y_RESOLUTION][0], tuple)\n\n        # v2 api\n        self.assertIsInstance(im.tag_v2[X_RESOLUTION],\n                              TiffImagePlugin.IFDRational)\n        self.assertIsInstance(im.tag_v2[Y_RESOLUTION],\n                              TiffImagePlugin.IFDRational)\n\n        self.assertEqual(im.info['dpi'], (72., 72.))\n\n    def test_xyres_fallback_tiff(self):\n        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION, RESOLUTION_UNIT\n        filename = \"Tests/images/compression.tif\"\n        im = Image.open(filename)\n\n        # v2 api\n        self.assertIsInstance(im.tag_v2[X_RESOLUTION],\n                              TiffImagePlugin.IFDRational)\n        self.assertIsInstance(im.tag_v2[Y_RESOLUTION],\n                              TiffImagePlugin.IFDRational)\n        self.assertRaises(KeyError,\n                          lambda: im.tag_v2[RESOLUTION_UNIT])\n\n        # Legacy.\n        self.assertEqual(im.info['resolution'], (100., 100.))\n        # Fallback \"inch\".\n        self.assertEqual(im.info['dpi'], (100., 100.))\n\n    def test_int_resolution(self):\n        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION\n        filename = \"Tests/images/pil168.tif\"\n        im = Image.open(filename)\n\n        # Try to read a file where X,Y_RESOLUTION are ints\n        im.tag_v2[X_RESOLUTION] = 71\n        im.tag_v2[Y_RESOLUTION] = 71\n        im._setup()\n        self.assertEqual(im.info['dpi'], (71., 71.))\n\n    def test_save_setting_missing_resolution(self):\n        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION\n        b = BytesIO()\n        Image.open(\"Tests/images/10ct_32bit_128.tiff\").save(\n            b, format=\"tiff\", resolution=123.45)\n        im = Image.open(b)\n        self.assertEqual(float(im.tag_v2[X_RESOLUTION]), 123.45)\n        self.assertEqual(float(im.tag_v2[Y_RESOLUTION]), 123.45)\n\n    def test_invalid_file(self):\n        invalid_file = \"Tests/images/flower.jpg\"\n\n        self.assertRaises(SyntaxError,\n                          lambda: TiffImagePlugin.TiffImageFile(invalid_file))\n\n        TiffImagePlugin.PREFIXES.append(b\"\\xff\\xd8\\xff\\xe0\")\n        self.assertRaises(SyntaxError,\n                          lambda: TiffImagePlugin.TiffImageFile(invalid_file))\n        TiffImagePlugin.PREFIXES.pop()\n\n    def test_bad_exif(self):\n        i = Image.open('Tests/images/hopper_bad_exif.jpg')\n        try:\n            self.assert_warning(UserWarning, i._getexif)\n        except struct.error:\n            self.fail(\n                \"Bad EXIF data passed incorrect values to _binary unpack\")\n\n    def test_save_rgba(self):\n        im = hopper(\"RGBA\")\n        outfile = self.tempfile(\"temp.tif\")\n        im.save(outfile)\n\n    def test_save_unsupported_mode(self):\n        im = hopper(\"HSV\")\n        outfile = self.tempfile(\"temp.tif\")\n        self.assertRaises(IOError, lambda: im.save(outfile))\n\n    def test_little_endian(self):\n        im = Image.open('Tests/images/16bit.cropped.tif')\n        self.assertEqual(im.getpixel((0, 0)), 480)\n        self.assertEqual(im.mode, 'I;16')\n\n        b = im.tobytes()\n        # Bytes are in image native order (little endian)\n        if py3:\n            self.assertEqual(b[0], ord(b'\\xe0'))\n            self.assertEqual(b[1], ord(b'\\x01'))\n        else:\n            self.assertEqual(b[0], b'\\xe0')\n            self.assertEqual(b[1], b'\\x01')\n\n    def test_big_endian(self):\n        im = Image.open('Tests/images/16bit.MM.cropped.tif')\n        self.assertEqual(im.getpixel((0, 0)), 480)\n        self.assertEqual(im.mode, 'I;16B')\n\n        b = im.tobytes()\n\n        # Bytes are in image native order (big endian)\n        if py3:\n            self.assertEqual(b[0], ord(b'\\x01'))\n            self.assertEqual(b[1], ord(b'\\xe0'))\n        else:\n            self.assertEqual(b[0], b'\\x01')\n            self.assertEqual(b[1], b'\\xe0')\n\n    def test_12bit_rawmode(self):\n        \"\"\" Are we generating the same interpretation\n        of the image as Imagemagick is? \"\"\"\n\n        im = Image.open('Tests/images/12bit.cropped.tif')\n\n        # to make the target --\n        # convert 12bit.cropped.tif -depth 16 tmp.tif\n        # convert tmp.tif -evaluate RightShift 4 12in16bit2.tif\n        # imagemagick will auto scale so that a 12bit FFF is 16bit FFF0,\n        # so we need to unshift so that the integer values are the same.\n\n        im2 = Image.open('Tests/images/12in16bit.tif')\n\n        logger.debug(\"%s\", [img.getpixel((0, idx))\n                            for img in [im, im2] for idx in range(3)])\n\n        self.assert_image_equal(im, im2)\n\n    def test_32bit_float(self):\n        # Issue 614, specific 32-bit float format\n        path = 'Tests/images/10ct_32bit_128.tiff'\n        im = Image.open(path)\n        im.load()\n\n        self.assertEqual(im.getpixel((0, 0)), -0.4526388943195343)\n        self.assertEqual(\n            im.getextrema(), (-3.140936851501465, 3.140684127807617))\n\n    def test_n_frames(self):\n        im = Image.open('Tests/images/multipage-lastframe.tif')\n        self.assertEqual(im.n_frames, 1)\n        self.assertFalse(im.is_animated)\n\n        im = Image.open('Tests/images/multipage.tiff')\n        self.assertEqual(im.n_frames, 3)\n        self.assertTrue(im.is_animated)\n\n    def test_eoferror(self):\n        im = Image.open('Tests/images/multipage-lastframe.tif')\n\n        n_frames = im.n_frames\n        while True:\n            n_frames -= 1\n            try:\n                im.seek(n_frames)\n                break\n            except EOFError:\n                self.assertTrue(im.tell() < n_frames)\n\n    def test_multipage(self):\n        # issue #862\n        im = Image.open('Tests/images/multipage.tiff')\n        # file is a multipage tiff: 10x10 green, 10x10 red, 20x20 blue\n\n        im.seek(0)\n        self.assertEqual(im.size, (10, 10))\n        self.assertEqual(im.convert('RGB').getpixel((0, 0)), (0, 128, 0))\n\n        im.seek(1)\n        im.load()\n        self.assertEqual(im.size, (10, 10))\n        self.assertEqual(im.convert('RGB').getpixel((0, 0)), (255, 0, 0))\n\n        im.seek(2)\n        im.load()\n        self.assertEqual(im.size, (20, 20))\n        self.assertEqual(im.convert('RGB').getpixel((0, 0)), (0, 0, 255))\n\n    def test_multipage_last_frame(self):\n        im = Image.open('Tests/images/multipage-lastframe.tif')\n        im.load()\n        self.assertEqual(im.size, (20, 20))\n        self.assertEqual(im.convert('RGB').getpixel((0, 0)), (0, 0, 255))\n\n    def test___str__(self):\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n\n        # Act\n        ret = str(im.ifd)\n\n        # Assert\n        self.assertIsInstance(ret, str)\n\n    def test_as_dict_deprecation(self):\n        # Arrange\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n\n        self.assert_warning(DeprecationWarning, im.tag_v2.as_dict)\n        self.assert_warning(DeprecationWarning, im.tag.as_dict)\n        self.assertEqual(dict(im.tag_v2), im.tag_v2.as_dict())\n        self.assertEqual(dict(im.tag), im.tag.as_dict())\n\n    def test_dict(self):\n        # Arrange\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n\n        # v2 interface\n        v2_tags = {256: 55, 257: 43, 258: (8, 8, 8, 8), 259: 1,\n                   262: 2, 296: 2, 273: (8,), 338: (1,), 277: 4,\n                   279: (9460,), 282: 72.0, 283: 72.0, 284: 1}\n        self.assertEqual(dict(im.tag_v2), v2_tags)\n\n        # legacy interface\n        legacy_tags = {256: (55,), 257: (43,), 258: (8, 8, 8, 8), 259: (1,),\n                       262: (2,), 296: (2,), 273: (8,), 338: (1,), 277: (4,),\n                       279: (9460,), 282: ((720000, 10000),),\n                       283: ((720000, 10000),), 284: (1,)}\n        self.assertEqual(dict(im.tag), legacy_tags)\n\n    def test__delitem__(self):\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n        len_before = len(dict(im.ifd))\n        del im.ifd[256]\n        len_after = len(dict(im.ifd))\n        self.assertEqual(len_before, len_after + 1)\n\n    def test_load_byte(self):\n        for legacy_api in [False, True]:\n            ifd = TiffImagePlugin.ImageFileDirectory_v2()\n            data = b\"abc\"\n            ret = ifd.load_byte(data, legacy_api)\n            self.assertEqual(ret, b\"abc\")\n\n    def test_load_string(self):\n        ifd = TiffImagePlugin.ImageFileDirectory_v2()\n        data = b\"abc\\0\"\n        ret = ifd.load_string(data, False)\n        self.assertEqual(ret, \"abc\")\n\n    def test_load_float(self):\n        ifd = TiffImagePlugin.ImageFileDirectory_v2()\n        data = b\"abcdabcd\"\n        ret = ifd.load_float(data, False)\n        self.assertEqual(ret, (1.6777999408082104e+22, 1.6777999408082104e+22))\n\n    def test_load_double(self):\n        ifd = TiffImagePlugin.ImageFileDirectory_v2()\n        data = b\"abcdefghabcdefgh\"\n        ret = ifd.load_double(data, False)\n        self.assertEqual(ret, (8.540883223036124e+194, 8.540883223036124e+194))\n\n    def test_seek(self):\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n        im.seek(-1)\n        self.assertEqual(im.tell(), 0)\n\n    def test_seek_eof(self):\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n        self.assertEqual(im.tell(), 0)\n        self.assertRaises(EOFError, lambda: im.seek(1))\n\n    def test__limit_rational_int(self):\n        from PIL.TiffImagePlugin import _limit_rational\n        value = 34\n        ret = _limit_rational(value, 65536)\n        self.assertEqual(ret, (34, 1))\n\n    def test__limit_rational_float(self):\n        from PIL.TiffImagePlugin import _limit_rational\n        value = 22.3\n        ret = _limit_rational(value, 65536)\n        self.assertEqual(ret, (223, 10))\n\n    def test_4bit(self):\n        test_file = \"Tests/images/hopper_gray_4bpp.tif\"\n        original = hopper(\"L\")\n        im = Image.open(test_file)\n        self.assertEqual(im.size, (128, 128))\n        self.assertEqual(im.mode, \"L\")\n        self.assert_image_similar(im, original, 7.3)\n\n    def test_gray_semibyte_per_pixel(self):\n        test_files = (\n            (\n                24.8,  # epsilon\n                (  # group\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper2.tif\",\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper2I.tif\",\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper2R.tif\",\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper2IR.tif\",\n                )\n            ),\n            (\n                7.3,  # epsilon\n                (  # group\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper4.tif\",\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper4I.tif\",\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper4R.tif\",\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper4IR.tif\",\n                )\n            ),\n        )\n        original = hopper(\"L\")\n        for epsilon, group in test_files:\n            im = Image.open(group[0])\n            self.assertEqual(im.size, (128, 128))\n            self.assertEqual(im.mode, \"L\")\n            self.assert_image_similar(im, original, epsilon)\n            for file in group[1:]:\n                im2 = Image.open(file)\n                self.assertEqual(im2.size, (128, 128))\n                self.assertEqual(im2.mode, \"L\")\n                self.assert_image_equal(im, im2)\n\n    def test_with_underscores(self):\n        kwargs = {'resolution_unit': 'inch',\n                  'x_resolution': 72,\n                  'y_resolution': 36}\n        filename = self.tempfile(\"temp.tif\")\n        hopper(\"RGB\").save(filename, **kwargs)\n        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION\n        im = Image.open(filename)\n\n        # legacy interface\n        self.assertEqual(im.tag[X_RESOLUTION][0][0], 72)\n        self.assertEqual(im.tag[Y_RESOLUTION][0][0], 36)\n\n        # v2 interface\n        self.assertEqual(im.tag_v2[X_RESOLUTION], 72)\n        self.assertEqual(im.tag_v2[Y_RESOLUTION], 36)\n\n    def test_deprecation_warning_with_spaces(self):\n        kwargs = {'resolution unit': 'inch',\n                  'x resolution': 36,\n                  'y resolution': 72}\n        filename = self.tempfile(\"temp.tif\")\n        self.assert_warning(DeprecationWarning,\n                            lambda: hopper(\"RGB\").save(filename, **kwargs))\n        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION\n\n        im = Image.open(filename)\n\n        # legacy interface\n        self.assertEqual(im.tag[X_RESOLUTION][0][0], 36)\n        self.assertEqual(im.tag[Y_RESOLUTION][0][0], 72)\n\n        # v2 interface\n        self.assertEqual(im.tag_v2[X_RESOLUTION], 36)\n        self.assertEqual(im.tag_v2[Y_RESOLUTION], 72)\n\n    def test_lzw(self):\n        # Act\n        im = Image.open(\"Tests/images/hopper_lzw.tif\")\n\n        # Assert\n        self.assertEqual(im.mode, 'RGB')\n        self.assertEqual(im.size, (128, 128))\n        self.assertEqual(im.format, \"TIFF\")\n        im2 = hopper()\n        self.assert_image_similar(im, im2, 5)\n\n    def test_roundtrip_tiff_uint16(self):\n        # Test an image of all '0' values\n        pixel_value = 0x1234\n        infile = \"Tests/images/uint16_1_4660.tif\"\n        im = Image.open(infile)\n        self.assertEqual(im.getpixel((0, 0)), pixel_value)\n\n        tmpfile = self.tempfile(\"temp.tif\")\n        im.save(tmpfile)\n\n        reloaded = Image.open(tmpfile)\n\n        self.assert_image_equal(im, reloaded)\n\n    def test_tiff_save_all(self):\n        import io\n        import os\n\n        mp = io.BytesIO()\n        with Image.open(\"Tests/images/multipage.tiff\") as im:\n            im.save(mp, format=\"tiff\", save_all=True)\n\n        mp.seek(0, os.SEEK_SET)\n        with Image.open(mp) as im:\n            self.assertEqual(im.n_frames, 3)\n\n    def test_saving_icc_profile(self):\n        # Tests saving TIFF with icc_profile set.\n        # At the time of writing this will only work for non-compressed tiffs\n        # as libtiff does not support embedded ICC profiles, ImageFile._save(..)\n        # however does.\n        im = Image.new('RGB', (1, 1))\n        im.info['icc_profile'] = 'Dummy value'\n        \n        # Try save-load round trip to make sure both handle icc_profile.\n        tmpfile = self.tempfile('temp.tif')\n        im.save(tmpfile, 'TIFF', compression='raw')\n        reloaded = Image.open(tmpfile)\n        \n        self.assertEqual(b'Dummy value', reloaded.info['icc_profile'])",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 13,
                                "end_lineno": 489,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "8a9bd2cdcdd7fc9ecd89fa79323463f4d24f53b8^",
    "new_commit_hash": "8a9bd2cdcdd7fc9ecd89fa79323463f4d24f53b8",
    "commit_message": "Default to inch-interpretation for missing ResolutionUnit in TiffImagePlugin.",
    "commit_date": "2017-01-19T17:24:28+01:00",
    "metadata": {}
}
{
    "repo_name": "pillow",
    "new_commit_hash": "8a9bd2cdcdd7fc9ecd89fa79323463f4d24f53b8",
    "test_file_codes": [
        "from __future__ import print_function\nimport logging\nfrom io import BytesIO\nimport struct\n\nfrom helper import unittest, PillowTestCase, hopper, py3\n\nfrom PIL import Image, TiffImagePlugin\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestFileTiff(PillowTestCase):\n\n    def test_sanity(self):\n\n        filename = self.tempfile(\"temp.tif\")\n\n        hopper(\"RGB\").save(filename)\n\n        im = Image.open(filename)\n        im.load()\n        self.assertEqual(im.mode, \"RGB\")\n        self.assertEqual(im.size, (128, 128))\n        self.assertEqual(im.format, \"TIFF\")\n\n        hopper(\"1\").save(filename)\n        im = Image.open(filename)\n\n        hopper(\"L\").save(filename)\n        im = Image.open(filename)\n\n        hopper(\"P\").save(filename)\n        im = Image.open(filename)\n\n        hopper(\"RGB\").save(filename)\n        im = Image.open(filename)\n\n        hopper(\"I\").save(filename)\n        im = Image.open(filename)\n\n    def test_mac_tiff(self):\n        # Read RGBa images from macOS [@PIL136]\n\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n\n        self.assertEqual(im.mode, \"RGBA\")\n        self.assertEqual(im.size, (55, 43))\n        self.assertEqual(im.tile, [('raw', (0, 0, 55, 43), 8, ('RGBa', 0, 1))])\n        im.load()\n\n    def test_gimp_tiff(self):\n        # Read TIFF JPEG images from GIMP [@PIL168]\n\n        codecs = dir(Image.core)\n        if \"jpeg_decoder\" not in codecs:\n            self.skipTest(\"jpeg support not available\")\n\n        filename = \"Tests/images/pil168.tif\"\n        im = Image.open(filename)\n\n        self.assertEqual(im.mode, \"RGB\")\n        self.assertEqual(im.size, (256, 256))\n        self.assertEqual(\n            im.tile, [\n                ('jpeg', (0, 0, 256, 64), 8, ('RGB', '')),\n                ('jpeg', (0, 64, 256, 128), 1215, ('RGB', '')),\n                ('jpeg', (0, 128, 256, 192), 2550, ('RGB', '')),\n                ('jpeg', (0, 192, 256, 256), 3890, ('RGB', '')),\n                ])\n        im.load()\n\n    def test_sampleformat(self):\n        # https://github.com/python-pillow/Pillow/issues/1466\n        im = Image.open(\"Tests/images/copyleft.tiff\")\n        self.assertEqual(im.mode, 'RGB')\n\n    def test_xyres_tiff(self):\n        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION\n        filename = \"Tests/images/pil168.tif\"\n        im = Image.open(filename)\n\n        # legacy api\n        self.assertIsInstance(im.tag[X_RESOLUTION][0], tuple)\n        self.assertIsInstance(im.tag[Y_RESOLUTION][0], tuple)\n\n        # v2 api\n        self.assertIsInstance(im.tag_v2[X_RESOLUTION],\n                              TiffImagePlugin.IFDRational)\n        self.assertIsInstance(im.tag_v2[Y_RESOLUTION],\n                              TiffImagePlugin.IFDRational)\n\n        self.assertEqual(im.info['dpi'], (72., 72.))\n\n    def test_xyres_fallback_tiff(self):\n        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION, RESOLUTION_UNIT\n        filename = \"Tests/images/compression.tif\"\n        im = Image.open(filename)\n\n        # v2 api\n        self.assertIsInstance(im.tag_v2[X_RESOLUTION],\n                              TiffImagePlugin.IFDRational)\n        self.assertIsInstance(im.tag_v2[Y_RESOLUTION],\n                              TiffImagePlugin.IFDRational)\n        self.assertRaises(KeyError,\n                          lambda: im.tag_v2[RESOLUTION_UNIT])\n\n        # Legacy.\n        self.assertEqual(im.info['resolution'], (100., 100.))\n        # Fallback \"inch\".\n        self.assertEqual(im.info['dpi'], (100., 100.))\n\n    def test_int_resolution(self):\n        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION\n        filename = \"Tests/images/pil168.tif\"\n        im = Image.open(filename)\n\n        # Try to read a file where X,Y_RESOLUTION are ints\n        im.tag_v2[X_RESOLUTION] = 71\n        im.tag_v2[Y_RESOLUTION] = 71\n        im._setup()\n        self.assertEqual(im.info['dpi'], (71., 71.))\n\n    def test_save_setting_missing_resolution(self):\n        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION\n        b = BytesIO()\n        Image.open(\"Tests/images/10ct_32bit_128.tiff\").save(\n            b, format=\"tiff\", resolution=123.45)\n        im = Image.open(b)\n        self.assertEqual(float(im.tag_v2[X_RESOLUTION]), 123.45)\n        self.assertEqual(float(im.tag_v2[Y_RESOLUTION]), 123.45)\n\n    def test_invalid_file(self):\n        invalid_file = \"Tests/images/flower.jpg\"\n\n        self.assertRaises(SyntaxError,\n                          lambda: TiffImagePlugin.TiffImageFile(invalid_file))\n\n        TiffImagePlugin.PREFIXES.append(b\"\\xff\\xd8\\xff\\xe0\")\n        self.assertRaises(SyntaxError,\n                          lambda: TiffImagePlugin.TiffImageFile(invalid_file))\n        TiffImagePlugin.PREFIXES.pop()\n\n    def test_bad_exif(self):\n        i = Image.open('Tests/images/hopper_bad_exif.jpg')\n        try:\n            self.assert_warning(UserWarning, i._getexif)\n        except struct.error:\n            self.fail(\n                \"Bad EXIF data passed incorrect values to _binary unpack\")\n\n    def test_save_rgba(self):\n        im = hopper(\"RGBA\")\n        outfile = self.tempfile(\"temp.tif\")\n        im.save(outfile)\n\n    def test_save_unsupported_mode(self):\n        im = hopper(\"HSV\")\n        outfile = self.tempfile(\"temp.tif\")\n        self.assertRaises(IOError, lambda: im.save(outfile))\n\n    def test_little_endian(self):\n        im = Image.open('Tests/images/16bit.cropped.tif')\n        self.assertEqual(im.getpixel((0, 0)), 480)\n        self.assertEqual(im.mode, 'I;16')\n\n        b = im.tobytes()\n        # Bytes are in image native order (little endian)\n        if py3:\n            self.assertEqual(b[0], ord(b'\\xe0'))\n            self.assertEqual(b[1], ord(b'\\x01'))\n        else:\n            self.assertEqual(b[0], b'\\xe0')\n            self.assertEqual(b[1], b'\\x01')\n\n    def test_big_endian(self):\n        im = Image.open('Tests/images/16bit.MM.cropped.tif')\n        self.assertEqual(im.getpixel((0, 0)), 480)\n        self.assertEqual(im.mode, 'I;16B')\n\n        b = im.tobytes()\n\n        # Bytes are in image native order (big endian)\n        if py3:\n            self.assertEqual(b[0], ord(b'\\x01'))\n            self.assertEqual(b[1], ord(b'\\xe0'))\n        else:\n            self.assertEqual(b[0], b'\\x01')\n            self.assertEqual(b[1], b'\\xe0')\n\n    def test_12bit_rawmode(self):\n        \"\"\" Are we generating the same interpretation\n        of the image as Imagemagick is? \"\"\"\n\n        im = Image.open('Tests/images/12bit.cropped.tif')\n\n        # to make the target --\n        # convert 12bit.cropped.tif -depth 16 tmp.tif\n        # convert tmp.tif -evaluate RightShift 4 12in16bit2.tif\n        # imagemagick will auto scale so that a 12bit FFF is 16bit FFF0,\n        # so we need to unshift so that the integer values are the same.\n\n        im2 = Image.open('Tests/images/12in16bit.tif')\n\n        logger.debug(\"%s\", [img.getpixel((0, idx))\n                            for img in [im, im2] for idx in range(3)])\n\n        self.assert_image_equal(im, im2)\n\n    def test_32bit_float(self):\n        # Issue 614, specific 32-bit float format\n        path = 'Tests/images/10ct_32bit_128.tiff'\n        im = Image.open(path)\n        im.load()\n\n        self.assertEqual(im.getpixel((0, 0)), -0.4526388943195343)\n        self.assertEqual(\n            im.getextrema(), (-3.140936851501465, 3.140684127807617))\n\n    def test_n_frames(self):\n        im = Image.open('Tests/images/multipage-lastframe.tif')\n        self.assertEqual(im.n_frames, 1)\n        self.assertFalse(im.is_animated)\n\n        im = Image.open('Tests/images/multipage.tiff')\n        self.assertEqual(im.n_frames, 3)\n        self.assertTrue(im.is_animated)\n\n    def test_eoferror(self):\n        im = Image.open('Tests/images/multipage-lastframe.tif')\n\n        n_frames = im.n_frames\n        while True:\n            n_frames -= 1\n            try:\n                im.seek(n_frames)\n                break\n            except EOFError:\n                self.assertTrue(im.tell() < n_frames)\n\n    def test_multipage(self):\n        # issue #862\n        im = Image.open('Tests/images/multipage.tiff')\n        # file is a multipage tiff: 10x10 green, 10x10 red, 20x20 blue\n\n        im.seek(0)\n        self.assertEqual(im.size, (10, 10))\n        self.assertEqual(im.convert('RGB').getpixel((0, 0)), (0, 128, 0))\n\n        im.seek(1)\n        im.load()\n        self.assertEqual(im.size, (10, 10))\n        self.assertEqual(im.convert('RGB').getpixel((0, 0)), (255, 0, 0))\n\n        im.seek(2)\n        im.load()\n        self.assertEqual(im.size, (20, 20))\n        self.assertEqual(im.convert('RGB').getpixel((0, 0)), (0, 0, 255))\n\n    def test_multipage_last_frame(self):\n        im = Image.open('Tests/images/multipage-lastframe.tif')\n        im.load()\n        self.assertEqual(im.size, (20, 20))\n        self.assertEqual(im.convert('RGB').getpixel((0, 0)), (0, 0, 255))\n\n    def test___str__(self):\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n\n        # Act\n        ret = str(im.ifd)\n\n        # Assert\n        self.assertIsInstance(ret, str)\n\n    def test_as_dict_deprecation(self):\n        # Arrange\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n\n        self.assert_warning(DeprecationWarning, im.tag_v2.as_dict)\n        self.assert_warning(DeprecationWarning, im.tag.as_dict)\n        self.assertEqual(dict(im.tag_v2), im.tag_v2.as_dict())\n        self.assertEqual(dict(im.tag), im.tag.as_dict())\n\n    def test_dict(self):\n        # Arrange\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n\n        # v2 interface\n        v2_tags = {256: 55, 257: 43, 258: (8, 8, 8, 8), 259: 1,\n                   262: 2, 296: 2, 273: (8,), 338: (1,), 277: 4,\n                   279: (9460,), 282: 72.0, 283: 72.0, 284: 1}\n        self.assertEqual(dict(im.tag_v2), v2_tags)\n\n        # legacy interface\n        legacy_tags = {256: (55,), 257: (43,), 258: (8, 8, 8, 8), 259: (1,),\n                       262: (2,), 296: (2,), 273: (8,), 338: (1,), 277: (4,),\n                       279: (9460,), 282: ((720000, 10000),),\n                       283: ((720000, 10000),), 284: (1,)}\n        self.assertEqual(dict(im.tag), legacy_tags)\n\n    def test__delitem__(self):\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n        len_before = len(dict(im.ifd))\n        del im.ifd[256]\n        len_after = len(dict(im.ifd))\n        self.assertEqual(len_before, len_after + 1)\n\n    def test_load_byte(self):\n        for legacy_api in [False, True]:\n            ifd = TiffImagePlugin.ImageFileDirectory_v2()\n            data = b\"abc\"\n            ret = ifd.load_byte(data, legacy_api)\n            self.assertEqual(ret, b\"abc\")\n\n    def test_load_string(self):\n        ifd = TiffImagePlugin.ImageFileDirectory_v2()\n        data = b\"abc\\0\"\n        ret = ifd.load_string(data, False)\n        self.assertEqual(ret, \"abc\")\n\n    def test_load_float(self):\n        ifd = TiffImagePlugin.ImageFileDirectory_v2()\n        data = b\"abcdabcd\"\n        ret = ifd.load_float(data, False)\n        self.assertEqual(ret, (1.6777999408082104e+22, 1.6777999408082104e+22))\n\n    def test_load_double(self):\n        ifd = TiffImagePlugin.ImageFileDirectory_v2()\n        data = b\"abcdefghabcdefgh\"\n        ret = ifd.load_double(data, False)\n        self.assertEqual(ret, (8.540883223036124e+194, 8.540883223036124e+194))\n\n    def test_seek(self):\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n        im.seek(-1)\n        self.assertEqual(im.tell(), 0)\n\n    def test_seek_eof(self):\n        filename = \"Tests/images/pil136.tiff\"\n        im = Image.open(filename)\n        self.assertEqual(im.tell(), 0)\n        self.assertRaises(EOFError, lambda: im.seek(1))\n\n    def test__limit_rational_int(self):\n        from PIL.TiffImagePlugin import _limit_rational\n        value = 34\n        ret = _limit_rational(value, 65536)\n        self.assertEqual(ret, (34, 1))\n\n    def test__limit_rational_float(self):\n        from PIL.TiffImagePlugin import _limit_rational\n        value = 22.3\n        ret = _limit_rational(value, 65536)\n        self.assertEqual(ret, (223, 10))\n\n    def test_4bit(self):\n        test_file = \"Tests/images/hopper_gray_4bpp.tif\"\n        original = hopper(\"L\")\n        im = Image.open(test_file)\n        self.assertEqual(im.size, (128, 128))\n        self.assertEqual(im.mode, \"L\")\n        self.assert_image_similar(im, original, 7.3)\n\n    def test_gray_semibyte_per_pixel(self):\n        test_files = (\n            (\n                24.8,  # epsilon\n                (  # group\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper2.tif\",\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper2I.tif\",\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper2R.tif\",\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper2IR.tif\",\n                )\n            ),\n            (\n                7.3,  # epsilon\n                (  # group\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper4.tif\",\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper4I.tif\",\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper4R.tif\",\n                    \"Tests/images/tiff_gray_2_4_bpp/hopper4IR.tif\",\n                )\n            ),\n        )\n        original = hopper(\"L\")\n        for epsilon, group in test_files:\n            im = Image.open(group[0])\n            self.assertEqual(im.size, (128, 128))\n            self.assertEqual(im.mode, \"L\")\n            self.assert_image_similar(im, original, epsilon)\n            for file in group[1:]:\n                im2 = Image.open(file)\n                self.assertEqual(im2.size, (128, 128))\n                self.assertEqual(im2.mode, \"L\")\n                self.assert_image_equal(im, im2)\n\n    def test_with_underscores(self):\n        kwargs = {'resolution_unit': 'inch',\n                  'x_resolution': 72,\n                  'y_resolution': 36}\n        filename = self.tempfile(\"temp.tif\")\n        hopper(\"RGB\").save(filename, **kwargs)\n        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION\n        im = Image.open(filename)\n\n        # legacy interface\n        self.assertEqual(im.tag[X_RESOLUTION][0][0], 72)\n        self.assertEqual(im.tag[Y_RESOLUTION][0][0], 36)\n\n        # v2 interface\n        self.assertEqual(im.tag_v2[X_RESOLUTION], 72)\n        self.assertEqual(im.tag_v2[Y_RESOLUTION], 36)\n\n    def test_deprecation_warning_with_spaces(self):\n        kwargs = {'resolution unit': 'inch',\n                  'x resolution': 36,\n                  'y resolution': 72}\n        filename = self.tempfile(\"temp.tif\")\n        self.assert_warning(DeprecationWarning,\n                            lambda: hopper(\"RGB\").save(filename, **kwargs))\n        from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION\n\n        im = Image.open(filename)\n\n        # legacy interface\n        self.assertEqual(im.tag[X_RESOLUTION][0][0], 36)\n        self.assertEqual(im.tag[Y_RESOLUTION][0][0], 72)\n\n        # v2 interface\n        self.assertEqual(im.tag_v2[X_RESOLUTION], 36)\n        self.assertEqual(im.tag_v2[Y_RESOLUTION], 72)\n\n    def test_lzw(self):\n        # Act\n        im = Image.open(\"Tests/images/hopper_lzw.tif\")\n\n        # Assert\n        self.assertEqual(im.mode, 'RGB')\n        self.assertEqual(im.size, (128, 128))\n        self.assertEqual(im.format, \"TIFF\")\n        im2 = hopper()\n        self.assert_image_similar(im, im2, 5)\n\n    def test_roundtrip_tiff_uint16(self):\n        # Test an image of all '0' values\n        pixel_value = 0x1234\n        infile = \"Tests/images/uint16_1_4660.tif\"\n        im = Image.open(infile)\n        self.assertEqual(im.getpixel((0, 0)), pixel_value)\n\n        tmpfile = self.tempfile(\"temp.tif\")\n        im.save(tmpfile)\n\n        reloaded = Image.open(tmpfile)\n\n        self.assert_image_equal(im, reloaded)\n\n    def test_tiff_save_all(self):\n        import io\n        import os\n\n        mp = io.BytesIO()\n        with Image.open(\"Tests/images/multipage.tiff\") as im:\n            im.save(mp, format=\"tiff\", save_all=True)\n\n        mp.seek(0, os.SEEK_SET)\n        with Image.open(mp) as im:\n            self.assertEqual(im.n_frames, 3)\n\n    def test_saving_icc_profile(self):\n        # Tests saving TIFF with icc_profile set.\n        # At the time of writing this will only work for non-compressed tiffs\n        # as libtiff does not support embedded ICC profiles, ImageFile._save(..)\n        # however does.\n        im = Image.new('RGB', (1, 1))\n        im.info['icc_profile'] = 'Dummy value'\n        \n        # Try save-load round trip to make sure both handle icc_profile.\n        tmpfile = self.tempfile('temp.tif')\n        im.save(tmpfile, 'TIFF', compression='raw')\n        reloaded = Image.open(tmpfile)\n        \n        self.assertEqual(b'Dummy value', reloaded.info['icc_profile'])\n\n\nif __name__ == '__main__':\n    unittest.main()\n",
        "#!/usr/bin/env python\nimport unittest\nimport sys\nimport time\nimport traceback\nimport platform\nimport os\n\n\nclass PytestLikeResult(unittest.TestResult):\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.start_time = None\n        # Store (test, outcome, info) for each test:\n        #   outcome ∈ { \"passed\", \"failed\", \"error\", \"skipped\" }\n        #   info can hold the exception or skip reason, etc.\n        self.results = []\n\n    def startTestRun(self):\n        \"\"\"Called once before all tests.\"\"\"\n        self.start_time = time.time()\n        # Print a header similar to pytest\n        print(\"=\" * 29 + \" test session starts \" + \"=\" * 29)\n        # You can customize the platform/versions/paths as you like:\n        print(\n            f\"platform {platform.system().lower()} -- Python {platform.python_version()}\"\n        )\n        print(f\"rootdir: {os.path.abspath(os.curdir)}\")\n\n    def stopTestRun(self):\n        \"\"\"Called once after all tests are done.\"\"\"\n        elapsed = time.time() - self.start_time\n        print()  # blank line after final dot\n\n        # Summarize\n        ntests = len(self.results)\n        print(f\"collected {ntests} items\")\n\n        # Show details of failures/errors\n        failures = [r for r in self.results if r[1] == \"failed\"]\n        errors = [r for r in self.results if r[1] == \"error\"]\n\n        if failures:\n            print(\"\\n\" + \"=\" * 35 + \" FAILURES \" + \"=\" * 35)\n            for test, outcome, err_info in failures:\n                test = test.split(\"::\")\n                if len(test) == 3:\n                    test = f\"{test[1]}.{test[2]}\"\n                else:\n                    test = f\"{test[1]}\"\n                print(f\"__________ {test} __________\")\n                self._print_traceback(err_info)\n        if errors:\n            print(\"\\n\" + \"=\" * 35 + \" ERRORS \" + \"=\" * 37)\n            for test, outcome, err_info in errors:\n                test = test.split(\"::\")\n                if len(test) == 3:\n                    test = f\"{test[1]}.{test[2]}\"\n                else:\n                    test = f\"{test[1]}\"\n                print(f\"__________ {test} __________\")\n                self._print_traceback(err_info)\n\n        # Optional short summary lines for passes/fails/skips\n        print(\"\\n==================== short test summary info ====================\")\n        for test, outcome, info in self.results:\n            if outcome in (\"passed\", \"failed\", \"error\", \"skipped\"):\n                print(f\"{outcome.upper()} {test}\")\n\n        # Final one-line summary: “1 failed, 1 errors, 10 passed in 2.04s”\n        passed_count = sum(1 for r in self.results if r[1] == \"passed\")\n        failed_count = len(failures)\n        error_count = len(errors)\n        skipped_count = sum(1 for r in self.results if r[1] == \"skipped\")\n\n        summary_bits = []\n        if failed_count:\n            summary_bits.append(f\"{failed_count} failed\")\n        if error_count:\n            summary_bits.append(f\"{error_count} error{'s' if error_count != 1 else ''}\")\n        if passed_count:\n            summary_bits.append(f\"{passed_count} passed\")\n        if skipped_count:\n            summary_bits.append(f\"{skipped_count} skipped\")\n\n        summary_str = \", \".join(summary_bits) if summary_bits else \"no tests run\"\n        print(\n            f\"=================== {summary_str} in {elapsed:.2f}s ===================\"\n        )\n\n    def startTest(self, test):\n        \"\"\"Called right before each test method.\"\"\"\n        super().startTest(test)\n        # Print a dot or some indicator\n        print(\".\", end=\"\", flush=True)\n\n    def addSuccess(self, test):\n        super().addSuccess(test)\n        self.results.append((self._test_id(test), \"passed\", None))\n\n    def addFailure(self, test, err):\n        super().addFailure(test, err)\n        self.results.append((self._test_id(test), \"failed\", err))\n\n    def addError(self, test, err):\n        super().addError(test, err)\n        self.results.append((self._test_id(test), \"error\", err))\n\n    def addSkip(self, test, reason):\n        super().addSkip(test, reason)\n        self.results.append((self._test_id(test), \"skipped\", reason))\n\n    def _print_traceback(self, err_info):\n        \"\"\"Helper to print the traceback like pytest does.\"\"\"\n        if isinstance(err_info, tuple) and len(err_info) == 3:\n            exc_type, exc_value, tb = err_info\n            traceback.print_exception(exc_type, exc_value, tb, file=sys.stdout)\n        else:\n            print(str(err_info))\n\n    def _test_id(self, test):\n        try:\n            return f\"{test.__class__.__module__}::{test.__class__.__name__}::{test._testMethodName}\"\n        except AttributeError:\n            # Fallback for _ErrorHolder objects\n            return f\"{test.__class__.__module__}::{test.__class__.__name__}\"\n\n\nclass PytestLikeRunner(unittest.TextTestRunner):\n    \"\"\"A custom TextTestRunner that uses the PytestLikeResult.\"\"\"\n\n    resultclass = PytestLikeResult\n\n    def run(self, test):\n        result = self._makeResult()\n        # Overriding run to ensure we call startTestRun/stopTestRun\n        result.startTestRun()\n        test(result)\n        result.stopTestRun()\n        return result\n\n\ndef main():\n    loader = unittest.TestLoader()\n    suite = loader.discover(\"r2e_tests\")  # discover tests in r2e_tests/\n    runner = PytestLikeRunner(verbosity=0)\n    result = runner.run(suite)\n    # Exit with code 0 if all tests passed/skipped, 1 if there were fails/errors\n    sys.exit(not result.wasSuccessful())\n\n\nif __name__ == \"__main__\":\n    main()\n"
    ],
    "test_file_names": [
        "test_1.py",
        "unittest_custom_runner.py"
    ],
    "setup_res_code": 0,
    "setup_res_stdout": "Starting Pillow installation attempts...\nVerifying Pillow installation...\n✅ Pillow installation successful!\nSuccessfully installed Pillow\n",
    "setup_res_stderr": "Using CPython 3.9.21\nCreating virtual environment at: .venv\nActivate with: source .venv/bin/activate\nResolved 12 packages in 17ms\nInstalled 12 packages in 220ms\n + coverage==7.6.10\n + exceptiongroup==1.2.2\n + iniconfig==2.0.0\n + packaging==24.2\n + pluggy==1.5.0\n + pyqt5==5.15.11\n + pyqt5-qt5==5.15.16\n + pyqt5-sip==12.16.1\n + pytest==8.3.4\n + pytest-cov==6.0.0\n + setuptools==75.8.0\n + tomli==2.2.1\nResolved 2 packages in 504ms\nPrepared 1 package in 15.17s\nInstalled 2 packages in 4ms\n + olefile==0.47\n + pillow==4.1.0.dev0 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/pillow_8a9bd2cdcdd7fc9ecd89fa79323463f4d24f53b8)\n",
    "new_commit_res_code": 0,
    "new_commit_res_stdout": "============================= test session starts =============================\nplatform linux -- Python 3.9.21\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/pillow_8a9bd2cdcdd7fc9ecd89fa79323463f4d24f53b8\n........................................\ncollected 40 items\n\n==================== short test summary info ====================\nPASSED test_1::TestFileTiff::test_12bit_rawmode\nPASSED test_1::TestFileTiff::test_32bit_float\nPASSED test_1::TestFileTiff::test_4bit\nPASSED test_1::TestFileTiff::test___str__\nPASSED test_1::TestFileTiff::test__delitem__\nPASSED test_1::TestFileTiff::test__limit_rational_float\nPASSED test_1::TestFileTiff::test__limit_rational_int\nPASSED test_1::TestFileTiff::test_as_dict_deprecation\nPASSED test_1::TestFileTiff::test_bad_exif\nPASSED test_1::TestFileTiff::test_big_endian\nPASSED test_1::TestFileTiff::test_deprecation_warning_with_spaces\nPASSED test_1::TestFileTiff::test_dict\nPASSED test_1::TestFileTiff::test_eoferror\nPASSED test_1::TestFileTiff::test_gimp_tiff\nPASSED test_1::TestFileTiff::test_gray_semibyte_per_pixel\nPASSED test_1::TestFileTiff::test_int_resolution\nPASSED test_1::TestFileTiff::test_invalid_file\nPASSED test_1::TestFileTiff::test_little_endian\nPASSED test_1::TestFileTiff::test_load_byte\nPASSED test_1::TestFileTiff::test_load_double\nPASSED test_1::TestFileTiff::test_load_float\nPASSED test_1::TestFileTiff::test_load_string\nPASSED test_1::TestFileTiff::test_lzw\nPASSED test_1::TestFileTiff::test_mac_tiff\nPASSED test_1::TestFileTiff::test_multipage\nPASSED test_1::TestFileTiff::test_multipage_last_frame\nPASSED test_1::TestFileTiff::test_n_frames\nPASSED test_1::TestFileTiff::test_roundtrip_tiff_uint16\nPASSED test_1::TestFileTiff::test_sampleformat\nPASSED test_1::TestFileTiff::test_sanity\nPASSED test_1::TestFileTiff::test_save_rgba\nPASSED test_1::TestFileTiff::test_save_setting_missing_resolution\nPASSED test_1::TestFileTiff::test_save_unsupported_mode\nPASSED test_1::TestFileTiff::test_saving_icc_profile\nPASSED test_1::TestFileTiff::test_seek\nPASSED test_1::TestFileTiff::test_seek_eof\nPASSED test_1::TestFileTiff::test_tiff_save_all\nPASSED test_1::TestFileTiff::test_with_underscores\nPASSED test_1::TestFileTiff::test_xyres_fallback_tiff\nPASSED test_1::TestFileTiff::test_xyres_tiff\n=================== 40 passed in 0.10s ===================\n",
    "new_commit_res_stderr": "",
    "old_commit_res_code": 1,
    "old_commit_res_stdout": "============================= test session starts =============================\nplatform linux -- Python 3.9.21\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/pillow_8a9bd2cdcdd7fc9ecd89fa79323463f4d24f53b8\n........................................\ncollected 40 items\n\n=================================== ERRORS =====================================\n__________ TestFileTiff.test_xyres_fallback_tiff __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/pillow_8a9bd2cdcdd7fc9ecd89fa79323463f4d24f53b8/r2e_tests/test_1.py\", line 112, in test_xyres_fallback_tiff\n    self.assertEqual(im.info['dpi'], (100., 100.))\nKeyError: 'dpi'\n\n==================== short test summary info ====================\nPASSED test_1::TestFileTiff::test_12bit_rawmode\nPASSED test_1::TestFileTiff::test_32bit_float\nPASSED test_1::TestFileTiff::test_4bit\nPASSED test_1::TestFileTiff::test___str__\nPASSED test_1::TestFileTiff::test__delitem__\nPASSED test_1::TestFileTiff::test__limit_rational_float\nPASSED test_1::TestFileTiff::test__limit_rational_int\nPASSED test_1::TestFileTiff::test_as_dict_deprecation\nPASSED test_1::TestFileTiff::test_bad_exif\nPASSED test_1::TestFileTiff::test_big_endian\nPASSED test_1::TestFileTiff::test_deprecation_warning_with_spaces\nPASSED test_1::TestFileTiff::test_dict\nPASSED test_1::TestFileTiff::test_eoferror\nPASSED test_1::TestFileTiff::test_gimp_tiff\nPASSED test_1::TestFileTiff::test_gray_semibyte_per_pixel\nPASSED test_1::TestFileTiff::test_int_resolution\nPASSED test_1::TestFileTiff::test_invalid_file\nPASSED test_1::TestFileTiff::test_little_endian\nPASSED test_1::TestFileTiff::test_load_byte\nPASSED test_1::TestFileTiff::test_load_double\nPASSED test_1::TestFileTiff::test_load_float\nPASSED test_1::TestFileTiff::test_load_string\nPASSED test_1::TestFileTiff::test_lzw\nPASSED test_1::TestFileTiff::test_mac_tiff\nPASSED test_1::TestFileTiff::test_multipage\nPASSED test_1::TestFileTiff::test_multipage_last_frame\nPASSED test_1::TestFileTiff::test_n_frames\nPASSED test_1::TestFileTiff::test_roundtrip_tiff_uint16\nPASSED test_1::TestFileTiff::test_sampleformat\nPASSED test_1::TestFileTiff::test_sanity\nPASSED test_1::TestFileTiff::test_save_rgba\nPASSED test_1::TestFileTiff::test_save_setting_missing_resolution\nPASSED test_1::TestFileTiff::test_save_unsupported_mode\nPASSED test_1::TestFileTiff::test_saving_icc_profile\nPASSED test_1::TestFileTiff::test_seek\nPASSED test_1::TestFileTiff::test_seek_eof\nPASSED test_1::TestFileTiff::test_tiff_save_all\nPASSED test_1::TestFileTiff::test_with_underscores\nERROR test_1::TestFileTiff::test_xyres_fallback_tiff\nPASSED test_1::TestFileTiff::test_xyres_tiff\n=================== 1 error, 39 passed in 0.07s ===================\n",
    "old_commit_res_stderr": ""
}
PIL/TiffImagePlugin.py Tests/test_file_tiff.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** Missing 'dpi' Information When ResolutionUnit is Absent in TIFF Files

**Description:**
When opening a TIFF image that does not include the `ResolutionUnit` tag, the `dpi` information is not added to the image's metadata. Attempting to access `im.info['dpi']` results in a `KeyError`, which can cause downstream processes to fail when they expect DPI information to be present.

**Example Code:**
```python
from PIL import Image

# Open a TIFF image without the ResolutionUnit tag
im = Image.open("path/to/tiff_without_resolution_unit.tif")

# Attempting to access 'dpi' raises KeyError
print(im.info['dpi'])  # KeyError: 'dpi'
```

**Expected Behavior:**
When the `ResolutionUnit` tag is missing from a TIFF file, the library should default the `dpi` to the values of `x_resolution` and `y_resolution`, interpreting the resolution in inches. This ensures that `im.info['dpi']` is always available, even if the `ResolutionUnit` is not specified.

**Actual Behavior:**
Accessing `im.info['dpi']` raises a `KeyError` because the `dpi` key is not set when the `ResolutionUnit` tag is missing from the TIFF file. This prevents users from reliably accessing DPI information, potentially causing crashes or unexpected behavior in applications that depend on this metadata.
[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### PIL/TiffImagePlugin.py
#
# The Python Imaging Library.
# $Id$
#
# TIFF file handling
#
# TIFF is a flexible, if somewhat aged, image file format originally
# defined by Aldus.  Although TIFF supports a wide variety of pixel
# layouts and compression methods, the name doesn't really stand for
# "thousands of incompatible file formats," it just feels that way.
#
# To read TIFF data from a stream, the stream must be seekable.  For
# progressive decoding, make sure to use TIFF files where the tag
# directory is placed first in the file.
#
# History:
# 1995-09-01 fl   Created
# 1996-05-04 fl   Handle JPEGTABLES tag
# 1996-05-18 fl   Fixed COLORMAP support
# 1997-01-05 fl   Fixed PREDICTOR support
# 1997-08-27 fl   Added support for rational tags (from Perry Stoll)
# 1998-01-10 fl   Fixed seek/tell (from Jan Blom)
# 1998-07-15 fl   Use private names for internal variables
# 1999-06-13 fl   Rewritten for PIL 1.0 (1.0)
# 2000-10-11 fl   Additional fixes for Python 2.0 (1.1)
# 2001-04-17 fl   Fixed rewind support (seek to frame 0) (1.2)
# 2001-05-12 fl   Added write support for more tags (from Greg Couch) (1.3)
# 2001-12-18 fl   Added workaround for broken Matrox library
# 2002-01-18 fl   Don't mess up if photometric tag is missing (D. Alan Stewart)
# 2003-05-19 fl   Check FILLORDER tag
# 2003-09-26 fl   Added RGBa support
# 2004-02-24 fl   Added DPI support; fixed rational write support
# 2005-02-07 fl   Added workaround for broken Corel Draw 10 files
# 2006-01-09 fl   Added support for float/double tags (from Russell Nelson)
#
# Copyright (c) 1997-2006 by Secret Labs AB.  All rights reserved.
# Copyright (c) 1995-1997 by Fredrik Lundh
#
# See the README file for information on usage and redistribution.
#

from __future__ import division, print_function

from . import Image, ImageFile, ImagePalette, TiffTags
from ._binary import i8, o8

import collections
from fractions import Fraction
from numbers import Number, Rational

import io
import itertools
import os
import struct
import sys
import warnings

from .TiffTags import TYPES


__version__ = "1.3.5"
DEBUG = False  # Needs to be merged with the new logging approach.

# Set these to true to force use of libtiff for reading or writing.
READ_LIBTIFF = False
WRITE_LIBTIFF = False
IFD_LEGACY_API = True

II = b"II"  # little-endian (Intel style)
MM = b"MM"  # big-endian (Motorola style)

#
# --------------------------------------------------------------------
# Read TIFF files

# a few tag names, just to make the code below a bit more readable
IMAGEWIDTH = 256
IMAGELENGTH = 257
BITSPERSAMPLE = 258
COMPRESSION = 259
PHOTOMETRIC_INTERPRETATION = 262
FILLORDER = 266
IMAGEDESCRIPTION = 270
STRIPOFFSETS = 273
SAMPLESPERPIXEL = 277
ROWSPERSTRIP = 278
STRIPBYTECOUNTS = 279
X_RESOLUTION = 282
Y_RESOLUTION = 283
PLANAR_CONFIGURATION = 284
RESOLUTION_UNIT = 296
SOFTWARE = 305
DATE_TIME = 306
ARTIST = 315
PREDICTOR = 317
COLORMAP = 320
TILEOFFSETS = 324
EXTRASAMPLES = 338
SAMPLEFORMAT = 339
JPEGTABLES = 347
COPYRIGHT = 33432
IPTC_NAA_CHUNK = 33723  # newsphoto properties
PHOTOSHOP_CHUNK = 34377  # photoshop properties
ICCPROFILE = 34675
EXIFIFD = 34665
XMP = 700

# https://github.com/imagej/ImageJA/blob/master/src/main/java/ij/io/TiffDecoder.java
IMAGEJ_META_DATA_BYTE_COUNTS = 50838
IMAGEJ_META_DATA = 50839

COMPRESSION_INFO = {
    # Compression => pil compression name
    1: "raw",
    2: "tiff_ccitt",
    3: "group3",
    4: "group4",
    5: "tiff_lzw",
    6: "tiff_jpeg",  # obsolete
    7: "jpeg",
    8: "tiff_adobe_deflate",
    32771: "tiff_raw_16",  # 16-bit padding
    32773: "packbits",
    32809: "tiff_thunderscan",
    32946: "tiff_deflate",
    34676: "tiff_sgilog",
    34677: "tiff_sgilog24",
}

COMPRESSION_INFO_REV = {v: k for k, v in COMPRESSION_INFO.items()}

OPEN_INFO = {
    # (ByteOrder, PhotoInterpretation, SampleFormat, FillOrder, BitsPerSample,
    #  ExtraSamples) => mode, rawmode
    (II, 0, (1,), 1, (1,), ()): ("1", "1;I"),
    (MM, 0, (1,), 1, (1,), ()): ("1", "1;I"),
    (II, 0, (1,), 2, (1,), ()): ("1", "1;IR"),
    (MM, 0, (1,), 2, (1,), ()): ("1", "1;IR"),
    (II, 1, (1,), 1, (1,), ()): ("1", "1"),
    (MM, 1, (1,), 1, (1,), ()): ("1", "1"),
    (II, 1, (1,), 2, (1,), ()): ("1", "1;R"),
    (MM, 1, (1,), 2, (1,), ()): ("1", "1;R"),

    (II, 0, (1,), 1, (2,), ()): ("L", "L;2I"),
    (MM, 0, (1,), 1, (2,), ()): ("L", "L;2I"),
    (II, 0, (1,), 2, (2,), ()): ("L", "L;2IR"),
    (MM, 0, (1,), 2, (2,), ()): ("L", "L;2IR"),
    (II, 1, (1,), 1, (2,), ()): ("L", "L;2"),
    (MM, 1, (1,), 1, (2,), ()): ("L", "L;2"),
    (II, 1, (1,), 2, (2,), ()): ("L", "L;2R"),
    (MM, 1, (1,), 2, (2,), ()): ("L", "L;2R"),

    (II, 0, (1,), 1, (4,), ()): ("L", "L;4I"),
    (MM, 0, (1,), 1, (4,), ()): ("L", "L;4I"),
    (II, 0, (1,), 2, (4,), ()): ("L", "L;4IR"),
    (MM, 0, (1,), 2, (4,), ()): ("L", "L;4IR"),
    (II, 1, (1,), 1, (4,), ()): ("L", "L;4"),
    (MM, 1, (1,), 1, (4,), ()): ("L", "L;4"),
    (II, 1, (1,), 2, (4,), ()): ("L", "L;4R"),
    (MM, 1, (1,), 2, (4,), ()): ("L", "L;4R"),

    (II, 0, (1,), 1, (8,), ()): ("L", "L;I"),
    (MM, 0, (1,), 1, (8,), ()): ("L", "L;I"),
    (II, 0, (1,), 2, (8,), ()): ("L", "L;IR"),
    (MM, 0, (1,), 2, (8,), ()): ("L", "L;IR"),
    (II, 1, (1,), 1, (8,), ()): ("L", "L"),
    (MM, 1, (1,), 1, (8,), ()): ("L", "L"),
    (II, 1, (1,), 2, (8,), ()): ("L", "L;R"),
    (MM, 1, (1,), 2, (8,), ()): ("L", "L;R"),

    (II, 1, (1,), 1, (12,), ()): ("I;16", "I;12"),

    (II, 1, (1,), 1, (16,), ()): ("I;16", "I;16"),
    (MM, 1, (1,), 1, (16,), ()): ("I;16B", "I;16B"),
    (II, 1, (2,), 1, (16,), ()): ("I;16S", "I;16S"),
    (MM, 1, (2,), 1, (16,), ()): ("I;16BS", "I;16BS"),

    (II, 0, (3,), 1, (32,), ()): ("F", "F;32F"),
    (MM, 0, (3,), 1, (32,), ()): ("F", "F;32BF"),
    (II, 1, (1,), 1, (32,), ()): ("I", "I;32N"),
    (II, 1, (2,), 1, (32,), ()): ("I", "I;32S"),
    (MM, 1, (2,), 1, (32,), ()): ("I;32BS", "I;32BS"),
    (II, 1, (3,), 1, (32,), ()): ("F", "F;32F"),
    (MM, 1, (3,), 1, (32,), ()): ("F", "F;32BF"),

    (II, 1, (1,), 1, (8, 8), (2,)): ("LA", "LA"),
    (MM, 1, (1,), 1, (8, 8), (2,)): ("LA", "LA"),

    (II, 2, (1,), 1, (8, 8, 8), ()): ("RGB", "RGB"),
    (MM, 2, (1,), 1, (8, 8, 8), ()): ("RGB", "RGB"),
    (II, 2, (1,), 2, (8, 8, 8), ()): ("RGB", "RGB;R"),
    (MM, 2, (1,), 2, (8, 8, 8), ()): ("RGB", "RGB;R"),
    (II, 2, (1,), 1, (8, 8, 8, 8), ()): ("RGBA", "RGBA"),  # missing ExtraSamples
    (MM, 2, (1,), 1, (8, 8, 8, 8), ()): ("RGBA", "RGBA"),  # missing ExtraSamples
    (II, 2, (1,), 1, (8, 8, 8, 8), (0,)): ("RGBX", "RGBX"),
    (MM, 2, (1,), 1, (8, 8, 8, 8), (0,)): ("RGBX", "RGBX"),
    (II, 2, (1,), 1, (8, 8, 8, 8), (1,)): ("RGBA", "RGBa"),
    (MM, 2, (1,), 1, (8, 8, 8, 8), (1,)): ("RGBA", "RGBa"),
    (II, 2, (1,), 1, (8, 8, 8, 8), (2,)): ("RGBA", "RGBA"),
    (MM, 2, (1,), 1, (8, 8, 8, 8), (2,)): ("RGBA", "RGBA"),
    (II, 2, (1,), 1, (8, 8, 8, 8), (999,)): ("RGBA", "RGBA"),  # Corel Draw 10
    (MM, 2, (1,), 1, (8, 8, 8, 8), (999,)): ("RGBA", "RGBA"),  # Corel Draw 10

    (II, 3, (1,), 1, (1,), ()): ("P", "P;1"),
    (MM, 3, (1,), 1, (1,), ()): ("P", "P;1"),
    (II, 3, (1,), 2, (1,), ()): ("P", "P;1R"),
    (MM, 3, (1,), 2, (1,), ()): ("P", "P;1R"),
    (II, 3, (1,), 1, (2,), ()): ("P", "P;2"),
    (MM, 3, (1,), 1, (2,), ()): ("P", "P;2"),
    (II, 3, (1,), 2, (2,), ()): ("P", "P;2R"),
    (MM, 3, (1,), 2, (2,), ()): ("P", "P;2R"),
    (II, 3, (1,), 1, (4,), ()): ("P", "P;4"),
    (MM, 3, (1,), 1, (4,), ()): ("P", "P;4"),
    (II, 3, (1,), 2, (4,), ()): ("P", "P;4R"),
    (MM, 3, (1,), 2, (4,), ()): ("P", "P;4R"),
    (II, 3, (1,), 1, (8,), ()): ("P", "P"),
    (MM, 3, (1,), 1, (8,), ()): ("P", "P"),
    (II, 3, (1,), 1, (8, 8), (2,)): ("PA", "PA"),
    (MM, 3, (1,), 1, (8, 8), (2,)): ("PA", "PA"),
    (II, 3, (1,), 2, (8,), ()): ("P", "P;R"),
    (MM, 3, (1,), 2, (8,), ()): ("P", "P;R"),

    (II, 5, (1,), 1, (8, 8, 8, 8), ()): ("CMYK", "CMYK"),
    (MM, 5, (1,), 1, (8, 8, 8, 8), ()): ("CMYK", "CMYK"),

    (II, 6, (1,), 1, (8, 8, 8), ()): ("YCbCr", "YCbCr"),
    (MM, 6, (1,), 1, (8, 8, 8), ()): ("YCbCr", "YCbCr"),

    (II, 8, (1,), 1, (8, 8, 8), ()): ("LAB", "LAB"),
    (MM, 8, (1,), 1, (8, 8, 8), ()): ("LAB", "LAB"),
}

PREFIXES = [b"MM\000\052", b"II\052\000", b"II\xBC\000"]


def _accept(prefix):
    return prefix[:4] in PREFIXES


def _limit_rational(val, max_val):
    inv = abs(val) > 1
    n_d = IFDRational(1 / val if inv else val).limit_rational(max_val)
    return n_d[::-1] if inv else n_d

##
# Wrapper for TIFF IFDs.

_load_dispatch = {}
_write_dispatch = {}


class IFDRational(Rational):
    """ Implements a rational class where 0/0 is a legal value to match
    the in the wild use of exif rationals.

    e.g., DigitalZoomRatio - 0.00/0.00  indicates that no digital zoom was used
    """

    """ If the denominator is 0, store this as a float('nan'), otherwise store
    as a fractions.Fraction(). Delegate as appropriate

    """

    __slots__ = ('_numerator', '_denominator', '_val')

    def __init__(self, value, denominator=1):
        """
        :param value: either an integer numerator, a
        float/rational/other number, or an IFDRational
        :param denominator: Optional integer denominator
        """
        self._denominator = denominator
        self._numerator = value
        self._val = float(1)

        if isinstance(value, Fraction):
            self._numerator = value.numerator
            self._denominator = value.denominator
            self._val = value

        if isinstance(value, IFDRational):
            self._denominator = value.denominator
            self._numerator = value.numerator
            self._val = value._val
            return

        if denominator == 0:
            self._val = float('nan')
            return

        elif denominator == 1:
            self._val = Fraction(value)
        else:
            self._val = Fraction(value, denominator)

    @property
    def numerator(a):
        return a._numerator

    @property
    def denominator(a):
        return a._denominator

    def limit_rational(self, max_denominator):
        """

        :param max_denominator: Integer, the maximum denominator value
        :returns: Tuple of (numerator, denominator)
        """

        if self.denominator == 0:
            return (self.numerator, self.denominator)

        f = self._val.limit_denominator(max_denominator)
        return (f.numerator, f.denominator)

    def __repr__(self):
        return str(float(self._val))

    def __hash__(self):
        return self._val.__hash__()

    def __eq__(self, other):
        return self._val == other

    def _delegate(op):
        def delegate(self, *args):
            return getattr(self._val, op)(*args)
        return delegate

    """ a = ['add','radd', 'sub', 'rsub','div', 'rdiv', 'mul', 'rmul',
             'truediv', 'rtruediv', 'floordiv',
             'rfloordiv','mod','rmod', 'pow','rpow', 'pos', 'neg',
             'abs', 'trunc', 'lt', 'gt', 'le', 'ge', 'nonzero',
             'ceil', 'floor', 'round']
        print("\n".join("__%s__ = _delegate('__%s__')" % (s,s) for s in a))
        """

    __add__ = _delegate('__add__')
    __radd__ = _delegate('__radd__')
    __sub__ = _delegate('__sub__')
    __rsub__ = _delegate('__rsub__')
    __div__ = _delegate('__div__')
    __rdiv__ = _delegate('__rdiv__')
    __mul__ = _delegate('__mul__')
    __rmul__ = _delegate('__rmul__')
    __truediv__ = _delegate('__truediv__')
    __rtruediv__ = _delegate('__rtruediv__')
    __floordiv__ = _delegate('__floordiv__')
    __rfloordiv__ = _delegate('__rfloordiv__')
    __mod__ = _delegate('__mod__')
    __rmod__ = _delegate('__rmod__')
    __pow__ = _delegate('__pow__')
    __rpow__ = _delegate('__rpow__')
    __pos__ = _delegate('__pos__')
    __neg__ = _delegate('__neg__')
    __abs__ = _delegate('__abs__')
    __trunc__ = _delegate('__trunc__')
    __lt__ = _delegate('__lt__')
    __gt__ = _delegate('__gt__')
    __le__ = _delegate('__le__')
    __ge__ = _delegate('__ge__')
    __nonzero__ = _delegate('__nonzero__')
    __ceil__ = _delegate('__ceil__')
    __floor__ = _delegate('__floor__')
    __round__ = _delegate('__round__')


class ImageFileDirectory_v2(collections.MutableMapping):
    """This class represents a TIFF tag directory.  To speed things up, we
    don't decode tags unless they're asked for.

    Exposes a dictionary interface of the tags in the directory::

        ifd = ImageFileDirectory_v2()
        ifd[key] = 'Some Data'
        ifd.tagtype[key] = 2
        print(ifd[key])
        'Some Data'

    Individual values are returned as the strings or numbers, sequences are
    returned as tuples of the values.

    The tiff metadata type of each item is stored in a dictionary of
    tag types in
    `~PIL.TiffImagePlugin.ImageFileDirectory_v2.tagtype`. The types
    are read from a tiff file, guessed from the type added, or added
    manually.

    Data Structures:

        * self.tagtype = {}

          * Key: numerical tiff tag number
          * Value: integer corresponding to the data type from `~PIL.TiffTags.TYPES`

    .. versionadded:: 3.0.0
    """
    """
    Documentation:

        'internal' data structures:
        * self._tags_v2 = {} Key: numerical tiff tag number
                             Value: decoded data, as tuple for multiple values
        * self._tagdata = {} Key: numerical tiff tag number
                             Value: undecoded byte string from file
        * self._tags_v1 = {} Key: numerical tiff tag number
                             Value: decoded data in the v1 format

    Tags will be found in the private attributes self._tagdata, and in
    self._tags_v2 once decoded.

    Self.legacy_api is a value for internal use, and shouldn't be
    changed from outside code. In cooperation with the
    ImageFileDirectory_v1 class, if legacy_api is true, then decoded
    tags will be populated into both _tags_v1 and _tags_v2. _Tags_v2
    will be used if this IFD is used in the TIFF save routine. Tags
    should be read from tags_v1 if legacy_api == true.

    """

    def __init__(self, ifh=b"II\052\0\0\0\0\0", prefix=None):
        """Initialize an ImageFileDirectory.

        To construct an ImageFileDirectory from a real file, pass the 8-byte
        magic header to the constructor.  To only set the endianness, pass it
        as the 'prefix' keyword argument.

        :param ifh: One of the accepted magic headers (cf. PREFIXES); also sets
              endianness.
        :param prefix: Override the endianness of the file.
        """
        if ifh[:4] not in PREFIXES:
            raise SyntaxError("not a TIFF file (header %r not valid)" % ifh)
        self._prefix = prefix if prefix is not None else ifh[:2]
        if self._prefix == MM:
            self._endian = ">"
        elif self._prefix == II:
            self._endian = "<"
        else:
            raise SyntaxError("not a TIFF IFD")
        self.reset()
        self.next, = self._unpack("L", ifh[4:])
        self._legacy_api = False

    prefix = property(lambda self: self._prefix)
    offset = property(lambda self: self._offset)
    legacy_api = property(lambda self: self._legacy_api)

    @legacy_api.setter
    def legacy_api(self, value):
        raise Exception("Not allowing setting of legacy api")

    def reset(self):
        self._tags_v1 = {}  # will remain empty if legacy_api is false
        self._tags_v2 = {}  # main tag storage
        self._tagdata = {}
        self.tagtype = {}   # added 2008-06-05 by Florian Hoech
        self._next = None
        self._offset = None

    def __str__(self):
        return str(dict(self))

    def as_dict(self):
        """Return a dictionary of the image's tags.

        .. deprecated:: 3.0.0
        """
        warnings.warn("as_dict() is deprecated. " +
                      "Please use dict(ifd) instead.", DeprecationWarning)
        return dict(self)

    def named(self):
        """
        :returns: dict of name|key: value

        Returns the complete tag dictionary, with named tags where possible.
        """
        return dict((TiffTags.lookup(code).name, value)
                    for code, value in self.items())

    def __len__(self):
        return len(set(self._tagdata) | set(self._tags_v2))

    def __getitem__(self, tag):
        if tag not in self._tags_v2:  # unpack on the fly
            data = self._tagdata[tag]
            typ = self.tagtype[tag]
            size, handler = self._load_dispatch[typ]
            self[tag] = handler(self, data, self.legacy_api)  # check type
        val = self._tags_v2[tag]
        if self.legacy_api and not isinstance(val, (tuple, bytes)):
            val = val,
        return val

    def __contains__(self, tag):
        return tag in self._tags_v2 or tag in self._tagdata

    if bytes is str:
        def has_key(self, tag):
            return tag in self

    def __setitem__(self, tag, value):
        self._setitem(tag, value, self.legacy_api)

    def _setitem(self, tag, value, legacy_api):
        basetypes = (Number, bytes, str)
        if bytes is str:
            basetypes += unicode,

        info = TiffTags.lookup(tag)
        values = [value] if isinstance(value, basetypes) else value

        if tag not in self.tagtype:
            if info.type:
                self.tagtype[tag] = info.type
            else:
                self.tagtype[tag] = 7
                if all(isinstance(v, IFDRational) for v in values):
                    self.tagtype[tag] = 5
                elif all(isinstance(v, int) for v in values):
                    if all(v < 2 ** 16 for v in values):
                        self.tagtype[tag] = 3
                    else:
                        self.tagtype[tag] = 4
                elif all(isinstance(v, float) for v in values):
                    self.tagtype[tag] = 12
                else:
                    if bytes is str:
                        # Never treat data as binary by default on Python 2.
                        self.tagtype[tag] = 2
                    else:
                        if all(isinstance(v, str) for v in values):
                            self.tagtype[tag] = 2

        if self.tagtype[tag] == 7 and bytes is not str:
            values = [value.encode("ascii", 'replace') if isinstance(value, str) else value]

        values = tuple(info.cvt_enum(value) for value in values)

        dest = self._tags_v1 if legacy_api else self._tags_v2

        if info.length == 1:
            if legacy_api and self.tagtype[tag] in [5, 10]:
                values = values,
            dest[tag], = values
        else:
            dest[tag] = values

    def __delitem__(self, tag):
        self._tags_v2.pop(tag, None)
        self._tags_v1.pop(tag, None)
        self._tagdata.pop(tag, None)

    def __iter__(self):
        return iter(set(self._tagdata) | set(self._tags_v2))

    def _unpack(self, fmt, data):
        return struct.unpack(self._endian + fmt, data)

    def _pack(self, fmt, *values):
        return struct.pack(self._endian + fmt, *values)

    def _register_loader(idx, size):
        def decorator(func):
            from .TiffTags import TYPES
            if func.__name__.startswith("load_"):
                TYPES[idx] = func.__name__[5:].replace("_", " ")
            _load_dispatch[idx] = size, func
            return func
        return decorator

    def _register_writer(idx):
        def decorator(func):
            _write_dispatch[idx] = func
            return func
        return decorator

    def _register_basic(idx_fmt_name):
        from .TiffTags import TYPES
        idx, fmt, name = idx_fmt_name
        TYPES[idx] = name
        size = struct.calcsize("=" + fmt)
        _load_dispatch[idx] = size, lambda self, data, legacy_api=True: (
            self._unpack("{}{}".format(len(data) // size, fmt), data))
        _write_dispatch[idx] = lambda self, *values: (
            b"".join(self._pack(fmt, value) for value in values))

    list(map(_register_basic,
             [(3, "H", "short"), (4, "L", "long"),
              (6, "b", "signed byte"), (8, "h", "signed short"),
              (9, "l", "signed long"), (11, "f", "float"), (12, "d", "double")]))

    @_register_loader(1, 1)  # Basic type, except for the legacy API.
    def load_byte(self, data, legacy_api=True):
        return data

    @_register_writer(1)  # Basic type, except for the legacy API.
    def write_byte(self, data):
        return data

    @_register_loader(2, 1)
    def load_string(self, data, legacy_api=True):
        if data.endswith(b"\0"):
            data = data[:-1]
        return data.decode("latin-1", "replace")

    @_register_writer(2)
    def write_string(self, value):
        # remerge of https://github.com/python-pillow/Pillow/pull/1416
        if sys.version_info[0] == 2:
            value = value.decode('ascii', 'replace')
        return b"" + value.encode('ascii', 'replace') + b"\0"

    @_register_loader(5, 8)
    def load_rational(self, data, legacy_api=True):
        vals = self._unpack("{}L".format(len(data) // 4), data)
        combine = lambda a, b: (a, b) if legacy_api else IFDRational(a, b)
        return tuple(combine(num, denom)
                     for num, denom in zip(vals[::2], vals[1::2]))

    @_register_writer(5)
    def write_rational(self, *values):
        return b"".join(self._pack("2L", *_limit_rational(frac, 2 ** 31))
                        for frac in values)

    @_register_loader(7, 1)
    def load_undefined(self, data, legacy_api=True):
        return data

    @_register_writer(7)
    def write_undefined(self, value):
        return value

    @_register_loader(10, 8)
    def load_signed_rational(self, data, legacy_api=True):
        vals = self._unpack("{}l".format(len(data) // 4), data)
        combine = lambda a, b: (a, b) if legacy_api else IFDRational(a, b)
        return tuple(combine(num, denom)
                     for num, denom in zip(vals[::2], vals[1::2]))

    @_register_writer(10)
    def write_signed_rational(self, *values):
        return b"".join(self._pack("2L", *_limit_rational(frac, 2 ** 30))
                        for frac in values)

    def _ensure_read(self, fp, size):
        ret = fp.read(size)
        if len(ret) != size:
            raise IOError("Corrupt EXIF data.  " +
                          "Expecting to read %d bytes but only got %d. " %
                          (size, len(ret)))
        return ret

    def load(self, fp):

        self.reset()
        self._offset = fp.tell()

        try:
            for i in range(self._unpack("H", self._ensure_read(fp, 2))[0]):
                tag, typ, count, data = self._unpack("HHL4s", self._ensure_read(fp, 12))
                if DEBUG:
                    tagname = TiffTags.lookup(tag).name
                    typname = TYPES.get(typ, "unknown")
                    print("tag: %s (%d) - type: %s (%d)" %
                          (tagname, tag, typname, typ), end=" ")

                try:
                    unit_size, handler = self._load_dispatch[typ]
                except KeyError:
                    if DEBUG:
                        print("- unsupported type", typ)
                    continue  # ignore unsupported type
                size = count * unit_size
                if size > 4:
                    here = fp.tell()
                    offset, = self._unpack("L", data)
                    if DEBUG:
                        print("Tag Location: %s - Data Location: %s" %
                              (here, offset), end=" ")
                    fp.seek(offset)
                    data = ImageFile._safe_read(fp, size)
                    fp.seek(here)
                else:
                    data = data[:size]

                if len(data) != size:
                    warnings.warn("Possibly corrupt EXIF data.  "
                                  "Expecting to read %d bytes but only got %d. "
                                  "Skipping tag %s" % (size, len(data), tag))
                    continue

                if not data:
                    continue

                self._tagdata[tag] = data
                self.tagtype[tag] = typ

                if DEBUG:
                    if size > 32:
                        print("- value: <table: %d bytes>" % size)
                    else:
                        print("- value:", self[tag])

            self.next, = self._unpack("L", self._ensure_read(fp, 4))
        except IOError as msg:
            warnings.warn(str(msg))
            return

    def save(self, fp):

        if fp.tell() == 0:  # skip TIFF header on subsequent pages
            # tiff header -- PIL always starts the first IFD at offset 8
            fp.write(self._prefix + self._pack("HL", 42, 8))

        # FIXME What about tagdata?
        fp.write(self._pack("H", len(self._tags_v2)))

        entries = []
        offset = fp.tell() + len(self._tags_v2) * 12 + 4
        stripoffsets = None

        # pass 1: convert tags to binary format
        # always write tags in ascending order
        for tag, value in sorted(self._tags_v2.items()):
            if tag == STRIPOFFSETS:
                stripoffsets = len(entries)
            typ = self.tagtype.get(tag)
            if DEBUG:
                print("Tag %s, Type: %s, Value: %s" % (tag, typ, value))
            values = value if isinstance(value, tuple) else (value,)
            data = self._write_dispatch[typ](self, *values)
            if DEBUG:
                tagname = TiffTags.lookup(tag).name
                typname = TYPES.get(typ, "unknown")
                print("save: %s (%d) - type: %s (%d)" %
                      (tagname, tag, typname, typ), end=" ")
                if len(data) >= 16:
                    print("- value: <table: %d bytes>" % len(data))
                else:
                    print("- value:", values)

            # count is sum of lengths for string and arbitrary data
            count = len(data) if typ in [2, 7] else len(values)
            # figure out if data fits into the entry
            if len(data) <= 4:
                entries.append((tag, typ, count, data.ljust(4, b"\0"), b""))
            else:
                entries.append((tag, typ, count, self._pack("L", offset), data))
                offset += (len(data) + 1) // 2 * 2  # pad to word

        # update strip offset data to point beyond auxiliary data
        if stripoffsets is not None:
            tag, typ, count, value, data = entries[stripoffsets]
            if data:
                raise NotImplementedError(
                    "multistrip support not yet implemented")
            value = self._pack("L", self._unpack("L", value)[0] + offset)
            entries[stripoffsets] = tag, typ, count, value, data

        # pass 2: write entries to file
        for tag, typ, count, value, data in entries:
            if DEBUG > 1:
                print(tag, typ, count, repr(value), repr(data))
            fp.write(self._pack("HHL4s", tag, typ, count, value))

        # -- overwrite here for multi-page --
        fp.write(b"\0\0\0\0")  # end of entries

        # pass 3: write auxiliary data to file
        for tag, typ, count, value, data in entries:
            fp.write(data)
            if len(data) & 1:
                fp.write(b"\0")

        return offset

ImageFileDirectory_v2._load_dispatch = _load_dispatch
ImageFileDirectory_v2._write_dispatch = _write_dispatch
for idx, name in TYPES.items():
    name = name.replace(" ", "_")
    setattr(ImageFileDirectory_v2, "load_" + name, _load_dispatch[idx][1])
    setattr(ImageFileDirectory_v2, "write_" + name, _write_dispatch[idx])
del _load_dispatch, _write_dispatch, idx, name


# Legacy ImageFileDirectory support.
class ImageFileDirectory_v1(ImageFileDirectory_v2):
    """This class represents the **legacy** interface to a TIFF tag directory.

    Exposes a dictionary interface of the tags in the directory::

        ifd = ImageFileDirectory_v1()
        ifd[key] = 'Some Data'
        ifd.tagtype[key] = 2
        print(ifd[key])
        ('Some Data',)

    Also contains a dictionary of tag types as read from the tiff image file,
    `~PIL.TiffImagePlugin.ImageFileDirectory_v1.tagtype`.

    Values are returned as a tuple.

    ..  deprecated:: 3.0.0
    """
    def __init__(self, *args, **kwargs):
        ImageFileDirectory_v2.__init__(self, *args, **kwargs)
        self._legacy_api = True

    tags = property(lambda self: self._tags_v1)
    tagdata = property(lambda self: self._tagdata)

    @classmethod
    def from_v2(cls, original):
        """ Returns an
        :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`
        instance with the same data as is contained in the original
        :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`
        instance.

        :returns: :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`

        """

        ifd = cls(prefix=original.prefix)
        ifd._tagdata = original._tagdata
        ifd.tagtype = original.tagtype
        ifd.next = original.next  # an indicator for multipage tiffs
        return ifd

    def to_v2(self):
        """ Returns an
        :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`
        instance with the same data as is contained in the original
        :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`
        instance.

        :returns: :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`

        """

        ifd = ImageFileDirectory_v2(prefix=self.prefix)
        ifd._tagdata = dict(self._tagdata)
        ifd.tagtype = dict(self.tagtype)
        ifd._tags_v2 = dict(self._tags_v2)
        return ifd

    def __contains__(self, tag):
        return tag in self._tags_v1 or tag in self._tagdata

    def __len__(self):
        return len(set(self._tagdata) | set(self._tags_v1))

    def __iter__(self):
        return iter(set(self._tagdata) | set(self._tags_v1))

    def __setitem__(self, tag, value):
        for legacy_api in (False, True):
            self._setitem(tag, value, legacy_api)

    def __getitem__(self, tag):
        if tag not in self._tags_v1:  # unpack on the fly
            data = self._tagdata[tag]
            typ = self.tagtype[tag]
            size, handler = self._load_dispatch[typ]
            for legacy in (False, True):
                self._setitem(tag, handler(self, data, legacy), legacy)
        val = self._tags_v1[tag]
        if not isinstance(val, (tuple, bytes)):
            val = val,
        return val


# undone -- switch this pointer when IFD_LEGACY_API == False
ImageFileDirectory = ImageFileDirectory_v1


##
# Image plugin for TIFF files.

class TiffImageFile(ImageFile.ImageFile):

    format = "TIFF"
    format_description = "Adobe TIFF"

    def _open(self):
        "Open the first image in a TIFF file"

        # Header
        ifh = self.fp.read(8)

        # image file directory (tag dictionary)
        self.tag_v2 = ImageFileDirectory_v2(ifh)

        # legacy tag/ifd entries will be filled in later
        self.tag = self.ifd = None

        # setup frame pointers
        self.__first = self.__next = self.tag_v2.next
        self.__frame = -1
        self.__fp = self.fp
        self._frame_pos = []
        self._n_frames = None
        self._is_animated = None

        if DEBUG:
            print("*** TiffImageFile._open ***")
            print("- __first:", self.__first)
            print("- ifh: ", ifh)

        # and load the first frame
        self._seek(0)

    @property
    def n_frames(self):
        if self._n_frames is None:
            current = self.tell()
            try:
                while True:
                    self._seek(self.tell() + 1)
            except EOFError:
                self._n_frames = self.tell() + 1
            self.seek(current)
        return self._n_frames

    @property
    def is_animated(self):
        if self._is_animated is None:
            current = self.tell()

            try:
                self.seek(1)
                self._is_animated = True
            except EOFError:
                self._is_animated = False

            self.seek(current)
        return self._is_animated

    def seek(self, frame):
        "Select a given frame as current image"
        self._seek(max(frame, 0))  # Questionable backwards compatibility.
        # Create a new core image object on second and
        # subsequent frames in the image. Image may be
        # different size/mode.
        Image._decompression_bomb_check(self.size)
        self.im = Image.core.new(self.mode, self.size)

    def _seek(self, frame):
        self.fp = self.__fp
        while len(self._frame_pos) <= frame:
            if not self.__next:
                raise EOFError("no more images in TIFF file")
            if DEBUG:
                print("Seeking to frame %s, on frame %s, "
                      "__next %s, location: %s" %
                      (frame, self.__frame, self.__next, self.fp.tell()))
            # reset python3 buffered io handle in case fp
            # was passed to libtiff, invalidating the buffer
            self.fp.tell()
            self.fp.seek(self.__next)
            self._frame_pos.append(self.__next)
            if DEBUG:
                print("Loading tags, location: %s" % self.fp.tell())
            self.tag_v2.load(self.fp)
            self.__next = self.tag_v2.next
            self.__frame += 1
        self.fp.seek(self._frame_pos[frame])
        self.tag_v2.load(self.fp)
        # fill the legacy tag/ifd entries
        self.tag = self.ifd = ImageFileDirectory_v1.from_v2(self.tag_v2)
        self.__frame = frame
        self._setup()

    def tell(self):
        "Return the current frame number"
        return self.__frame

    def _decoder(self, rawmode, layer, tile=None):
        "Setup decoder contexts"

        args = None
        if rawmode == "RGB" and self._planar_configuration == 2:
            rawmode = rawmode[layer]
        compression = self._compression
        if compression == "raw":
            args = (rawmode, 0, 1)
        elif compression == "jpeg":
            args = rawmode, ""
            if JPEGTABLES in self.tag_v2:
                # Hack to handle abbreviated JPEG headers
                # FIXME This will fail with more than one value
                self.tile_prefix, = self.tag_v2[JPEGTABLES]
        elif compression == "packbits":
            args = rawmode
        elif compression == "tiff_lzw":
            args = rawmode
            if PREDICTOR in self.tag_v2:
                # Section 14: Differencing Predictor
                self.decoderconfig = (self.tag_v2[PREDICTOR],)

        return args

    def load(self):
        if self.use_load_libtiff:
            return self._load_libtiff()
        return super(TiffImageFile, self).load()

    def _load_libtiff(self):
        """ Overload method triggered when we detect a compressed tiff
            Calls out to libtiff """

        pixel = Image.Image.load(self)

        if self.tile is None:
            raise IOError("cannot load this image")
        if not self.tile:
            return pixel

        self.load_prepare()

        if not len(self.tile) == 1:
            raise IOError("Not exactly one tile")

        # (self._compression, (extents tuple),
        #   0, (rawmode, self._compression, fp))
        extents = self.tile[0][1]
        args = list(self.tile[0][3]) + [self.tag_v2.offset]

        # To be nice on memory footprint, if there's a
        # file descriptor, use that instead of reading
        # into a string in python.
        # libtiff closes the file descriptor, so pass in a dup.
        try:
            fp = hasattr(self.fp, "fileno") and os.dup(self.fp.fileno())
            # flush the file descriptor, prevents error on pypy 2.4+
            # should also eliminate the need for fp.tell for py3
            # in _seek
            if hasattr(self.fp, "flush"):
                self.fp.flush()
        except IOError:
            # io.BytesIO have a fileno, but returns an IOError if
            # it doesn't use a file descriptor.
            fp = False

        if fp:
            args[2] = fp

        decoder = Image._getdecoder(self.mode, 'libtiff', tuple(args),
                                    self.decoderconfig)
        try:
            decoder.setimage(self.im, extents)
        except ValueError:
            raise IOError("Couldn't set the image")

        if hasattr(self.fp, "getvalue"):
            # We've got a stringio like thing passed in. Yay for all in memory.
            # The decoder needs the entire file in one shot, so there's not
            # a lot we can do here other than give it the entire file.
            # unless we could do something like get the address of the
            # underlying string for stringio.
            #
            # Rearranging for supporting byteio items, since they have a fileno
            # that returns an IOError if there's no underlying fp. Easier to
            # deal with here by reordering.
            if DEBUG:
                print("have getvalue. just sending in a string from getvalue")
            n, err = decoder.decode(self.fp.getvalue())
        elif hasattr(self.fp, "fileno"):
            # we've got a actual file on disk, pass in the fp.
            if DEBUG:
                print("have fileno, calling fileno version of the decoder.")
            self.fp.seek(0)
            # 4 bytes, otherwise the trace might error out
            n, err = decoder.decode(b"fpfp")
        else:
            # we have something else.
            if DEBUG:
                print("don't have fileno or getvalue. just reading")
            # UNDONE -- so much for that buffer size thing.
            n, err = decoder.decode(self.fp.read())

        self.tile = []
        self.readonly = 0
        # libtiff closed the fp in a, we need to close self.fp, if possible
        if hasattr(self.fp, 'close'):
            if not self.__next:
                self.fp.close()
        self.fp = None  # might be shared

        if err < 0:
            raise IOError(err)

        self.load_end()

        return Image.Image.load(self)

    def _setup(self):
        "Setup this image object based on current tags"

        if 0xBC01 in self.tag_v2:
            raise IOError("Windows Media Photo files not yet supported")

        # extract relevant tags
        self._compression = COMPRESSION_INFO[self.tag_v2.get(COMPRESSION, 1)]
        self._planar_configuration = self.tag_v2.get(PLANAR_CONFIGURATION, 1)

        # photometric is a required tag, but not everyone is reading
        # the specification
        photo = self.tag_v2.get(PHOTOMETRIC_INTERPRETATION, 0)

        fillorder = self.tag_v2.get(FILLORDER, 1)

        if DEBUG:
            print("*** Summary ***")
            print("- compression:", self._compression)
            print("- photometric_interpretation:", photo)
            print("- planar_configuration:", self._planar_configuration)
            print("- fill_order:", fillorder)

        # size
        xsize = self.tag_v2.get(IMAGEWIDTH)
        ysize = self.tag_v2.get(IMAGELENGTH)
        self.size = xsize, ysize

        if DEBUG:
            print("- size:", self.size)

        sampleFormat = self.tag_v2.get(SAMPLEFORMAT, (1,))
        if (len(sampleFormat) > 1
            and max(sampleFormat) == min(sampleFormat) == 1):
            # SAMPLEFORMAT is properly per band, so an RGB image will
            # be (1,1,1).  But, we don't support per band pixel types,
            # and anything more than one band is a uint8. So, just
            # take the first element. Revisit this if adding support
            # for more exotic images.
            sampleFormat = (1,)

        # mode: check photometric interpretation and bits per pixel
        key = (
            self.tag_v2.prefix, photo, sampleFormat, fillorder,
            self.tag_v2.get(BITSPERSAMPLE, (1,)),
            self.tag_v2.get(EXTRASAMPLES, ())
            )
        if DEBUG:
            print("format key:", key)
        try:
            self.mode, rawmode = OPEN_INFO[key]
        except KeyError:
            if DEBUG:
                print("- unsupported format")
            raise SyntaxError("unknown pixel mode")

        if DEBUG:
            print("- raw mode:", rawmode)
            print("- pil mode:", self.mode)

        self.info["compression"] = self._compression

        xres = self.tag_v2.get(X_RESOLUTION, 1)
        yres = self.tag_v2.get(Y_RESOLUTION, 1)

        if xres and yres:
            resunit = self.tag_v2.get(RESOLUTION_UNIT, 1)
            if resunit == 2:  # dots per inch
                self.info["dpi"] = xres, yres
            elif resunit == 3:  # dots per centimeter. convert to dpi
                self.info["dpi"] = xres * 2.54, yres * 2.54
            else:  # No absolute unit of measurement
                self.info["resolution"] = xres, yres

        # build tile descriptors
        x = y = l = 0
        self.tile = []
        self.use_load_libtiff = False
        if STRIPOFFSETS in self.tag_v2:
            # striped image
            offsets = self.tag_v2[STRIPOFFSETS]
            h = self.tag_v2.get(ROWSPERSTRIP, ysize)
            w = self.size[0]
            if READ_LIBTIFF or self._compression in ["tiff_ccitt", "group3",
                                                     "group4", "tiff_jpeg",
                                                     "tiff_adobe_deflate",
                                                     "tiff_thunderscan",
                                                     "tiff_deflate",
                                                     "tiff_sgilog",
                                                     "tiff_sgilog24",
                                                     "tiff_raw_16"]:
                # if DEBUG:
                #     print("Activating g4 compression for whole file")

                # Decoder expects entire file as one tile.
                # There's a buffer size limit in load (64k)
                # so large g4 images will fail if we use that
                # function.
                #
                # Setup the one tile for the whole image, then
                # use the _load_libtiff function.

                self.use_load_libtiff = True

                # libtiff handles the fillmode for us, so 1;IR should
                # actually be 1;I. Including the R double reverses the
                # bits, so stripes of the image are reversed.  See
                # https://github.com/python-pillow/Pillow/issues/279
                if fillorder == 2:
                    key = (
                        self.tag_v2.prefix, photo, sampleFormat, 1,
                        self.tag_v2.get(BITSPERSAMPLE, (1,)),
                        self.tag_v2.get(EXTRASAMPLES, ())
                        )
                    if DEBUG:
                        print("format key:", key)
                    # this should always work, since all the
                    # fillorder==2 modes have a corresponding
                    # fillorder=1 mode
                    self.mode, rawmode = OPEN_INFO[key]
                # libtiff always returns the bytes in native order.
                # we're expecting image byte order. So, if the rawmode
                # contains I;16, we need to convert from native to image
                # byte order.
                if self.mode in ('I;16B', 'I;16') and 'I;16' in rawmode:
                    rawmode = 'I;16N'

                # Offset in the tile tuple is 0, we go from 0,0 to
                # w,h, and we only do this once -- eds
                a = (rawmode, self._compression, False)
                self.tile.append(
                    (self._compression,
                     (0, 0, w, ysize),
                     0, a))
                a = None

            else:
                for i, offset in enumerate(offsets):
                    a = self._decoder(rawmode, l, i)
                    self.tile.append(
                        (self._compression,
                            (0, min(y, ysize), w, min(y+h, ysize)),
                            offset, a))
                    if DEBUG:
                        print("tiles: ", self.tile)
                    y = y + h
                    if y >= self.size[1]:
                        x = y = 0
                        l += 1
                    a = None
        elif TILEOFFSETS in self.tag_v2:
            # tiled image
            w = self.tag_v2.get(322)
            h = self.tag_v2.get(323)
            a = None
            for o in self.tag_v2[TILEOFFSETS]:
                if not a:
                    a = self._decoder(rawmode, l)
                # FIXME: this doesn't work if the image size
                # is not a multiple of the tile size...
                self.tile.append(
                    (self._compression,
                        (x, y, x+w, y+h),
                        o, a))
                x = x + w
                if x >= self.size[0]:
                    x, y = 0, y + h
                    if y >= self.size[1]:
                        x = y = 0
                        l += 1
                        a = None
        else:
            if DEBUG:
                print("- unsupported data organization")
            raise SyntaxError("unknown data organization")

        # Fix up info.
        if ICCPROFILE in self.tag_v2:
            self.info['icc_profile'] = self.tag_v2[ICCPROFILE]

        # fixup palette descriptor

        if self.mode == "P":
            palette = [o8(b // 256) for b in self.tag_v2[COLORMAP]]
            self.palette = ImagePalette.raw("RGB;L", b"".join(palette))
#
# --------------------------------------------------------------------
# Write TIFF files

# little endian is default except for image modes with
# explicit big endian byte-order

SAVE_INFO = {
    # mode => rawmode, byteorder, photometrics,
    #           sampleformat, bitspersample, extra
    "1": ("1", II, 1, 1, (1,), None),
    "L": ("L", II, 1, 1, (8,), None),
    "LA": ("LA", II, 1, 1, (8, 8), 2),
    "P": ("P", II, 3, 1, (8,), None),
    "PA": ("PA", II, 3, 1, (8, 8), 2),
    "I": ("I;32S", II, 1, 2, (32,), None),
    "I;16": ("I;16", II, 1, 1, (16,), None),
    "I;16S": ("I;16S", II, 1, 2, (16,), None),
    "F": ("F;32F", II, 1, 3, (32,), None),
    "RGB": ("RGB", II, 2, 1, (8, 8, 8), None),
    "RGBX": ("RGBX", II, 2, 1, (8, 8, 8, 8), 0),
    "RGBA": ("RGBA", II, 2, 1, (8, 8, 8, 8), 2),
    "CMYK": ("CMYK", II, 5, 1, (8, 8, 8, 8), None),
    "YCbCr": ("YCbCr", II, 6, 1, (8, 8, 8), None),
    "LAB": ("LAB", II, 8, 1, (8, 8, 8), None),

    "I;32BS": ("I;32BS", MM, 1, 2, (32,), None),
    "I;16B": ("I;16B", MM, 1, 1, (16,), None),
    "I;16BS": ("I;16BS", MM, 1, 2, (16,), None),
    "F;32BF": ("F;32BF", MM, 1, 3, (32,), None),
}


def _save(im, fp, filename):

    try:
        rawmode, prefix, photo, format, bits, extra = SAVE_INFO[im.mode]
    except KeyError:
        raise IOError("cannot write mode %s as TIFF" % im.mode)

    ifd = ImageFileDirectory_v2(prefix=prefix)

    compression = im.encoderinfo.get('compression',
                                     im.info.get('compression', 'raw'))

    libtiff = WRITE_LIBTIFF or compression != 'raw'

    # required for color libtiff images
    ifd[PLANAR_CONFIGURATION] = getattr(im, '_planar_configuration', 1)

    ifd[IMAGEWIDTH] = im.size[0]
    ifd[IMAGELENGTH] = im.size[1]

    # write any arbitrary tags passed in as an ImageFileDirectory
    info = im.encoderinfo.get("tiffinfo", {})
    if DEBUG:
        print("Tiffinfo Keys: %s" % list(info))
    if isinstance(info, ImageFileDirectory_v1):
        info = info.to_v2()
    for key in info:
        ifd[key] = info.get(key)
        try:
            ifd.tagtype[key] = info.tagtype[key]
        except:
            pass  # might not be an IFD, Might not have populated type

    # additions written by Greg Couch, gregc@cgl.ucsf.edu
    # inspired by image-sig posting from Kevin Cazabon, kcazabon@home.com
    if hasattr(im, 'tag_v2'):
        # preserve tags from original TIFF image file
        for key in (RESOLUTION_UNIT, X_RESOLUTION, Y_RESOLUTION,
                    IPTC_NAA_CHUNK, PHOTOSHOP_CHUNK, XMP):
            if key in im.tag_v2:
                ifd[key] = im.tag_v2[key]
                ifd.tagtype[key] = im.tag_v2.tagtype[key]

    # preserve ICC profile (should also work when saving other formats
    # which support profiles as TIFF) -- 2008-06-06 Florian Hoech
    if "icc_profile" in im.info:
        ifd[ICCPROFILE] = im.info["icc_profile"]

    for key, name in [(IMAGEDESCRIPTION, "description"),
                      (X_RESOLUTION, "resolution"),
                      (Y_RESOLUTION, "resolution"),
                      (X_RESOLUTION, "x_resolution"),
                      (Y_RESOLUTION, "y_resolution"),
                      (RESOLUTION_UNIT, "resolution_unit"),
                      (SOFTWARE, "software"),
                      (DATE_TIME, "date_time"),
                      (ARTIST, "artist"),
                      (COPYRIGHT, "copyright")]:
        name_with_spaces = name.replace("_", " ")
        if "_" in name and name_with_spaces in im.encoderinfo:
            warnings.warn("%r is deprecated; use %r instead" %
                          (name_with_spaces, name), DeprecationWarning)
            ifd[key] = im.encoderinfo[name.replace("_", " ")]
        if name in im.encoderinfo:
            ifd[key] = im.encoderinfo[name]

    dpi = im.encoderinfo.get("dpi")
    if dpi:
        ifd[RESOLUTION_UNIT] = 2
        ifd[X_RESOLUTION] = dpi[0]
        ifd[Y_RESOLUTION] = dpi[1]

    if bits != (1,):
        ifd[BITSPERSAMPLE] = bits
        if len(bits) != 1:
            ifd[SAMPLESPERPIXEL] = len(bits)
    if extra is not None:
        ifd[EXTRASAMPLES] = extra
    if format != 1:
        ifd[SAMPLEFORMAT] = format

    ifd[PHOTOMETRIC_INTERPRETATION] = photo

    if im.mode == "P":
        lut = im.im.getpalette("RGB", "RGB;L")
        ifd[COLORMAP] = tuple(i8(v) * 256 for v in lut)
    # data orientation
    stride = len(bits) * ((im.size[0]*bits[0]+7)//8)
    ifd[ROWSPERSTRIP] = im.size[1]
    ifd[STRIPBYTECOUNTS] = stride * im.size[1]
    ifd[STRIPOFFSETS] = 0  # this is adjusted by IFD writer
    # no compression by default:
    ifd[COMPRESSION] = COMPRESSION_INFO_REV.get(compression, 1)

    if libtiff:
        if DEBUG:
            print("Saving using libtiff encoder")
            print("Items: %s" % sorted(ifd.items()))
        _fp = 0
        if hasattr(fp, "fileno"):
            try:
                fp.seek(0)
                _fp = os.dup(fp.fileno())
            except io.UnsupportedOperation:
                pass

        # STRIPOFFSETS and STRIPBYTECOUNTS are added by the library
        # based on the data in the strip.
        blocklist = [STRIPOFFSETS, STRIPBYTECOUNTS]
        atts = {}
        # bits per sample is a single short in the tiff directory, not a list.
        atts[BITSPERSAMPLE] = bits[0]
        # Merge the ones that we have with (optional) more bits from
        # the original file, e.g x,y resolution so that we can
        # save(load('')) == original file.
        legacy_ifd = {}
        if hasattr(im, 'tag'):
            legacy_ifd = im.tag.to_v2()
        for tag, value in itertools.chain(ifd.items(),
                                          getattr(im, 'tag_v2', {}).items(),
                                          legacy_ifd.items()):
            # Libtiff can only process certain core items without adding
            # them to the custom dictionary. It will segfault if it attempts
            # to add a custom tag without the dictionary entry
            #
            # UNDONE --  add code for the custom dictionary
            if tag not in TiffTags.LIBTIFF_CORE:
                continue
            if tag not in atts and tag not in blocklist:
                if isinstance(value, unicode if bytes is str else str):
                    atts[tag] = value.encode('ascii', 'replace') + b"\0"
                elif isinstance(value, IFDRational):
                    atts[tag] = float(value)
                else:
                    atts[tag] = value

        if DEBUG:
            print("Converted items: %s" % sorted(atts.items()))

        # libtiff always expects the bytes in native order.
        # we're storing image byte order. So, if the rawmode
        # contains I;16, we need to convert from native to image
        # byte order.
        if im.mode in ('I;16B', 'I;16'):
            rawmode = 'I;16N'

        a = (rawmode, compression, _fp, filename, atts)
        # print(im.mode, compression, a, im.encoderconfig)
        e = Image._getencoder(im.mode, 'libtiff', a, im.encoderconfig)
        e.setimage(im.im, (0, 0)+im.size)
        while True:
            # undone, change to self.decodermaxblock:
            l, s, d = e.encode(16*1024)
            if not _fp:
                fp.write(d)
            if s:
                break
        if s < 0:
            raise IOError("encoder error %d when writing image file" % s)

    else:
        offset = ifd.save(fp)

        ImageFile._save(im, fp, [
            ("raw", (0, 0)+im.size, offset, (rawmode, stride, 1))
            ])

    # -- helper for multi-page save --
    if "_debug_multipage" in im.encoderinfo:
        # just to access o32 and o16 (using correct byte order)
        im._debug_multipage = ifd

class AppendingTiffWriter:
    fieldSizes = [
        0,  # None
        1,  # byte
        1,  # ascii
        2,  # short
        4,  # long
        8,  # rational
        1,  # sbyte
        1,  # undefined
        2,  # sshort
        4,  # slong
        8,  # srational
        4,  # float
        8,  # double
    ]

    #    StripOffsets = 273
    #    FreeOffsets = 288
    #    TileOffsets = 324
    #    JPEGQTables = 519
    #    JPEGDCTables = 520
    #    JPEGACTables = 521
    Tags = {273, 288, 324, 519, 520, 521}

    def __init__(self, fn, new=False):
        if hasattr(fn, 'read'):
            self.f = fn
            self.close_fp = False
        else:
            self.name = fn
            self.close_fp = True
            try:
                self.f = io.open(fn, "w+b" if new else "r+b")
            except IOError:
                self.f = io.open(fn, "w+b")
        self.beginning = self.f.tell()
        self.setup()

    def setup(self):
        # Reset everything.
        self.f.seek(self.beginning, os.SEEK_SET)

        self.whereToWriteNewIFDOffset = None
        self.offsetOfNewPage = 0

        self.IIMM = IIMM = self.f.read(4)
        if not IIMM:
            # empty file - first page
            self.isFirst = True
            return

        self.isFirst = False
        if IIMM == b"II\x2a\x00":
            self.setEndian("<")
        elif IIMM == b"MM\x00\x2a":
            self.setEndian(">")
        else:
            raise RuntimeError("Invalid TIFF file header")

        self.skipIFDs()
        self.goToEnd()

    def finalize(self):
        if self.isFirst:
            return

        # fix offsets
        self.f.seek(self.offsetOfNewPage)

        IIMM = self.f.read(4)
        if not IIMM:
            # raise RuntimeError("nothing written into new page")
            # Make it easy to finish a frame without committing to a new one.
            return

        if IIMM != self.IIMM:
            raise RuntimeError("IIMM of new page doesn't match IIMM of "
                               "first page")

        IFDoffset = self.readLong()
        IFDoffset += self.offsetOfNewPage
        self.f.seek(self.whereToWriteNewIFDOffset)
        self.writeLong(IFDoffset)
        self.f.seek(IFDoffset)
        self.fixIFD()

    def newFrame(self):
        # Call this to finish a frame.
        self.finalize()
        self.setup()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        if self.close_fp:
            self.close()
        return False

    def tell(self):
        return self.f.tell() - self.offsetOfNewPage

    def seek(self, offset, whence):
        if whence == os.SEEK_SET:
            offset += self.offsetOfNewPage

        self.f.seek(offset, whence)
        return self.tell()

    def goToEnd(self):
        self.f.seek(0, os.SEEK_END)
        pos = self.f.tell()

        # pad to 16 byte boundary
        padBytes = 16 - pos % 16
        if 0 < padBytes < 16:
            self.f.write(bytes(bytearray(padBytes)))
        self.offsetOfNewPage = self.f.tell()

    def setEndian(self, endian):
        self.endian = endian
        self.longFmt = self.endian + "L"
        self.shortFmt = self.endian + "H"
        self.tagFormat = self.endian + "HHL"

    def skipIFDs(self):
        while True:
            IFDoffset = self.readLong()
            if IFDoffset == 0:
                self.whereToWriteNewIFDOffset = self.f.tell() - 4
                break

            self.f.seek(IFDoffset)
            numTags = self.readShort()
            self.f.seek(numTags * 12, os.SEEK_CUR)

    def write(self, data):
        return self.f.write(data)

    def readShort(self):
        value, = struct.unpack(self.shortFmt, self.f.read(2))
        return value

    def readLong(self):
        value, = struct.unpack(self.longFmt, self.f.read(4))
        return value

    def rewriteLastShortToLong(self, value):
        self.f.seek(-2, os.SEEK_CUR)
        bytesWritten = self.f.write(struct.pack(self.longFmt, value))
        if bytesWritten is not None and bytesWritten != 4:
            raise RuntimeError("wrote only %u bytes but wanted 4" %
                               bytesWritten)

    def rewriteLastShort(self, value):
        self.f.seek(-2, os.SEEK_CUR)
        bytesWritten = self.f.write(struct.pack(self.shortFmt, value))
        if bytesWritten is not None and bytesWritten != 2:
            raise RuntimeError("wrote only %u bytes but wanted 2" %
                               bytesWritten)

    def rewriteLastLong(self, value):
        self.f.seek(-4, os.SEEK_CUR)
        bytesWritten = self.f.write(struct.pack(self.longFmt, value))
        if bytesWritten is not None and bytesWritten != 4:
            raise RuntimeError("wrote only %u bytes but wanted 4" %
                               bytesWritten)

    def writeShort(self, value):
        bytesWritten = self.f.write(struct.pack(self.shortFmt, value))
        if bytesWritten is not None and bytesWritten != 2:
            raise RuntimeError("wrote only %u bytes but wanted 2" %
                               bytesWritten)

    def writeLong(self, value):
        bytesWritten = self.f.write(struct.pack(self.longFmt, value))
        if bytesWritten is not None and bytesWritten != 4:
            raise RuntimeError("wrote only %u bytes but wanted 4" %
                               bytesWritten)

    def close(self):
        self.finalize()
        self.f.close()

    def fixIFD(self):
        numTags = self.readShort()
        #trace("fixing IFD at %X; number of tags: %u (0x%X)", self.f.tell()-2,
        #      numTags, numTags)

        for i in range(numTags):
            tag, fieldType, count = struct.unpack(self.tagFormat, self.f.read(8))
            #trace("  at %X: tag %u (0x%X), type %u, count %u", self.f.tell()-8,
            #      tag, tag, fieldType, count)

            fieldSize = self.fieldSizes[fieldType]
            totalSize = fieldSize * count
            isLocal = (totalSize <= 4)
            if not isLocal:
                offset = self.readLong()
                offset += self.offsetOfNewPage
                self.rewriteLastLong(offset)

            if tag in self.Tags:
                curPos = self.f.tell()

                if isLocal:
                    self.fixOffsets(count, isShort=(fieldSize == 2),
                                    isLong=(fieldSize == 4))
                    self.f.seek(curPos + 4)
                else:
                    self.f.seek(offset)
                    self.fixOffsets(count, isShort=(fieldSize == 2),
                                    isLong=(fieldSize == 4))
                    self.f.seek(curPos)

                offset = curPos = None

            elif isLocal:
                # skip the locally stored value that is not an offset
                self.f.seek(4, os.SEEK_CUR)

    def fixOffsets(self, count, isShort=False, isLong=False):
        if not isShort and not isLong:
            raise RuntimeError("offset is neither short nor long")

        for i in range(count):
            offset = self.readShort() if isShort else self.readLong()
            offset += self.offsetOfNewPage
            if isShort and offset >= 65536:
                # offset is now too large - we must convert shorts to longs
                if count != 1:
                    raise RuntimeError("not implemented")  # XXX TODO

                # simple case - the offset is just one and therefore it is
                # local (not referenced with another offset)
                self.rewriteLastShortToLong(offset)
                self.f.seek(-10, os.SEEK_CUR)
                self.writeShort(4)  # rewrite the type to LONG
                self.f.seek(8, os.SEEK_CUR)
            elif isShort:
                self.rewriteLastShort(offset)
            else:
                self.rewriteLastLong(offset)

def _save_all(im, fp, filename):
    if not hasattr(im, "n_frames"):
        return _save(im, fp, filename)

    cur_idx = im.tell()
    try:
        with AppendingTiffWriter(fp) as tf:
            for idx in range(im.n_frames):
                im.seek(idx)
                im.load()
                _save(im, tf, filename)
                tf.newFrame()
    finally:
        im.seek(cur_idx)

#
# --------------------------------------------------------------------
# Register

Image.register_open(TiffImageFile.format, TiffImageFile, _accept)
Image.register_save(TiffImageFile.format, _save)
Image.register_save_all(TiffImageFile.format, _save_all)

Image.register_extension(TiffImageFile.format, ".tif")
Image.register_extension(TiffImageFile.format, ".tiff")

Image.register_mime(TiffImageFile.format, "image/tiff")

```
--- END FILE ---

Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.

Every *SEARCH/REPLACE* edit must use this format:
1. The file path
2. The start of search block: <<<<<<< SEARCH
3. A contiguous chunk of lines to search for in the existing source code
4. The dividing line: =======
5. The lines to replace into the source code
6. The end of the replace block: >>>>>>> REPLACE

Here is an example:

```python
### mathweb/flask/app.py
<<<<<<< SEARCH
from flask import Flask
=======
import math
from flask import Flask
>>>>>>> REPLACE
```
</solution>

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
[ISSUE]
**Title:** Missing 'dpi' Information When ResolutionUnit is Absent in TIFF Files

**Description:**
When opening a TIFF image that does not include the `ResolutionUnit` tag, the `dpi` information is not added to the image's metadata. Attempting to access `im.info['dpi']` results in a `KeyError`, which can cause downstream processes to fail when they expect DPI information to be present.

**Example Code:**
```python
from PIL import Image

# Open a TIFF image without the ResolutionUnit tag
im = Image.open("path/to/tiff_without_resolution_unit.tif")

# Attempting to access 'dpi' raises KeyError
print(im.info['dpi'])  # KeyError: 'dpi'
```

**Expected Behavior:**
When the `ResolutionUnit` tag is missing from a TIFF file, the library should default the `dpi` to the values of `x_resolution` and `y_resolution`, interpreting the resolution in inches. This ensures that `im.info['dpi']` is always available, even if the `ResolutionUnit` is not specified.

**Actual Behavior:**
Accessing `im.info['dpi']` raises a `KeyError` because the `dpi` key is not set when the `ResolutionUnit` tag is missing from the TIFF file. This prevents users from reliably accessing DPI information, potentially causing crashes or unexpected behavior in applications that depend on this metadata.
[/ISSUE]
{
    "TestFileTiff.test_12bit_rawmode": "PASSED",
    "TestFileTiff.test_32bit_float": "PASSED",
    "TestFileTiff.test_4bit": "PASSED",
    "TestFileTiff.test___str__": "PASSED",
    "TestFileTiff.test__delitem__": "PASSED",
    "TestFileTiff.test__limit_rational_float": "PASSED",
    "TestFileTiff.test__limit_rational_int": "PASSED",
    "TestFileTiff.test_as_dict_deprecation": "PASSED",
    "TestFileTiff.test_bad_exif": "PASSED",
    "TestFileTiff.test_big_endian": "PASSED",
    "TestFileTiff.test_deprecation_warning_with_spaces": "PASSED",
    "TestFileTiff.test_dict": "PASSED",
    "TestFileTiff.test_eoferror": "PASSED",
    "TestFileTiff.test_gimp_tiff": "PASSED",
    "TestFileTiff.test_gray_semibyte_per_pixel": "PASSED",
    "TestFileTiff.test_int_resolution": "PASSED",
    "TestFileTiff.test_invalid_file": "PASSED",
    "TestFileTiff.test_little_endian": "PASSED",
    "TestFileTiff.test_load_byte": "PASSED",
    "TestFileTiff.test_load_double": "PASSED",
    "TestFileTiff.test_load_float": "PASSED",
    "TestFileTiff.test_load_string": "PASSED",
    "TestFileTiff.test_lzw": "PASSED",
    "TestFileTiff.test_mac_tiff": "PASSED",
    "TestFileTiff.test_multipage": "PASSED",
    "TestFileTiff.test_multipage_last_frame": "PASSED",
    "TestFileTiff.test_n_frames": "PASSED",
    "TestFileTiff.test_roundtrip_tiff_uint16": "PASSED",
    "TestFileTiff.test_sampleformat": "PASSED",
    "TestFileTiff.test_sanity": "PASSED",
    "TestFileTiff.test_save_rgba": "PASSED",
    "TestFileTiff.test_save_setting_missing_resolution": "PASSED",
    "TestFileTiff.test_save_unsupported_mode": "PASSED",
    "TestFileTiff.test_saving_icc_profile": "PASSED",
    "TestFileTiff.test_seek": "PASSED",
    "TestFileTiff.test_seek_eof": "PASSED",
    "TestFileTiff.test_tiff_save_all": "PASSED",
    "TestFileTiff.test_with_underscores": "PASSED",
    "TestFileTiff.test_xyres_fallback_tiff": "PASSED",
    "TestFileTiff.test_xyres_tiff": "PASSED"
}
diff --git a/PIL/TiffImagePlugin.py b/PIL/TiffImagePlugin.py
index e5009d0f1..505025bb8 100644
--- a/PIL/TiffImagePlugin.py
+++ b/PIL/TiffImagePlugin.py
@@ -1163,11 +1163,15 @@ class TiffImageFile(ImageFile.ImageFile):
         yres = self.tag_v2.get(Y_RESOLUTION, 1)
 
         if xres and yres:
-            resunit = self.tag_v2.get(RESOLUTION_UNIT, 1)
+            resunit = self.tag_v2.get(RESOLUTION_UNIT)
             if resunit == 2:  # dots per inch
                 self.info["dpi"] = xres, yres
             elif resunit == 3:  # dots per centimeter. convert to dpi
                 self.info["dpi"] = xres * 2.54, yres * 2.54
+            elif resunit == None: # used to default to 1, but now 2)
+                self.info["dpi"] = xres, yres
+                # For backward compatibility, we also preserve the old behavior.
+                self.info["resolution"] = xres, yres
             else:  # No absolute unit of measurement
                 self.info["resolution"] = xres, yres
 

{"PIL/TiffImagePlugin.py": "#\n# The Python Imaging Library.\n# $Id$\n#\n# TIFF file handling\n#\n# TIFF is a flexible, if somewhat aged, image file format originally\n# defined by Aldus.  Although TIFF supports a wide variety of pixel\n# layouts and compression methods, the name doesn't really stand for\n# \"thousands of incompatible file formats,\" it just feels that way.\n#\n# To read TIFF data from a stream, the stream must be seekable.  For\n# progressive decoding, make sure to use TIFF files where the tag\n# directory is placed first in the file.\n#\n# History:\n# 1995-09-01 fl   Created\n# 1996-05-04 fl   Handle JPEGTABLES tag\n# 1996-05-18 fl   Fixed COLORMAP support\n# 1997-01-05 fl   Fixed PREDICTOR support\n# 1997-08-27 fl   Added support for rational tags (from Perry Stoll)\n# 1998-01-10 fl   Fixed seek/tell (from Jan Blom)\n# 1998-07-15 fl   Use private names for internal variables\n# 1999-06-13 fl   Rewritten for PIL 1.0 (1.0)\n# 2000-10-11 fl   Additional fixes for Python 2.0 (1.1)\n# 2001-04-17 fl   Fixed rewind support (seek to frame 0) (1.2)\n# 2001-05-12 fl   Added write support for more tags (from Greg Couch) (1.3)\n# 2001-12-18 fl   Added workaround for broken Matrox library\n# 2002-01-18 fl   Don't mess up if photometric tag is missing (D. Alan Stewart)\n# 2003-05-19 fl   Check FILLORDER tag\n# 2003-09-26 fl   Added RGBa support\n# 2004-02-24 fl   Added DPI support; fixed rational write support\n# 2005-02-07 fl   Added workaround for broken Corel Draw 10 files\n# 2006-01-09 fl   Added support for float/double tags (from Russell Nelson)\n#\n# Copyright (c) 1997-2006 by Secret Labs AB.  All rights reserved.\n# Copyright (c) 1995-1997 by Fredrik Lundh\n#\n# See the README file for information on usage and redistribution.\n#\n\nfrom __future__ import division, print_function\n\nfrom . import Image, ImageFile, ImagePalette, TiffTags\nfrom ._binary import i8, o8\n\nimport collections\nfrom fractions import Fraction\nfrom numbers import Number, Rational\n\nimport io\nimport itertools\nimport os\nimport struct\nimport sys\nimport warnings\n\nfrom .TiffTags import TYPES\n\n\n__version__ = \"1.3.5\"\nDEBUG = False  # Needs to be merged with the new logging approach.\n\n# Set these to true to force use of libtiff for reading or writing.\nREAD_LIBTIFF = False\nWRITE_LIBTIFF = False\nIFD_LEGACY_API = True\n\nII = b\"II\"  # little-endian (Intel style)\nMM = b\"MM\"  # big-endian (Motorola style)\n\n#\n# --------------------------------------------------------------------\n# Read TIFF files\n\n# a few tag names, just to make the code below a bit more readable\nIMAGEWIDTH = 256\nIMAGELENGTH = 257\nBITSPERSAMPLE = 258\nCOMPRESSION = 259\nPHOTOMETRIC_INTERPRETATION = 262\nFILLORDER = 266\nIMAGEDESCRIPTION = 270\nSTRIPOFFSETS = 273\nSAMPLESPERPIXEL = 277\nROWSPERSTRIP = 278\nSTRIPBYTECOUNTS = 279\nX_RESOLUTION = 282\nY_RESOLUTION = 283\nPLANAR_CONFIGURATION = 284\nRESOLUTION_UNIT = 296\nSOFTWARE = 305\nDATE_TIME = 306\nARTIST = 315\nPREDICTOR = 317\nCOLORMAP = 320\nTILEOFFSETS = 324\nEXTRASAMPLES = 338\nSAMPLEFORMAT = 339\nJPEGTABLES = 347\nCOPYRIGHT = 33432\nIPTC_NAA_CHUNK = 33723  # newsphoto properties\nPHOTOSHOP_CHUNK = 34377  # photoshop properties\nICCPROFILE = 34675\nEXIFIFD = 34665\nXMP = 700\n\n# https://github.com/imagej/ImageJA/blob/master/src/main/java/ij/io/TiffDecoder.java\nIMAGEJ_META_DATA_BYTE_COUNTS = 50838\nIMAGEJ_META_DATA = 50839\n\nCOMPRESSION_INFO = {\n    # Compression => pil compression name\n    1: \"raw\",\n    2: \"tiff_ccitt\",\n    3: \"group3\",\n    4: \"group4\",\n    5: \"tiff_lzw\",\n    6: \"tiff_jpeg\",  # obsolete\n    7: \"jpeg\",\n    8: \"tiff_adobe_deflate\",\n    32771: \"tiff_raw_16\",  # 16-bit padding\n    32773: \"packbits\",\n    32809: \"tiff_thunderscan\",\n    32946: \"tiff_deflate\",\n    34676: \"tiff_sgilog\",\n    34677: \"tiff_sgilog24\",\n}\n\nCOMPRESSION_INFO_REV = {v: k for k, v in COMPRESSION_INFO.items()}\n\nOPEN_INFO = {\n    # (ByteOrder, PhotoInterpretation, SampleFormat, FillOrder, BitsPerSample,\n    #  ExtraSamples) => mode, rawmode\n    (II, 0, (1,), 1, (1,), ()): (\"1\", \"1;I\"),\n    (MM, 0, (1,), 1, (1,), ()): (\"1\", \"1;I\"),\n    (II, 0, (1,), 2, (1,), ()): (\"1\", \"1;IR\"),\n    (MM, 0, (1,), 2, (1,), ()): (\"1\", \"1;IR\"),\n    (II, 1, (1,), 1, (1,), ()): (\"1\", \"1\"),\n    (MM, 1, (1,), 1, (1,), ()): (\"1\", \"1\"),\n    (II, 1, (1,), 2, (1,), ()): (\"1\", \"1;R\"),\n    (MM, 1, (1,), 2, (1,), ()): (\"1\", \"1;R\"),\n\n    (II, 0, (1,), 1, (2,), ()): (\"L\", \"L;2I\"),\n    (MM, 0, (1,), 1, (2,), ()): (\"L\", \"L;2I\"),\n    (II, 0, (1,), 2, (2,), ()): (\"L\", \"L;2IR\"),\n    (MM, 0, (1,), 2, (2,), ()): (\"L\", \"L;2IR\"),\n    (II, 1, (1,), 1, (2,), ()): (\"L\", \"L;2\"),\n    (MM, 1, (1,), 1, (2,), ()): (\"L\", \"L;2\"),\n    (II, 1, (1,), 2, (2,), ()): (\"L\", \"L;2R\"),\n    (MM, 1, (1,), 2, (2,), ()): (\"L\", \"L;2R\"),\n\n    (II, 0, (1,), 1, (4,), ()): (\"L\", \"L;4I\"),\n    (MM, 0, (1,), 1, (4,), ()): (\"L\", \"L;4I\"),\n    (II, 0, (1,), 2, (4,), ()): (\"L\", \"L;4IR\"),\n    (MM, 0, (1,), 2, (4,), ()): (\"L\", \"L;4IR\"),\n    (II, 1, (1,), 1, (4,), ()): (\"L\", \"L;4\"),\n    (MM, 1, (1,), 1, (4,), ()): (\"L\", \"L;4\"),\n    (II, 1, (1,), 2, (4,), ()): (\"L\", \"L;4R\"),\n    (MM, 1, (1,), 2, (4,), ()): (\"L\", \"L;4R\"),\n\n    (II, 0, (1,), 1, (8,), ()): (\"L\", \"L;I\"),\n    (MM, 0, (1,), 1, (8,), ()): (\"L\", \"L;I\"),\n    (II, 0, (1,), 2, (8,), ()): (\"L\", \"L;IR\"),\n    (MM, 0, (1,), 2, (8,), ()): (\"L\", \"L;IR\"),\n    (II, 1, (1,), 1, (8,), ()): (\"L\", \"L\"),\n    (MM, 1, (1,), 1, (8,), ()): (\"L\", \"L\"),\n    (II, 1, (1,), 2, (8,), ()): (\"L\", \"L;R\"),\n    (MM, 1, (1,), 2, (8,), ()): (\"L\", \"L;R\"),\n\n    (II, 1, (1,), 1, (12,), ()): (\"I;16\", \"I;12\"),\n\n    (II, 1, (1,), 1, (16,), ()): (\"I;16\", \"I;16\"),\n    (MM, 1, (1,), 1, (16,), ()): (\"I;16B\", \"I;16B\"),\n    (II, 1, (2,), 1, (16,), ()): (\"I;16S\", \"I;16S\"),\n    (MM, 1, (2,), 1, (16,), ()): (\"I;16BS\", \"I;16BS\"),\n\n    (II, 0, (3,), 1, (32,), ()): (\"F\", \"F;32F\"),\n    (MM, 0, (3,), 1, (32,), ()): (\"F\", \"F;32BF\"),\n    (II, 1, (1,), 1, (32,), ()): (\"I\", \"I;32N\"),\n    (II, 1, (2,), 1, (32,), ()): (\"I\", \"I;32S\"),\n    (MM, 1, (2,), 1, (32,), ()): (\"I;32BS\", \"I;32BS\"),\n    (II, 1, (3,), 1, (32,), ()): (\"F\", \"F;32F\"),\n    (MM, 1, (3,), 1, (32,), ()): (\"F\", \"F;32BF\"),\n\n    (II, 1, (1,), 1, (8, 8), (2,)): (\"LA\", \"LA\"),\n    (MM, 1, (1,), 1, (8, 8), (2,)): (\"LA\", \"LA\"),\n\n    (II, 2, (1,), 1, (8, 8, 8), ()): (\"RGB\", \"RGB\"),\n    (MM, 2, (1,), 1, (8, 8, 8), ()): (\"RGB\", \"RGB\"),\n    (II, 2, (1,), 2, (8, 8, 8), ()): (\"RGB\", \"RGB;R\"),\n    (MM, 2, (1,), 2, (8, 8, 8), ()): (\"RGB\", \"RGB;R\"),\n    (II, 2, (1,), 1, (8, 8, 8, 8), ()): (\"RGBA\", \"RGBA\"),  # missing ExtraSamples\n    (MM, 2, (1,), 1, (8, 8, 8, 8), ()): (\"RGBA\", \"RGBA\"),  # missing ExtraSamples\n    (II, 2, (1,), 1, (8, 8, 8, 8), (0,)): (\"RGBX\", \"RGBX\"),\n    (MM, 2, (1,), 1, (8, 8, 8, 8), (0,)): (\"RGBX\", \"RGBX\"),\n    (II, 2, (1,), 1, (8, 8, 8, 8), (1,)): (\"RGBA\", \"RGBa\"),\n    (MM, 2, (1,), 1, (8, 8, 8, 8), (1,)): (\"RGBA\", \"RGBa\"),\n    (II, 2, (1,), 1, (8, 8, 8, 8), (2,)): (\"RGBA\", \"RGBA\"),\n    (MM, 2, (1,), 1, (8, 8, 8, 8), (2,)): (\"RGBA\", \"RGBA\"),\n    (II, 2, (1,), 1, (8, 8, 8, 8), (999,)): (\"RGBA\", \"RGBA\"),  # Corel Draw 10\n    (MM, 2, (1,), 1, (8, 8, 8, 8), (999,)): (\"RGBA\", \"RGBA\"),  # Corel Draw 10\n\n    (II, 3, (1,), 1, (1,), ()): (\"P\", \"P;1\"),\n    (MM, 3, (1,), 1, (1,), ()): (\"P\", \"P;1\"),\n    (II, 3, (1,), 2, (1,), ()): (\"P\", \"P;1R\"),\n    (MM, 3, (1,), 2, (1,), ()): (\"P\", \"P;1R\"),\n    (II, 3, (1,), 1, (2,), ()): (\"P\", \"P;2\"),\n    (MM, 3, (1,), 1, (2,), ()): (\"P\", \"P;2\"),\n    (II, 3, (1,), 2, (2,), ()): (\"P\", \"P;2R\"),\n    (MM, 3, (1,), 2, (2,), ()): (\"P\", \"P;2R\"),\n    (II, 3, (1,), 1, (4,), ()): (\"P\", \"P;4\"),\n    (MM, 3, (1,), 1, (4,), ()): (\"P\", \"P;4\"),\n    (II, 3, (1,), 2, (4,), ()): (\"P\", \"P;4R\"),\n    (MM, 3, (1,), 2, (4,), ()): (\"P\", \"P;4R\"),\n    (II, 3, (1,), 1, (8,), ()): (\"P\", \"P\"),\n    (MM, 3, (1,), 1, (8,), ()): (\"P\", \"P\"),\n    (II, 3, (1,), 1, (8, 8), (2,)): (\"PA\", \"PA\"),\n    (MM, 3, (1,), 1, (8, 8), (2,)): (\"PA\", \"PA\"),\n    (II, 3, (1,), 2, (8,), ()): (\"P\", \"P;R\"),\n    (MM, 3, (1,), 2, (8,), ()): (\"P\", \"P;R\"),\n\n    (II, 5, (1,), 1, (8, 8, 8, 8), ()): (\"CMYK\", \"CMYK\"),\n    (MM, 5, (1,), 1, (8, 8, 8, 8), ()): (\"CMYK\", \"CMYK\"),\n\n    (II, 6, (1,), 1, (8, 8, 8), ()): (\"YCbCr\", \"YCbCr\"),\n    (MM, 6, (1,), 1, (8, 8, 8), ()): (\"YCbCr\", \"YCbCr\"),\n\n    (II, 8, (1,), 1, (8, 8, 8), ()): (\"LAB\", \"LAB\"),\n    (MM, 8, (1,), 1, (8, 8, 8), ()): (\"LAB\", \"LAB\"),\n}\n\nPREFIXES = [b\"MM\\000\\052\", b\"II\\052\\000\", b\"II\\xBC\\000\"]\n\n\ndef _accept(prefix):\n    return prefix[:4] in PREFIXES\n\n\ndef _limit_rational(val, max_val):\n    inv = abs(val) > 1\n    n_d = IFDRational(1 / val if inv else val).limit_rational(max_val)\n    return n_d[::-1] if inv else n_d\n\n##\n# Wrapper for TIFF IFDs.\n\n_load_dispatch = {}\n_write_dispatch = {}\n\n\nclass IFDRational(Rational):\n    \"\"\" Implements a rational class where 0/0 is a legal value to match\n    the in the wild use of exif rationals.\n\n    e.g., DigitalZoomRatio - 0.00/0.00  indicates that no digital zoom was used\n    \"\"\"\n\n    \"\"\" If the denominator is 0, store this as a float('nan'), otherwise store\n    as a fractions.Fraction(). Delegate as appropriate\n\n    \"\"\"\n\n    __slots__ = ('_numerator', '_denominator', '_val')\n\n    def __init__(self, value, denominator=1):\n        \"\"\"\n        :param value: either an integer numerator, a\n        float/rational/other number, or an IFDRational\n        :param denominator: Optional integer denominator\n        \"\"\"\n        self._denominator = denominator\n        self._numerator = value\n        self._val = float(1)\n\n        if isinstance(value, Fraction):\n            self._numerator = value.numerator\n            self._denominator = value.denominator\n            self._val = value\n\n        if isinstance(value, IFDRational):\n            self._denominator = value.denominator\n            self._numerator = value.numerator\n            self._val = value._val\n            return\n\n        if denominator == 0:\n            self._val = float('nan')\n            return\n\n        elif denominator == 1:\n            self._val = Fraction(value)\n        else:\n            self._val = Fraction(value, denominator)\n\n    @property\n    def numerator(a):\n        return a._numerator\n\n    @property\n    def denominator(a):\n        return a._denominator\n\n    def limit_rational(self, max_denominator):\n        \"\"\"\n\n        :param max_denominator: Integer, the maximum denominator value\n        :returns: Tuple of (numerator, denominator)\n        \"\"\"\n\n        if self.denominator == 0:\n            return (self.numerator, self.denominator)\n\n        f = self._val.limit_denominator(max_denominator)\n        return (f.numerator, f.denominator)\n\n    def __repr__(self):\n        return str(float(self._val))\n\n    def __hash__(self):\n        return self._val.__hash__()\n\n    def __eq__(self, other):\n        return self._val == other\n\n    def _delegate(op):\n        def delegate(self, *args):\n            return getattr(self._val, op)(*args)\n        return delegate\n\n    \"\"\" a = ['add','radd', 'sub', 'rsub','div', 'rdiv', 'mul', 'rmul',\n             'truediv', 'rtruediv', 'floordiv',\n             'rfloordiv','mod','rmod', 'pow','rpow', 'pos', 'neg',\n             'abs', 'trunc', 'lt', 'gt', 'le', 'ge', 'nonzero',\n             'ceil', 'floor', 'round']\n        print(\"\\n\".join(\"__%s__ = _delegate('__%s__')\" % (s,s) for s in a))\n        \"\"\"\n\n    __add__ = _delegate('__add__')\n    __radd__ = _delegate('__radd__')\n    __sub__ = _delegate('__sub__')\n    __rsub__ = _delegate('__rsub__')\n    __div__ = _delegate('__div__')\n    __rdiv__ = _delegate('__rdiv__')\n    __mul__ = _delegate('__mul__')\n    __rmul__ = _delegate('__rmul__')\n    __truediv__ = _delegate('__truediv__')\n    __rtruediv__ = _delegate('__rtruediv__')\n    __floordiv__ = _delegate('__floordiv__')\n    __rfloordiv__ = _delegate('__rfloordiv__')\n    __mod__ = _delegate('__mod__')\n    __rmod__ = _delegate('__rmod__')\n    __pow__ = _delegate('__pow__')\n    __rpow__ = _delegate('__rpow__')\n    __pos__ = _delegate('__pos__')\n    __neg__ = _delegate('__neg__')\n    __abs__ = _delegate('__abs__')\n    __trunc__ = _delegate('__trunc__')\n    __lt__ = _delegate('__lt__')\n    __gt__ = _delegate('__gt__')\n    __le__ = _delegate('__le__')\n    __ge__ = _delegate('__ge__')\n    __nonzero__ = _delegate('__nonzero__')\n    __ceil__ = _delegate('__ceil__')\n    __floor__ = _delegate('__floor__')\n    __round__ = _delegate('__round__')\n\n\nclass ImageFileDirectory_v2(collections.MutableMapping):\n    \"\"\"This class represents a TIFF tag directory.  To speed things up, we\n    don't decode tags unless they're asked for.\n\n    Exposes a dictionary interface of the tags in the directory::\n\n        ifd = ImageFileDirectory_v2()\n        ifd[key] = 'Some Data'\n        ifd.tagtype[key] = 2\n        print(ifd[key])\n        'Some Data'\n\n    Individual values are returned as the strings or numbers, sequences are\n    returned as tuples of the values.\n\n    The tiff metadata type of each item is stored in a dictionary of\n    tag types in\n    `~PIL.TiffImagePlugin.ImageFileDirectory_v2.tagtype`. The types\n    are read from a tiff file, guessed from the type added, or added\n    manually.\n\n    Data Structures:\n\n        * self.tagtype = {}\n\n          * Key: numerical tiff tag number\n          * Value: integer corresponding to the data type from `~PIL.TiffTags.TYPES`\n\n    .. versionadded:: 3.0.0\n    \"\"\"\n    \"\"\"\n    Documentation:\n\n        'internal' data structures:\n        * self._tags_v2 = {} Key: numerical tiff tag number\n                             Value: decoded data, as tuple for multiple values\n        * self._tagdata = {} Key: numerical tiff tag number\n                             Value: undecoded byte string from file\n        * self._tags_v1 = {} Key: numerical tiff tag number\n                             Value: decoded data in the v1 format\n\n    Tags will be found in the private attributes self._tagdata, and in\n    self._tags_v2 once decoded.\n\n    Self.legacy_api is a value for internal use, and shouldn't be\n    changed from outside code. In cooperation with the\n    ImageFileDirectory_v1 class, if legacy_api is true, then decoded\n    tags will be populated into both _tags_v1 and _tags_v2. _Tags_v2\n    will be used if this IFD is used in the TIFF save routine. Tags\n    should be read from tags_v1 if legacy_api == true.\n\n    \"\"\"\n\n    def __init__(self, ifh=b\"II\\052\\0\\0\\0\\0\\0\", prefix=None):\n        \"\"\"Initialize an ImageFileDirectory.\n\n        To construct an ImageFileDirectory from a real file, pass the 8-byte\n        magic header to the constructor.  To only set the endianness, pass it\n        as the 'prefix' keyword argument.\n\n        :param ifh: One of the accepted magic headers (cf. PREFIXES); also sets\n              endianness.\n        :param prefix: Override the endianness of the file.\n        \"\"\"\n        if ifh[:4] not in PREFIXES:\n            raise SyntaxError(\"not a TIFF file (header %r not valid)\" % ifh)\n        self._prefix = prefix if prefix is not None else ifh[:2]\n        if self._prefix == MM:\n            self._endian = \">\"\n        elif self._prefix == II:\n            self._endian = \"<\"\n        else:\n            raise SyntaxError(\"not a TIFF IFD\")\n        self.reset()\n        self.next, = self._unpack(\"L\", ifh[4:])\n        self._legacy_api = False\n\n    prefix = property(lambda self: self._prefix)\n    offset = property(lambda self: self._offset)\n    legacy_api = property(lambda self: self._legacy_api)\n\n    @legacy_api.setter\n    def legacy_api(self, value):\n        raise Exception(\"Not allowing setting of legacy api\")\n\n    def reset(self):\n        self._tags_v1 = {}  # will remain empty if legacy_api is false\n        self._tags_v2 = {}  # main tag storage\n        self._tagdata = {}\n        self.tagtype = {}   # added 2008-06-05 by Florian Hoech\n        self._next = None\n        self._offset = None\n\n    def __str__(self):\n        return str(dict(self))\n\n    def as_dict(self):\n        \"\"\"Return a dictionary of the image's tags.\n\n        .. deprecated:: 3.0.0\n        \"\"\"\n        warnings.warn(\"as_dict() is deprecated. \" +\n                      \"Please use dict(ifd) instead.\", DeprecationWarning)\n        return dict(self)\n\n    def named(self):\n        \"\"\"\n        :returns: dict of name|key: value\n\n        Returns the complete tag dictionary, with named tags where possible.\n        \"\"\"\n        return dict((TiffTags.lookup(code).name, value)\n                    for code, value in self.items())\n\n    def __len__(self):\n        return len(set(self._tagdata) | set(self._tags_v2))\n\n    def __getitem__(self, tag):\n        if tag not in self._tags_v2:  # unpack on the fly\n            data = self._tagdata[tag]\n            typ = self.tagtype[tag]\n            size, handler = self._load_dispatch[typ]\n            self[tag] = handler(self, data, self.legacy_api)  # check type\n        val = self._tags_v2[tag]\n        if self.legacy_api and not isinstance(val, (tuple, bytes)):\n            val = val,\n        return val\n\n    def __contains__(self, tag):\n        return tag in self._tags_v2 or tag in self._tagdata\n\n    if bytes is str:\n        def has_key(self, tag):\n            return tag in self\n\n    def __setitem__(self, tag, value):\n        self._setitem(tag, value, self.legacy_api)\n\n    def _setitem(self, tag, value, legacy_api):\n        basetypes = (Number, bytes, str)\n        if bytes is str:\n            basetypes += unicode,\n\n        info = TiffTags.lookup(tag)\n        values = [value] if isinstance(value, basetypes) else value\n\n        if tag not in self.tagtype:\n            if info.type:\n                self.tagtype[tag] = info.type\n            else:\n                self.tagtype[tag] = 7\n                if all(isinstance(v, IFDRational) for v in values):\n                    self.tagtype[tag] = 5\n                elif all(isinstance(v, int) for v in values):\n                    if all(v < 2 ** 16 for v in values):\n                        self.tagtype[tag] = 3\n                    else:\n                        self.tagtype[tag] = 4\n                elif all(isinstance(v, float) for v in values):\n                    self.tagtype[tag] = 12\n                else:\n                    if bytes is str:\n                        # Never treat data as binary by default on Python 2.\n                        self.tagtype[tag] = 2\n                    else:\n                        if all(isinstance(v, str) for v in values):\n                            self.tagtype[tag] = 2\n\n        if self.tagtype[tag] == 7 and bytes is not str:\n            values = [value.encode(\"ascii\", 'replace') if isinstance(value, str) else value]\n\n        values = tuple(info.cvt_enum(value) for value in values)\n\n        dest = self._tags_v1 if legacy_api else self._tags_v2\n\n        if info.length == 1:\n            if legacy_api and self.tagtype[tag] in [5, 10]:\n                values = values,\n            dest[tag], = values\n        else:\n            dest[tag] = values\n\n    def __delitem__(self, tag):\n        self._tags_v2.pop(tag, None)\n        self._tags_v1.pop(tag, None)\n        self._tagdata.pop(tag, None)\n\n    def __iter__(self):\n        return iter(set(self._tagdata) | set(self._tags_v2))\n\n    def _unpack(self, fmt, data):\n        return struct.unpack(self._endian + fmt, data)\n\n    def _pack(self, fmt, *values):\n        return struct.pack(self._endian + fmt, *values)\n\n    def _register_loader(idx, size):\n        def decorator(func):\n            from .TiffTags import TYPES\n            if func.__name__.startswith(\"load_\"):\n                TYPES[idx] = func.__name__[5:].replace(\"_\", \" \")\n            _load_dispatch[idx] = size, func\n            return func\n        return decorator\n\n    def _register_writer(idx):\n        def decorator(func):\n            _write_dispatch[idx] = func\n            return func\n        return decorator\n\n    def _register_basic(idx_fmt_name):\n        from .TiffTags import TYPES\n        idx, fmt, name = idx_fmt_name\n        TYPES[idx] = name\n        size = struct.calcsize(\"=\" + fmt)\n        _load_dispatch[idx] = size, lambda self, data, legacy_api=True: (\n            self._unpack(\"{}{}\".format(len(data) // size, fmt), data))\n        _write_dispatch[idx] = lambda self, *values: (\n            b\"\".join(self._pack(fmt, value) for value in values))\n\n    list(map(_register_basic,\n             [(3, \"H\", \"short\"), (4, \"L\", \"long\"),\n              (6, \"b\", \"signed byte\"), (8, \"h\", \"signed short\"),\n              (9, \"l\", \"signed long\"), (11, \"f\", \"float\"), (12, \"d\", \"double\")]))\n\n    @_register_loader(1, 1)  # Basic type, except for the legacy API.\n    def load_byte(self, data, legacy_api=True):\n        return data\n\n    @_register_writer(1)  # Basic type, except for the legacy API.\n    def write_byte(self, data):\n        return data\n\n    @_register_loader(2, 1)\n    def load_string(self, data, legacy_api=True):\n        if data.endswith(b\"\\0\"):\n            data = data[:-1]\n        return data.decode(\"latin-1\", \"replace\")\n\n    @_register_writer(2)\n    def write_string(self, value):\n        # remerge of https://github.com/python-pillow/Pillow/pull/1416\n        if sys.version_info[0] == 2:\n            value = value.decode('ascii', 'replace')\n        return b\"\" + value.encode('ascii', 'replace') + b\"\\0\"\n\n    @_register_loader(5, 8)\n    def load_rational(self, data, legacy_api=True):\n        vals = self._unpack(\"{}L\".format(len(data) // 4), data)\n        combine = lambda a, b: (a, b) if legacy_api else IFDRational(a, b)\n        return tuple(combine(num, denom)\n                     for num, denom in zip(vals[::2], vals[1::2]))\n\n    @_register_writer(5)\n    def write_rational(self, *values):\n        return b\"\".join(self._pack(\"2L\", *_limit_rational(frac, 2 ** 31))\n                        for frac in values)\n\n    @_register_loader(7, 1)\n    def load_undefined(self, data, legacy_api=True):\n        return data\n\n    @_register_writer(7)\n    def write_undefined(self, value):\n        return value\n\n    @_register_loader(10, 8)\n    def load_signed_rational(self, data, legacy_api=True):\n        vals = self._unpack(\"{}l\".format(len(data) // 4), data)\n        combine = lambda a, b: (a, b) if legacy_api else IFDRational(a, b)\n        return tuple(combine(num, denom)\n                     for num, denom in zip(vals[::2], vals[1::2]))\n\n    @_register_writer(10)\n    def write_signed_rational(self, *values):\n        return b\"\".join(self._pack(\"2L\", *_limit_rational(frac, 2 ** 30))\n                        for frac in values)\n\n    def _ensure_read(self, fp, size):\n        ret = fp.read(size)\n        if len(ret) != size:\n            raise IOError(\"Corrupt EXIF data.  \" +\n                          \"Expecting to read %d bytes but only got %d. \" %\n                          (size, len(ret)))\n        return ret\n\n    def load(self, fp):\n\n        self.reset()\n        self._offset = fp.tell()\n\n        try:\n            for i in range(self._unpack(\"H\", self._ensure_read(fp, 2))[0]):\n                tag, typ, count, data = self._unpack(\"HHL4s\", self._ensure_read(fp, 12))\n                if DEBUG:\n                    tagname = TiffTags.lookup(tag).name\n                    typname = TYPES.get(typ, \"unknown\")\n                    print(\"tag: %s (%d) - type: %s (%d)\" %\n                          (tagname, tag, typname, typ), end=\" \")\n\n                try:\n                    unit_size, handler = self._load_dispatch[typ]\n                except KeyError:\n                    if DEBUG:\n                        print(\"- unsupported type\", typ)\n                    continue  # ignore unsupported type\n                size = count * unit_size\n                if size > 4:\n                    here = fp.tell()\n                    offset, = self._unpack(\"L\", data)\n                    if DEBUG:\n                        print(\"Tag Location: %s - Data Location: %s\" %\n                              (here, offset), end=\" \")\n                    fp.seek(offset)\n                    data = ImageFile._safe_read(fp, size)\n                    fp.seek(here)\n                else:\n                    data = data[:size]\n\n                if len(data) != size:\n                    warnings.warn(\"Possibly corrupt EXIF data.  \"\n                                  \"Expecting to read %d bytes but only got %d. \"\n                                  \"Skipping tag %s\" % (size, len(data), tag))\n                    continue\n\n                if not data:\n                    continue\n\n                self._tagdata[tag] = data\n                self.tagtype[tag] = typ\n\n                if DEBUG:\n                    if size > 32:\n                        print(\"- value: <table: %d bytes>\" % size)\n                    else:\n                        print(\"- value:\", self[tag])\n\n            self.next, = self._unpack(\"L\", self._ensure_read(fp, 4))\n        except IOError as msg:\n            warnings.warn(str(msg))\n            return\n\n    def save(self, fp):\n\n        if fp.tell() == 0:  # skip TIFF header on subsequent pages\n            # tiff header -- PIL always starts the first IFD at offset 8\n            fp.write(self._prefix + self._pack(\"HL\", 42, 8))\n\n        # FIXME What about tagdata?\n        fp.write(self._pack(\"H\", len(self._tags_v2)))\n\n        entries = []\n        offset = fp.tell() + len(self._tags_v2) * 12 + 4\n        stripoffsets = None\n\n        # pass 1: convert tags to binary format\n        # always write tags in ascending order\n        for tag, value in sorted(self._tags_v2.items()):\n            if tag == STRIPOFFSETS:\n                stripoffsets = len(entries)\n            typ = self.tagtype.get(tag)\n            if DEBUG:\n                print(\"Tag %s, Type: %s, Value: %s\" % (tag, typ, value))\n            values = value if isinstance(value, tuple) else (value,)\n            data = self._write_dispatch[typ](self, *values)\n            if DEBUG:\n                tagname = TiffTags.lookup(tag).name\n                typname = TYPES.get(typ, \"unknown\")\n                print(\"save: %s (%d) - type: %s (%d)\" %\n                      (tagname, tag, typname, typ), end=\" \")\n                if len(data) >= 16:\n                    print(\"- value: <table: %d bytes>\" % len(data))\n                else:\n                    print(\"- value:\", values)\n\n            # count is sum of lengths for string and arbitrary data\n            count = len(data) if typ in [2, 7] else len(values)\n            # figure out if data fits into the entry\n            if len(data) <= 4:\n                entries.append((tag, typ, count, data.ljust(4, b\"\\0\"), b\"\"))\n            else:\n                entries.append((tag, typ, count, self._pack(\"L\", offset), data))\n                offset += (len(data) + 1) // 2 * 2  # pad to word\n\n        # update strip offset data to point beyond auxiliary data\n        if stripoffsets is not None:\n            tag, typ, count, value, data = entries[stripoffsets]\n            if data:\n                raise NotImplementedError(\n                    \"multistrip support not yet implemented\")\n            value = self._pack(\"L\", self._unpack(\"L\", value)[0] + offset)\n            entries[stripoffsets] = tag, typ, count, value, data\n\n        # pass 2: write entries to file\n        for tag, typ, count, value, data in entries:\n            if DEBUG > 1:\n                print(tag, typ, count, repr(value), repr(data))\n            fp.write(self._pack(\"HHL4s\", tag, typ, count, value))\n\n        # -- overwrite here for multi-page --\n        fp.write(b\"\\0\\0\\0\\0\")  # end of entries\n\n        # pass 3: write auxiliary data to file\n        for tag, typ, count, value, data in entries:\n            fp.write(data)\n            if len(data) & 1:\n                fp.write(b\"\\0\")\n\n        return offset\n\nImageFileDirectory_v2._load_dispatch = _load_dispatch\nImageFileDirectory_v2._write_dispatch = _write_dispatch\nfor idx, name in TYPES.items():\n    name = name.replace(\" \", \"_\")\n    setattr(ImageFileDirectory_v2, \"load_\" + name, _load_dispatch[idx][1])\n    setattr(ImageFileDirectory_v2, \"write_\" + name, _write_dispatch[idx])\ndel _load_dispatch, _write_dispatch, idx, name\n\n\n# Legacy ImageFileDirectory support.\nclass ImageFileDirectory_v1(ImageFileDirectory_v2):\n    \"\"\"This class represents the **legacy** interface to a TIFF tag directory.\n\n    Exposes a dictionary interface of the tags in the directory::\n\n        ifd = ImageFileDirectory_v1()\n        ifd[key] = 'Some Data'\n        ifd.tagtype[key] = 2\n        print(ifd[key])\n        ('Some Data',)\n\n    Also contains a dictionary of tag types as read from the tiff image file,\n    `~PIL.TiffImagePlugin.ImageFileDirectory_v1.tagtype`.\n\n    Values are returned as a tuple.\n\n    ..  deprecated:: 3.0.0\n    \"\"\"\n    def __init__(self, *args, **kwargs):\n        ImageFileDirectory_v2.__init__(self, *args, **kwargs)\n        self._legacy_api = True\n\n    tags = property(lambda self: self._tags_v1)\n    tagdata = property(lambda self: self._tagdata)\n\n    @classmethod\n    def from_v2(cls, original):\n        \"\"\" Returns an\n        :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`\n        instance with the same data as is contained in the original\n        :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`\n        instance.\n\n        :returns: :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`\n\n        \"\"\"\n\n        ifd = cls(prefix=original.prefix)\n        ifd._tagdata = original._tagdata\n        ifd.tagtype = original.tagtype\n        ifd.next = original.next  # an indicator for multipage tiffs\n        return ifd\n\n    def to_v2(self):\n        \"\"\" Returns an\n        :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`\n        instance with the same data as is contained in the original\n        :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`\n        instance.\n\n        :returns: :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`\n\n        \"\"\"\n\n        ifd = ImageFileDirectory_v2(prefix=self.prefix)\n        ifd._tagdata = dict(self._tagdata)\n        ifd.tagtype = dict(self.tagtype)\n        ifd._tags_v2 = dict(self._tags_v2)\n        return ifd\n\n    def __contains__(self, tag):\n        return tag in self._tags_v1 or tag in self._tagdata\n\n    def __len__(self):\n        return len(set(self._tagdata) | set(self._tags_v1))\n\n    def __iter__(self):\n        return iter(set(self._tagdata) | set(self._tags_v1))\n\n    def __setitem__(self, tag, value):\n        for legacy_api in (False, True):\n            self._setitem(tag, value, legacy_api)\n\n    def __getitem__(self, tag):\n        if tag not in self._tags_v1:  # unpack on the fly\n            data = self._tagdata[tag]\n            typ = self.tagtype[tag]\n            size, handler = self._load_dispatch[typ]\n            for legacy in (False, True):\n                self._setitem(tag, handler(self, data, legacy), legacy)\n        val = self._tags_v1[tag]\n        if not isinstance(val, (tuple, bytes)):\n            val = val,\n        return val\n\n\n# undone -- switch this pointer when IFD_LEGACY_API == False\nImageFileDirectory = ImageFileDirectory_v1\n\n\n##\n# Image plugin for TIFF files.\n\nclass TiffImageFile(ImageFile.ImageFile):\n\n    format = \"TIFF\"\n    format_description = \"Adobe TIFF\"\n\n    def _open(self):\n        \"Open the first image in a TIFF file\"\n\n        # Header\n        ifh = self.fp.read(8)\n\n        # image file directory (tag dictionary)\n        self.tag_v2 = ImageFileDirectory_v2(ifh)\n\n        # legacy tag/ifd entries will be filled in later\n        self.tag = self.ifd = None\n\n        # setup frame pointers\n        self.__first = self.__next = self.tag_v2.next\n        self.__frame = -1\n        self.__fp = self.fp\n        self._frame_pos = []\n        self._n_frames = None\n        self._is_animated = None\n\n        if DEBUG:\n            print(\"*** TiffImageFile._open ***\")\n            print(\"- __first:\", self.__first)\n            print(\"- ifh: \", ifh)\n\n        # and load the first frame\n        self._seek(0)\n\n    @property\n    def n_frames(self):\n        if self._n_frames is None:\n            current = self.tell()\n            try:\n                while True:\n                    self._seek(self.tell() + 1)\n            except EOFError:\n                self._n_frames = self.tell() + 1\n            self.seek(current)\n        return self._n_frames\n\n    @property\n    def is_animated(self):\n        if self._is_animated is None:\n            current = self.tell()\n\n            try:\n                self.seek(1)\n                self._is_animated = True\n            except EOFError:\n                self._is_animated = False\n\n            self.seek(current)\n        return self._is_animated\n\n    def seek(self, frame):\n        \"Select a given frame as current image\"\n        self._seek(max(frame, 0))  # Questionable backwards compatibility.\n        # Create a new core image object on second and\n        # subsequent frames in the image. Image may be\n        # different size/mode.\n        Image._decompression_bomb_check(self.size)\n        self.im = Image.core.new(self.mode, self.size)\n\n    def _seek(self, frame):\n        self.fp = self.__fp\n        while len(self._frame_pos) <= frame:\n            if not self.__next:\n                raise EOFError(\"no more images in TIFF file\")\n            if DEBUG:\n                print(\"Seeking to frame %s, on frame %s, \"\n                      \"__next %s, location: %s\" %\n                      (frame, self.__frame, self.__next, self.fp.tell()))\n            # reset python3 buffered io handle in case fp\n            # was passed to libtiff, invalidating the buffer\n            self.fp.tell()\n            self.fp.seek(self.__next)\n            self._frame_pos.append(self.__next)\n            if DEBUG:\n                print(\"Loading tags, location: %s\" % self.fp.tell())\n            self.tag_v2.load(self.fp)\n            self.__next = self.tag_v2.next\n            self.__frame += 1\n        self.fp.seek(self._frame_pos[frame])\n        self.tag_v2.load(self.fp)\n        # fill the legacy tag/ifd entries\n        self.tag = self.ifd = ImageFileDirectory_v1.from_v2(self.tag_v2)\n        self.__frame = frame\n        self._setup()\n\n    def tell(self):\n        \"Return the current frame number\"\n        return self.__frame\n\n    def _decoder(self, rawmode, layer, tile=None):\n        \"Setup decoder contexts\"\n\n        args = None\n        if rawmode == \"RGB\" and self._planar_configuration == 2:\n            rawmode = rawmode[layer]\n        compression = self._compression\n        if compression == \"raw\":\n            args = (rawmode, 0, 1)\n        elif compression == \"jpeg\":\n            args = rawmode, \"\"\n            if JPEGTABLES in self.tag_v2:\n                # Hack to handle abbreviated JPEG headers\n                # FIXME This will fail with more than one value\n                self.tile_prefix, = self.tag_v2[JPEGTABLES]\n        elif compression == \"packbits\":\n            args = rawmode\n        elif compression == \"tiff_lzw\":\n            args = rawmode\n            if PREDICTOR in self.tag_v2:\n                # Section 14: Differencing Predictor\n                self.decoderconfig = (self.tag_v2[PREDICTOR],)\n\n        return args\n\n    def load(self):\n        if self.use_load_libtiff:\n            return self._load_libtiff()\n        return super(TiffImageFile, self).load()\n\n    def _load_libtiff(self):\n        \"\"\" Overload method triggered when we detect a compressed tiff\n            Calls out to libtiff \"\"\"\n\n        pixel = Image.Image.load(self)\n\n        if self.tile is None:\n            raise IOError(\"cannot load this image\")\n        if not self.tile:\n            return pixel\n\n        self.load_prepare()\n\n        if not len(self.tile) == 1:\n            raise IOError(\"Not exactly one tile\")\n\n        # (self._compression, (extents tuple),\n        #   0, (rawmode, self._compression, fp))\n        extents = self.tile[0][1]\n        args = list(self.tile[0][3]) + [self.tag_v2.offset]\n\n        # To be nice on memory footprint, if there's a\n        # file descriptor, use that instead of reading\n        # into a string in python.\n        # libtiff closes the file descriptor, so pass in a dup.\n        try:\n            fp = hasattr(self.fp, \"fileno\") and os.dup(self.fp.fileno())\n            # flush the file descriptor, prevents error on pypy 2.4+\n            # should also eliminate the need for fp.tell for py3\n            # in _seek\n            if hasattr(self.fp, \"flush\"):\n                self.fp.flush()\n        except IOError:\n            # io.BytesIO have a fileno, but returns an IOError if\n            # it doesn't use a file descriptor.\n            fp = False\n\n        if fp:\n            args[2] = fp\n\n        decoder = Image._getdecoder(self.mode, 'libtiff', tuple(args),\n                                    self.decoderconfig)\n        try:\n            decoder.setimage(self.im, extents)\n        except ValueError:\n            raise IOError(\"Couldn't set the image\")\n\n        if hasattr(self.fp, \"getvalue\"):\n            # We've got a stringio like thing passed in. Yay for all in memory.\n            # The decoder needs the entire file in one shot, so there's not\n            # a lot we can do here other than give it the entire file.\n            # unless we could do something like get the address of the\n            # underlying string for stringio.\n            #\n            # Rearranging for supporting byteio items, since they have a fileno\n            # that returns an IOError if there's no underlying fp. Easier to\n            # deal with here by reordering.\n            if DEBUG:\n                print(\"have getvalue. just sending in a string from getvalue\")\n            n, err = decoder.decode(self.fp.getvalue())\n        elif hasattr(self.fp, \"fileno\"):\n            # we've got a actual file on disk, pass in the fp.\n            if DEBUG:\n                print(\"have fileno, calling fileno version of the decoder.\")\n            self.fp.seek(0)\n            # 4 bytes, otherwise the trace might error out\n            n, err = decoder.decode(b\"fpfp\")\n        else:\n            # we have something else.\n            if DEBUG:\n                print(\"don't have fileno or getvalue. just reading\")\n            # UNDONE -- so much for that buffer size thing.\n            n, err = decoder.decode(self.fp.read())\n\n        self.tile = []\n        self.readonly = 0\n        # libtiff closed the fp in a, we need to close self.fp, if possible\n        if hasattr(self.fp, 'close'):\n            if not self.__next:\n                self.fp.close()\n        self.fp = None  # might be shared\n\n        if err < 0:\n            raise IOError(err)\n\n        self.load_end()\n\n        return Image.Image.load(self)\n\n    def _setup(self):\n        \"Setup this image object based on current tags\"\n\n        if 0xBC01 in self.tag_v2:\n            raise IOError(\"Windows Media Photo files not yet supported\")\n\n        # extract relevant tags\n        self._compression = COMPRESSION_INFO[self.tag_v2.get(COMPRESSION, 1)]\n        self._planar_configuration = self.tag_v2.get(PLANAR_CONFIGURATION, 1)\n\n        # photometric is a required tag, but not everyone is reading\n        # the specification\n        photo = self.tag_v2.get(PHOTOMETRIC_INTERPRETATION, 0)\n\n        fillorder = self.tag_v2.get(FILLORDER, 1)\n\n        if DEBUG:\n            print(\"*** Summary ***\")\n            print(\"- compression:\", self._compression)\n            print(\"- photometric_interpretation:\", photo)\n            print(\"- planar_configuration:\", self._planar_configuration)\n            print(\"- fill_order:\", fillorder)\n\n        # size\n        xsize = self.tag_v2.get(IMAGEWIDTH)\n        ysize = self.tag_v2.get(IMAGELENGTH)\n        self.size = xsize, ysize\n\n        if DEBUG:\n            print(\"- size:\", self.size)\n\n        sampleFormat = self.tag_v2.get(SAMPLEFORMAT, (1,))\n        if (len(sampleFormat) > 1\n            and max(sampleFormat) == min(sampleFormat) == 1):\n            # SAMPLEFORMAT is properly per band, so an RGB image will\n            # be (1,1,1).  But, we don't support per band pixel types,\n            # and anything more than one band is a uint8. So, just\n            # take the first element. Revisit this if adding support\n            # for more exotic images.\n            sampleFormat = (1,)\n\n        # mode: check photometric interpretation and bits per pixel\n        key = (\n            self.tag_v2.prefix, photo, sampleFormat, fillorder,\n            self.tag_v2.get(BITSPERSAMPLE, (1,)),\n            self.tag_v2.get(EXTRASAMPLES, ())\n            )\n        if DEBUG:\n            print(\"format key:\", key)\n        try:\n            self.mode, rawmode = OPEN_INFO[key]\n        except KeyError:\n            if DEBUG:\n                print(\"- unsupported format\")\n            raise SyntaxError(\"unknown pixel mode\")\n\n        if DEBUG:\n            print(\"- raw mode:\", rawmode)\n            print(\"- pil mode:\", self.mode)\n\n        self.info[\"compression\"] = self._compression\n\n        xres = self.tag_v2.get(X_RESOLUTION, 1)\n        yres = self.tag_v2.get(Y_RESOLUTION, 1)\n\n        if xres and yres:\n            resunit = self.tag_v2.get(RESOLUTION_UNIT, 1)\n            if resunit == 2:  # dots per inch\n                self.info[\"dpi\"] = xres, yres\n            elif resunit == 3:  # dots per centimeter. convert to dpi\n                self.info[\"dpi\"] = xres * 2.54, yres * 2.54\n            else:  # No absolute unit of measurement\n                self.info[\"resolution\"] = xres, yres\n\n        # build tile descriptors\n        x = y = l = 0\n        self.tile = []\n        self.use_load_libtiff = False\n        if STRIPOFFSETS in self.tag_v2:\n            # striped image\n            offsets = self.tag_v2[STRIPOFFSETS]\n            h = self.tag_v2.get(ROWSPERSTRIP, ysize)\n            w = self.size[0]\n            if READ_LIBTIFF or self._compression in [\"tiff_ccitt\", \"group3\",\n                                                     \"group4\", \"tiff_jpeg\",\n                                                     \"tiff_adobe_deflate\",\n                                                     \"tiff_thunderscan\",\n                                                     \"tiff_deflate\",\n                                                     \"tiff_sgilog\",\n                                                     \"tiff_sgilog24\",\n                                                     \"tiff_raw_16\"]:\n                # if DEBUG:\n                #     print(\"Activating g4 compression for whole file\")\n\n                # Decoder expects entire file as one tile.\n                # There's a buffer size limit in load (64k)\n                # so large g4 images will fail if we use that\n                # function.\n                #\n                # Setup the one tile for the whole image, then\n                # use the _load_libtiff function.\n\n                self.use_load_libtiff = True\n\n                # libtiff handles the fillmode for us, so 1;IR should\n                # actually be 1;I. Including the R double reverses the\n                # bits, so stripes of the image are reversed.  See\n                # https://github.com/python-pillow/Pillow/issues/279\n                if fillorder == 2:\n                    key = (\n                        self.tag_v2.prefix, photo, sampleFormat, 1,\n                        self.tag_v2.get(BITSPERSAMPLE, (1,)),\n                        self.tag_v2.get(EXTRASAMPLES, ())\n                        )\n                    if DEBUG:\n                        print(\"format key:\", key)\n                    # this should always work, since all the\n                    # fillorder==2 modes have a corresponding\n                    # fillorder=1 mode\n                    self.mode, rawmode = OPEN_INFO[key]\n                # libtiff always returns the bytes in native order.\n                # we're expecting image byte order. So, if the rawmode\n                # contains I;16, we need to convert from native to image\n                # byte order.\n                if self.mode in ('I;16B', 'I;16') and 'I;16' in rawmode:\n                    rawmode = 'I;16N'\n\n                # Offset in the tile tuple is 0, we go from 0,0 to\n                # w,h, and we only do this once -- eds\n                a = (rawmode, self._compression, False)\n                self.tile.append(\n                    (self._compression,\n                     (0, 0, w, ysize),\n                     0, a))\n                a = None\n\n            else:\n                for i, offset in enumerate(offsets):\n                    a = self._decoder(rawmode, l, i)\n                    self.tile.append(\n                        (self._compression,\n                            (0, min(y, ysize), w, min(y+h, ysize)),\n                            offset, a))\n                    if DEBUG:\n                        print(\"tiles: \", self.tile)\n                    y = y + h\n                    if y >= self.size[1]:\n                        x = y = 0\n                        l += 1\n                    a = None\n        elif TILEOFFSETS in self.tag_v2:\n            # tiled image\n            w = self.tag_v2.get(322)\n            h = self.tag_v2.get(323)\n            a = None\n            for o in self.tag_v2[TILEOFFSETS]:\n                if not a:\n                    a = self._decoder(rawmode, l)\n                # FIXME: this doesn't work if the image size\n                # is not a multiple of the tile size...\n                self.tile.append(\n                    (self._compression,\n                        (x, y, x+w, y+h),\n                        o, a))\n                x = x + w\n                if x >= self.size[0]:\n                    x, y = 0, y + h\n                    if y >= self.size[1]:\n                        x = y = 0\n                        l += 1\n                        a = None\n        else:\n            if DEBUG:\n                print(\"- unsupported data organization\")\n            raise SyntaxError(\"unknown data organization\")\n\n        # Fix up info.\n        if ICCPROFILE in self.tag_v2:\n            self.info['icc_profile'] = self.tag_v2[ICCPROFILE]\n\n        # fixup palette descriptor\n\n        if self.mode == \"P\":\n            palette = [o8(b // 256) for b in self.tag_v2[COLORMAP]]\n            self.palette = ImagePalette.raw(\"RGB;L\", b\"\".join(palette))\n#\n# --------------------------------------------------------------------\n# Write TIFF files\n\n# little endian is default except for image modes with\n# explicit big endian byte-order\n\nSAVE_INFO = {\n    # mode => rawmode, byteorder, photometrics,\n    #           sampleformat, bitspersample, extra\n    \"1\": (\"1\", II, 1, 1, (1,), None),\n    \"L\": (\"L\", II, 1, 1, (8,), None),\n    \"LA\": (\"LA\", II, 1, 1, (8, 8), 2),\n    \"P\": (\"P\", II, 3, 1, (8,), None),\n    \"PA\": (\"PA\", II, 3, 1, (8, 8), 2),\n    \"I\": (\"I;32S\", II, 1, 2, (32,), None),\n    \"I;16\": (\"I;16\", II, 1, 1, (16,), None),\n    \"I;16S\": (\"I;16S\", II, 1, 2, (16,), None),\n    \"F\": (\"F;32F\", II, 1, 3, (32,), None),\n    \"RGB\": (\"RGB\", II, 2, 1, (8, 8, 8), None),\n    \"RGBX\": (\"RGBX\", II, 2, 1, (8, 8, 8, 8), 0),\n    \"RGBA\": (\"RGBA\", II, 2, 1, (8, 8, 8, 8), 2),\n    \"CMYK\": (\"CMYK\", II, 5, 1, (8, 8, 8, 8), None),\n    \"YCbCr\": (\"YCbCr\", II, 6, 1, (8, 8, 8), None),\n    \"LAB\": (\"LAB\", II, 8, 1, (8, 8, 8), None),\n\n    \"I;32BS\": (\"I;32BS\", MM, 1, 2, (32,), None),\n    \"I;16B\": (\"I;16B\", MM, 1, 1, (16,), None),\n    \"I;16BS\": (\"I;16BS\", MM, 1, 2, (16,), None),\n    \"F;32BF\": (\"F;32BF\", MM, 1, 3, (32,), None),\n}\n\n\ndef _save(im, fp, filename):\n\n    try:\n        rawmode, prefix, photo, format, bits, extra = SAVE_INFO[im.mode]\n    except KeyError:\n        raise IOError(\"cannot write mode %s as TIFF\" % im.mode)\n\n    ifd = ImageFileDirectory_v2(prefix=prefix)\n\n    compression = im.encoderinfo.get('compression',\n                                     im.info.get('compression', 'raw'))\n\n    libtiff = WRITE_LIBTIFF or compression != 'raw'\n\n    # required for color libtiff images\n    ifd[PLANAR_CONFIGURATION] = getattr(im, '_planar_configuration', 1)\n\n    ifd[IMAGEWIDTH] = im.size[0]\n    ifd[IMAGELENGTH] = im.size[1]\n\n    # write any arbitrary tags passed in as an ImageFileDirectory\n    info = im.encoderinfo.get(\"tiffinfo\", {})\n    if DEBUG:\n        print(\"Tiffinfo Keys: %s\" % list(info))\n    if isinstance(info, ImageFileDirectory_v1):\n        info = info.to_v2()\n    for key in info:\n        ifd[key] = info.get(key)\n        try:\n            ifd.tagtype[key] = info.tagtype[key]\n        except:\n            pass  # might not be an IFD, Might not have populated type\n\n    # additions written by Greg Couch, gregc@cgl.ucsf.edu\n    # inspired by image-sig posting from Kevin Cazabon, kcazabon@home.com\n    if hasattr(im, 'tag_v2'):\n        # preserve tags from original TIFF image file\n        for key in (RESOLUTION_UNIT, X_RESOLUTION, Y_RESOLUTION,\n                    IPTC_NAA_CHUNK, PHOTOSHOP_CHUNK, XMP):\n            if key in im.tag_v2:\n                ifd[key] = im.tag_v2[key]\n                ifd.tagtype[key] = im.tag_v2.tagtype[key]\n\n    # preserve ICC profile (should also work when saving other formats\n    # which support profiles as TIFF) -- 2008-06-06 Florian Hoech\n    if \"icc_profile\" in im.info:\n        ifd[ICCPROFILE] = im.info[\"icc_profile\"]\n\n    for key, name in [(IMAGEDESCRIPTION, \"description\"),\n                      (X_RESOLUTION, \"resolution\"),\n                      (Y_RESOLUTION, \"resolution\"),\n                      (X_RESOLUTION, \"x_resolution\"),\n                      (Y_RESOLUTION, \"y_resolution\"),\n                      (RESOLUTION_UNIT, \"resolution_unit\"),\n                      (SOFTWARE, \"software\"),\n                      (DATE_TIME, \"date_time\"),\n                      (ARTIST, \"artist\"),\n                      (COPYRIGHT, \"copyright\")]:\n        name_with_spaces = name.replace(\"_\", \" \")\n        if \"_\" in name and name_with_spaces in im.encoderinfo:\n            warnings.warn(\"%r is deprecated; use %r instead\" %\n                          (name_with_spaces, name), DeprecationWarning)\n            ifd[key] = im.encoderinfo[name.replace(\"_\", \" \")]\n        if name in im.encoderinfo:\n            ifd[key] = im.encoderinfo[name]\n\n    dpi = im.encoderinfo.get(\"dpi\")\n    if dpi:\n        ifd[RESOLUTION_UNIT] = 2\n        ifd[X_RESOLUTION] = dpi[0]\n        ifd[Y_RESOLUTION] = dpi[1]\n\n    if bits != (1,):\n        ifd[BITSPERSAMPLE] = bits\n        if len(bits) != 1:\n            ifd[SAMPLESPERPIXEL] = len(bits)\n    if extra is not None:\n        ifd[EXTRASAMPLES] = extra\n    if format != 1:\n        ifd[SAMPLEFORMAT] = format\n\n    ifd[PHOTOMETRIC_INTERPRETATION] = photo\n\n    if im.mode == \"P\":\n        lut = im.im.getpalette(\"RGB\", \"RGB;L\")\n        ifd[COLORMAP] = tuple(i8(v) * 256 for v in lut)\n    # data orientation\n    stride = len(bits) * ((im.size[0]*bits[0]+7)//8)\n    ifd[ROWSPERSTRIP] = im.size[1]\n    ifd[STRIPBYTECOUNTS] = stride * im.size[1]\n    ifd[STRIPOFFSETS] = 0  # this is adjusted by IFD writer\n    # no compression by default:\n    ifd[COMPRESSION] = COMPRESSION_INFO_REV.get(compression, 1)\n\n    if libtiff:\n        if DEBUG:\n            print(\"Saving using libtiff encoder\")\n            print(\"Items: %s\" % sorted(ifd.items()))\n        _fp = 0\n        if hasattr(fp, \"fileno\"):\n            try:\n                fp.seek(0)\n                _fp = os.dup(fp.fileno())\n            except io.UnsupportedOperation:\n                pass\n\n        # STRIPOFFSETS and STRIPBYTECOUNTS are added by the library\n        # based on the data in the strip.\n        blocklist = [STRIPOFFSETS, STRIPBYTECOUNTS]\n        atts = {}\n        # bits per sample is a single short in the tiff directory, not a list.\n        atts[BITSPERSAMPLE] = bits[0]\n        # Merge the ones that we have with (optional) more bits from\n        # the original file, e.g x,y resolution so that we can\n        # save(load('')) == original file.\n        legacy_ifd = {}\n        if hasattr(im, 'tag'):\n            legacy_ifd = im.tag.to_v2()\n        for tag, value in itertools.chain(ifd.items(),\n                                          getattr(im, 'tag_v2', {}).items(),\n                                          legacy_ifd.items()):\n            # Libtiff can only process certain core items without adding\n            # them to the custom dictionary. It will segfault if it attempts\n            # to add a custom tag without the dictionary entry\n            #\n            # UNDONE --  add code for the custom dictionary\n            if tag not in TiffTags.LIBTIFF_CORE:\n                continue\n            if tag not in atts and tag not in blocklist:\n                if isinstance(value, unicode if bytes is str else str):\n                    atts[tag] = value.encode('ascii', 'replace') + b\"\\0\"\n                elif isinstance(value, IFDRational):\n                    atts[tag] = float(value)\n                else:\n                    atts[tag] = value\n\n        if DEBUG:\n            print(\"Converted items: %s\" % sorted(atts.items()))\n\n        # libtiff always expects the bytes in native order.\n        # we're storing image byte order. So, if the rawmode\n        # contains I;16, we need to convert from native to image\n        # byte order.\n        if im.mode in ('I;16B', 'I;16'):\n            rawmode = 'I;16N'\n\n        a = (rawmode, compression, _fp, filename, atts)\n        # print(im.mode, compression, a, im.encoderconfig)\n        e = Image._getencoder(im.mode, 'libtiff', a, im.encoderconfig)\n        e.setimage(im.im, (0, 0)+im.size)\n        while True:\n            # undone, change to self.decodermaxblock:\n            l, s, d = e.encode(16*1024)\n            if not _fp:\n                fp.write(d)\n            if s:\n                break\n        if s < 0:\n            raise IOError(\"encoder error %d when writing image file\" % s)\n\n    else:\n        offset = ifd.save(fp)\n\n        ImageFile._save(im, fp, [\n            (\"raw\", (0, 0)+im.size, offset, (rawmode, stride, 1))\n            ])\n\n    # -- helper for multi-page save --\n    if \"_debug_multipage\" in im.encoderinfo:\n        # just to access o32 and o16 (using correct byte order)\n        im._debug_multipage = ifd\n\nclass AppendingTiffWriter:\n    fieldSizes = [\n        0,  # None\n        1,  # byte\n        1,  # ascii\n        2,  # short\n        4,  # long\n        8,  # rational\n        1,  # sbyte\n        1,  # undefined\n        2,  # sshort\n        4,  # slong\n        8,  # srational\n        4,  # float\n        8,  # double\n    ]\n\n    #    StripOffsets = 273\n    #    FreeOffsets = 288\n    #    TileOffsets = 324\n    #    JPEGQTables = 519\n    #    JPEGDCTables = 520\n    #    JPEGACTables = 521\n    Tags = {273, 288, 324, 519, 520, 521}\n\n    def __init__(self, fn, new=False):\n        if hasattr(fn, 'read'):\n            self.f = fn\n            self.close_fp = False\n        else:\n            self.name = fn\n            self.close_fp = True\n            try:\n                self.f = io.open(fn, \"w+b\" if new else \"r+b\")\n            except IOError:\n                self.f = io.open(fn, \"w+b\")\n        self.beginning = self.f.tell()\n        self.setup()\n\n    def setup(self):\n        # Reset everything.\n        self.f.seek(self.beginning, os.SEEK_SET)\n\n        self.whereToWriteNewIFDOffset = None\n        self.offsetOfNewPage = 0\n\n        self.IIMM = IIMM = self.f.read(4)\n        if not IIMM:\n            # empty file - first page\n            self.isFirst = True\n            return\n\n        self.isFirst = False\n        if IIMM == b\"II\\x2a\\x00\":\n            self.setEndian(\"<\")\n        elif IIMM == b\"MM\\x00\\x2a\":\n            self.setEndian(\">\")\n        else:\n            raise RuntimeError(\"Invalid TIFF file header\")\n\n        self.skipIFDs()\n        self.goToEnd()\n\n    def finalize(self):\n        if self.isFirst:\n            return\n\n        # fix offsets\n        self.f.seek(self.offsetOfNewPage)\n\n        IIMM = self.f.read(4)\n        if not IIMM:\n            # raise RuntimeError(\"nothing written into new page\")\n            # Make it easy to finish a frame without committing to a new one.\n            return\n\n        if IIMM != self.IIMM:\n            raise RuntimeError(\"IIMM of new page doesn't match IIMM of \"\n                               \"first page\")\n\n        IFDoffset = self.readLong()\n        IFDoffset += self.offsetOfNewPage\n        self.f.seek(self.whereToWriteNewIFDOffset)\n        self.writeLong(IFDoffset)\n        self.f.seek(IFDoffset)\n        self.fixIFD()\n\n    def newFrame(self):\n        # Call this to finish a frame.\n        self.finalize()\n        self.setup()\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, exc_type, exc_value, traceback):\n        if self.close_fp:\n            self.close()\n        return False\n\n    def tell(self):\n        return self.f.tell() - self.offsetOfNewPage\n\n    def seek(self, offset, whence):\n        if whence == os.SEEK_SET:\n            offset += self.offsetOfNewPage\n\n        self.f.seek(offset, whence)\n        return self.tell()\n\n    def goToEnd(self):\n        self.f.seek(0, os.SEEK_END)\n        pos = self.f.tell()\n\n        # pad to 16 byte boundary\n        padBytes = 16 - pos % 16\n        if 0 < padBytes < 16:\n            self.f.write(bytes(bytearray(padBytes)))\n        self.offsetOfNewPage = self.f.tell()\n\n    def setEndian(self, endian):\n        self.endian = endian\n        self.longFmt = self.endian + \"L\"\n        self.shortFmt = self.endian + \"H\"\n        self.tagFormat = self.endian + \"HHL\"\n\n    def skipIFDs(self):\n        while True:\n            IFDoffset = self.readLong()\n            if IFDoffset == 0:\n                self.whereToWriteNewIFDOffset = self.f.tell() - 4\n                break\n\n            self.f.seek(IFDoffset)\n            numTags = self.readShort()\n            self.f.seek(numTags * 12, os.SEEK_CUR)\n\n    def write(self, data):\n        return self.f.write(data)\n\n    def readShort(self):\n        value, = struct.unpack(self.shortFmt, self.f.read(2))\n        return value\n\n    def readLong(self):\n        value, = struct.unpack(self.longFmt, self.f.read(4))\n        return value\n\n    def rewriteLastShortToLong(self, value):\n        self.f.seek(-2, os.SEEK_CUR)\n        bytesWritten = self.f.write(struct.pack(self.longFmt, value))\n        if bytesWritten is not None and bytesWritten != 4:\n            raise RuntimeError(\"wrote only %u bytes but wanted 4\" %\n                               bytesWritten)\n\n    def rewriteLastShort(self, value):\n        self.f.seek(-2, os.SEEK_CUR)\n        bytesWritten = self.f.write(struct.pack(self.shortFmt, value))\n        if bytesWritten is not None and bytesWritten != 2:\n            raise RuntimeError(\"wrote only %u bytes but wanted 2\" %\n                               bytesWritten)\n\n    def rewriteLastLong(self, value):\n        self.f.seek(-4, os.SEEK_CUR)\n        bytesWritten = self.f.write(struct.pack(self.longFmt, value))\n        if bytesWritten is not None and bytesWritten != 4:\n            raise RuntimeError(\"wrote only %u bytes but wanted 4\" %\n                               bytesWritten)\n\n    def writeShort(self, value):\n        bytesWritten = self.f.write(struct.pack(self.shortFmt, value))\n        if bytesWritten is not None and bytesWritten != 2:\n            raise RuntimeError(\"wrote only %u bytes but wanted 2\" %\n                               bytesWritten)\n\n    def writeLong(self, value):\n        bytesWritten = self.f.write(struct.pack(self.longFmt, value))\n        if bytesWritten is not None and bytesWritten != 4:\n            raise RuntimeError(\"wrote only %u bytes but wanted 4\" %\n                               bytesWritten)\n\n    def close(self):\n        self.finalize()\n        self.f.close()\n\n    def fixIFD(self):\n        numTags = self.readShort()\n        #trace(\"fixing IFD at %X; number of tags: %u (0x%X)\", self.f.tell()-2,\n        #      numTags, numTags)\n\n        for i in range(numTags):\n            tag, fieldType, count = struct.unpack(self.tagFormat, self.f.read(8))\n            #trace(\"  at %X: tag %u (0x%X), type %u, count %u\", self.f.tell()-8,\n            #      tag, tag, fieldType, count)\n\n            fieldSize = self.fieldSizes[fieldType]\n            totalSize = fieldSize * count\n            isLocal = (totalSize <= 4)\n            if not isLocal:\n                offset = self.readLong()\n                offset += self.offsetOfNewPage\n                self.rewriteLastLong(offset)\n\n            if tag in self.Tags:\n                curPos = self.f.tell()\n\n                if isLocal:\n                    self.fixOffsets(count, isShort=(fieldSize == 2),\n                                    isLong=(fieldSize == 4))\n                    self.f.seek(curPos + 4)\n                else:\n                    self.f.seek(offset)\n                    self.fixOffsets(count, isShort=(fieldSize == 2),\n                                    isLong=(fieldSize == 4))\n                    self.f.seek(curPos)\n\n                offset = curPos = None\n\n            elif isLocal:\n                # skip the locally stored value that is not an offset\n                self.f.seek(4, os.SEEK_CUR)\n\n    def fixOffsets(self, count, isShort=False, isLong=False):\n        if not isShort and not isLong:\n            raise RuntimeError(\"offset is neither short nor long\")\n\n        for i in range(count):\n            offset = self.readShort() if isShort else self.readLong()\n            offset += self.offsetOfNewPage\n            if isShort and offset >= 65536:\n                # offset is now too large - we must convert shorts to longs\n                if count != 1:\n                    raise RuntimeError(\"not implemented\")  # XXX TODO\n\n                # simple case - the offset is just one and therefore it is\n                # local (not referenced with another offset)\n                self.rewriteLastShortToLong(offset)\n                self.f.seek(-10, os.SEEK_CUR)\n                self.writeShort(4)  # rewrite the type to LONG\n                self.f.seek(8, os.SEEK_CUR)\n            elif isShort:\n                self.rewriteLastShort(offset)\n            else:\n                self.rewriteLastLong(offset)\n\ndef _save_all(im, fp, filename):\n    if not hasattr(im, \"n_frames\"):\n        return _save(im, fp, filename)\n\n    cur_idx = im.tell()\n    try:\n        with AppendingTiffWriter(fp) as tf:\n            for idx in range(im.n_frames):\n                im.seek(idx)\n                im.load()\n                _save(im, tf, filename)\n                tf.newFrame()\n    finally:\n        im.seek(cur_idx)\n\n#\n# --------------------------------------------------------------------\n# Register\n\nImage.register_open(TiffImageFile.format, TiffImageFile, _accept)\nImage.register_save(TiffImageFile.format, _save)\nImage.register_save_all(TiffImageFile.format, _save_all)\n\nImage.register_extension(TiffImageFile.format, \".tif\")\nImage.register_extension(TiffImageFile.format, \".tiff\")\n\nImage.register_mime(TiffImageFile.format, \"image/tiff\")\n"}
A user will ask you to solve a task. You should first draft your thinking process (inner monologue). Then, generate the solution.

Your response format must follow the template below:
<think>
Your thoughts or/and draft, like working through an exercise on scratch paper. Be as casual and as long as you want until you are confident to generate a correct solution.
</think>
<solution>
Final solution presented to the user.
</solution>
system
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** Missing 'dpi' Information When ResolutionUnit is Absent in TIFF Files

**Description:**
When opening a TIFF image that does not include the `ResolutionUnit` tag, the `dpi` information is not added to the image's metadata. Attempting to access `im.info['dpi']` results in a `KeyError`, which can cause downstream processes to fail when they expect DPI information to be present.

**Example Code:**
```python
from PIL import Image

# Open a TIFF image without the ResolutionUnit tag
im = Image.open("path/to/tiff_without_resolution_unit.tif")

# Attempting to access 'dpi' raises KeyError
print(im.info['dpi'])  # KeyError: 'dpi'
```

**Expected Behavior:**
When the `ResolutionUnit` tag is missing from a TIFF file, the library should default the `dpi` to the values of `x_resolution` and `y_resolution`, interpreting the resolution in inches. This ensures that `im.info['dpi']` is always available, even if the `ResolutionUnit` is not specified.

**Actual Behavior:**
Accessing `im.info['dpi']` raises a `KeyError` because the `dpi` key is not set when the `ResolutionUnit` tag is missing from the TIFF file. This prevents users from reliably accessing DPI information, potentially causing crashes or unexpected behavior in applications that depend on this metadata.
[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### PIL/TiffImagePlugin.py
#
# The Python Imaging Library.
# $Id$
#
# TIFF file handling
#
# TIFF is a flexible, if somewhat aged, image file format originally
# defined by Aldus.  Although TIFF supports a wide variety of pixel
# layouts and compression methods, the name doesn't really stand for
# "thousands of incompatible file formats," it just feels that way.
#
# To read TIFF data from a stream, the stream must be seekable.  For
# progressive decoding, make sure to use TIFF files where the tag
# directory is placed first in the file.
#
# History:
# 1995-09-01 fl   Created
# 1996-05-04 fl   Handle JPEGTABLES tag
# 1996-05-18 fl   Fixed COLORMAP support
# 1997-01-05 fl   Fixed PREDICTOR support
# 1997-08-27 fl   Added support for rational tags (from Perry Stoll)
# 1998-01-10 fl   Fixed seek/tell (from Jan Blom)
# 1998-07-15 fl   Use private names for internal variables
# 1999-06-13 fl   Rewritten for PIL 1.0 (1.0)
# 2000-10-11 fl   Additional fixes for Python 2.0 (1.1)
# 2001-04-17 fl   Fixed rewind support (seek to frame 0) (1.2)
# 2001-05-12 fl   Added write support for more tags (from Greg Couch) (1.3)
# 2001-12-18 fl   Added workaround for broken Matrox library
# 2002-01-18 fl   Don't mess up if photometric tag is missing (D. Alan Stewart)
# 2003-05-19 fl   Check FILLORDER tag
# 2003-09-26 fl   Added RGBa support
# 2004-02-24 fl   Added DPI support; fixed rational write support
# 2005-02-07 fl   Added workaround for broken Corel Draw 10 files
# 2006-01-09 fl   Added support for float/double tags (from Russell Nelson)
#
# Copyright (c) 1997-2006 by Secret Labs AB.  All rights reserved.
# Copyright (c) 1995-1997 by Fredrik Lundh
#
# See the README file for information on usage and redistribution.
#

from __future__ import division, print_function

from . import Image, ImageFile, ImagePalette, TiffTags
from ._binary import i8, o8

import collections
from fractions import Fraction
from numbers import Number, Rational

import io
import itertools
import os
import struct
import sys
import warnings

from .TiffTags import TYPES


__version__ = "1.3.5"
DEBUG = False  # Needs to be merged with the new logging approach.

# Set these to true to force use of libtiff for reading or writing.
READ_LIBTIFF = False
WRITE_LIBTIFF = False
IFD_LEGACY_API = True

II = b"II"  # little-endian (Intel style)
MM = b"MM"  # big-endian (Motorola style)

#
# --------------------------------------------------------------------
# Read TIFF files

# a few tag names, just to make the code below a bit more readable
IMAGEWIDTH = 256
IMAGELENGTH = 257
BITSPERSAMPLE = 258
COMPRESSION = 259
PHOTOMETRIC_INTERPRETATION = 262
FILLORDER = 266
IMAGEDESCRIPTION = 270
STRIPOFFSETS = 273
SAMPLESPERPIXEL = 277
ROWSPERSTRIP = 278
STRIPBYTECOUNTS = 279
X_RESOLUTION = 282
Y_RESOLUTION = 283
PLANAR_CONFIGURATION = 284
RESOLUTION_UNIT = 296
SOFTWARE = 305
DATE_TIME = 306
ARTIST = 315
PREDICTOR = 317
COLORMAP = 320
TILEOFFSETS = 324
EXTRASAMPLES = 338
SAMPLEFORMAT = 339
JPEGTABLES = 347
COPYRIGHT = 33432
IPTC_NAA_CHUNK = 33723  # newsphoto properties
PHOTOSHOP_CHUNK = 34377  # photoshop properties
ICCPROFILE = 34675
EXIFIFD = 34665
XMP = 700

# https://github.com/imagej/ImageJA/blob/master/src/main/java/ij/io/TiffDecoder.java
IMAGEJ_META_DATA_BYTE_COUNTS = 50838
IMAGEJ_META_DATA = 50839

COMPRESSION_INFO = {
    # Compression => pil compression name
    1: "raw",
    2: "tiff_ccitt",
    3: "group3",
    4: "group4",
    5: "tiff_lzw",
    6: "tiff_jpeg",  # obsolete
    7: "jpeg",
    8: "tiff_adobe_deflate",
    32771: "tiff_raw_16",  # 16-bit padding
    32773: "packbits",
    32809: "tiff_thunderscan",
    32946: "tiff_deflate",
    34676: "tiff_sgilog",
    34677: "tiff_sgilog24",
}

COMPRESSION_INFO_REV = {v: k for k, v in COMPRESSION_INFO.items()}

OPEN_INFO = {
    # (ByteOrder, PhotoInterpretation, SampleFormat, FillOrder, BitsPerSample,
    #  ExtraSamples) => mode, rawmode
    (II, 0, (1,), 1, (1,), ()): ("1", "1;I"),
    (MM, 0, (1,), 1, (1,), ()): ("1", "1;I"),
    (II, 0, (1,), 2, (1,), ()): ("1", "1;IR"),
    (MM, 0, (1,), 2, (1,), ()): ("1", "1;IR"),
    (II, 1, (1,), 1, (1,), ()): ("1", "1"),
    (MM, 1, (1,), 1, (1,), ()): ("1", "1"),
    (II, 1, (1,), 2, (1,), ()): ("1", "1;R"),
    (MM, 1, (1,), 2, (1,), ()): ("1", "1;R"),

    (II, 0, (1,), 1, (2,), ()): ("L", "L;2I"),
    (MM, 0, (1,), 1, (2,), ()): ("L", "L;2I"),
    (II, 0, (1,), 2, (2,), ()): ("L", "L;2IR"),
    (MM, 0, (1,), 2, (2,), ()): ("L", "L;2IR"),
    (II, 1, (1,), 1, (2,), ()): ("L", "L;2"),
    (MM, 1, (1,), 1, (2,), ()): ("L", "L;2"),
    (II, 1, (1,), 2, (2,), ()): ("L", "L;2R"),
    (MM, 1, (1,), 2, (2,), ()): ("L", "L;2R"),

    (II, 0, (1,), 1, (4,), ()): ("L", "L;4I"),
    (MM, 0, (1,), 1, (4,), ()): ("L", "L;4I"),
    (II, 0, (1,), 2, (4,), ()): ("L", "L;4IR"),
    (MM, 0, (1,), 2, (4,), ()): ("L", "L;4IR"),
    (II, 1, (1,), 1, (4,), ()): ("L", "L;4"),
    (MM, 1, (1,), 1, (4,), ()): ("L", "L;4"),
    (II, 1, (1,), 2, (4,), ()): ("L", "L;4R"),
    (MM, 1, (1,), 2, (4,), ()): ("L", "L;4R"),

    (II, 0, (1,), 1, (8,), ()): ("L", "L;I"),
    (MM, 0, (1,), 1, (8,), ()): ("L", "L;I"),
    (II, 0, (1,), 2, (8,), ()): ("L", "L;IR"),
    (MM, 0, (1,), 2, (8,), ()): ("L", "L;IR"),
    (II, 1, (1,), 1, (8,), ()): ("L", "L"),
    (MM, 1, (1,), 1, (8,), ()): ("L", "L"),
    (II, 1, (1,), 2, (8,), ()): ("L", "L;R"),
    (MM, 1, (1,), 2, (8,), ()): ("L", "L;R"),

    (II, 1, (1,), 1, (12,), ()): ("I;16", "I;12"),

    (II, 1, (1,), 1, (16,), ()): ("I;16", "I;16"),
    (MM, 1, (1,), 1, (16,), ()): ("I;16B", "I;16B"),
    (II, 1, (2,), 1, (16,), ()): ("I;16S", "I;16S"),
    (MM, 1, (2,), 1, (16,), ()): ("I;16BS", "I;16BS"),

    (II, 0, (3,), 1, (32,), ()): ("F", "F;32F"),
    (MM, 0, (3,), 1, (32,), ()): ("F", "F;32BF"),
    (II, 1, (1,), 1, (32,), ()): ("I", "I;32N"),
    (II, 1, (2,), 1, (32,), ()): ("I", "I;32S"),
    (MM, 1, (2,), 1, (32,), ()): ("I;32BS", "I;32BS"),
    (II, 1, (3,), 1, (32,), ()): ("F", "F;32F"),
    (MM, 1, (3,), 1, (32,), ()): ("F", "F;32BF"),

    (II, 1, (1,), 1, (8, 8), (2,)): ("LA", "LA"),
    (MM, 1, (1,), 1, (8, 8), (2,)): ("LA", "LA"),

    (II, 2, (1,), 1, (8, 8, 8), ()): ("RGB", "RGB"),
    (MM, 2, (1,), 1, (8, 8, 8), ()): ("RGB", "RGB"),
    (II, 2, (1,), 2, (8, 8, 8), ()): ("RGB", "RGB;R"),
    (MM, 2, (1,), 2, (8, 8, 8), ()): ("RGB", "RGB;R"),
    (II, 2, (1,), 1, (8, 8, 8, 8), ()): ("RGBA", "RGBA"),  # missing ExtraSamples
    (MM, 2, (1,), 1, (8, 8, 8, 8), ()): ("RGBA", "RGBA"),  # missing ExtraSamples
    (II, 2, (1,), 1, (8, 8, 8, 8), (0,)): ("RGBX", "RGBX"),
    (MM, 2, (1,), 1, (8, 8, 8, 8), (0,)): ("RGBX", "RGBX"),
    (II, 2, (1,), 1, (8, 8, 8, 8), (1,)): ("RGBA", "RGBa"),
    (MM, 2, (1,), 1, (8, 8, 8, 8), (1,)): ("RGBA", "RGBa"),
    (II, 2, (1,), 1, (8, 8, 8, 8), (2,)): ("RGBA", "RGBA"),
    (MM, 2, (1,), 1, (8, 8, 8, 8), (2,)): ("RGBA", "RGBA"),
    (II, 2, (1,), 1, (8, 8, 8, 8), (999,)): ("RGBA", "RGBA"),  # Corel Draw 10
    (MM, 2, (1,), 1, (8, 8, 8, 8), (999,)): ("RGBA", "RGBA"),  # Corel Draw 10

    (II, 3, (1,), 1, (1,), ()): ("P", "P;1"),
    (MM, 3, (1,), 1, (1,), ()): ("P", "P;1"),
    (II, 3, (1,), 2, (1,), ()): ("P", "P;1R"),
    (MM, 3, (1,), 2, (1,), ()): ("P", "P;1R"),
    (II, 3, (1,), 1, (2,), ()): ("P", "P;2"),
    (MM, 3, (1,), 1, (2,), ()): ("P", "P;2"),
    (II, 3, (1,), 2, (2,), ()): ("P", "P;2R"),
    (MM, 3, (1,), 2, (2,), ()): ("P", "P;2R"),
    (II, 3, (1,), 1, (4,), ()): ("P", "P;4"),
    (MM, 3, (1,), 1, (4,), ()): ("P", "P;4"),
    (II, 3, (1,), 2, (4,), ()): ("P", "P;4R"),
    (MM, 3, (1,), 2, (4,), ()): ("P", "P;4R"),
    (II, 3, (1,), 1, (8,), ()): ("P", "P"),
    (MM, 3, (1,), 1, (8,), ()): ("P", "P"),
    (II, 3, (1,), 1, (8, 8), (2,)): ("PA", "PA"),
    (MM, 3, (1,), 1, (8, 8), (2,)): ("PA", "PA"),
    (II, 3, (1,), 2, (8,), ()): ("P", "P;R"),
    (MM, 3, (1,), 2, (8,), ()): ("P", "P;R"),

    (II, 5, (1,), 1, (8, 8, 8, 8), ()): ("CMYK", "CMYK"),
    (MM, 5, (1,), 1, (8, 8, 8, 8), ()): ("CMYK", "CMYK"),

    (II, 6, (1,), 1, (8, 8, 8), ()): ("YCbCr", "YCbCr"),
    (MM, 6, (1,), 1, (8, 8, 8), ()): ("YCbCr", "YCbCr"),

    (II, 8, (1,), 1, (8, 8, 8), ()): ("LAB", "LAB"),
    (MM, 8, (1,), 1, (8, 8, 8), ()): ("LAB", "LAB"),
}

PREFIXES = [b"MM\000\052", b"II\052\000", b"II\xBC\000"]


def _accept(prefix):
    return prefix[:4] in PREFIXES


def _limit_rational(val, max_val):
    inv = abs(val) > 1
    n_d = IFDRational(1 / val if inv else val).limit_rational(max_val)
    return n_d[::-1] if inv else n_d

##
# Wrapper for TIFF IFDs.

_load_dispatch = {}
_write_dispatch = {}


class IFDRational(Rational):
    """ Implements a rational class where 0/0 is a legal value to match
    the in the wild use of exif rationals.

    e.g., DigitalZoomRatio - 0.00/0.00  indicates that no digital zoom was used
    """

    """ If the denominator is 0, store this as a float('nan'), otherwise store
    as a fractions.Fraction(). Delegate as appropriate

    """

    __slots__ = ('_numerator', '_denominator', '_val')

    def __init__(self, value, denominator=1):
        """
        :param value: either an integer numerator, a
        float/rational/other number, or an IFDRational
        :param denominator: Optional integer denominator
        """
        self._denominator = denominator
        self._numerator = value
        self._val = float(1)

        if isinstance(value, Fraction):
            self._numerator = value.numerator
            self._denominator = value.denominator
            self._val = value

        if isinstance(value, IFDRational):
            self._denominator = value.denominator
            self._numerator = value.numerator
            self._val = value._val
            return

        if denominator == 0:
            self._val = float('nan')
            return

        elif denominator == 1:
            self._val = Fraction(value)
        else:
            self._val = Fraction(value, denominator)

    @property
    def numerator(a):
        return a._numerator

    @property
    def denominator(a):
        return a._denominator

    def limit_rational(self, max_denominator):
        """

        :param max_denominator: Integer, the maximum denominator value
        :returns: Tuple of (numerator, denominator)
        """

        if self.denominator == 0:
            return (self.numerator, self.denominator)

        f = self._val.limit_denominator(max_denominator)
        return (f.numerator, f.denominator)

    def __repr__(self):
        return str(float(self._val))

    def __hash__(self):
        return self._val.__hash__()

    def __eq__(self, other):
        return self._val == other

    def _delegate(op):
        def delegate(self, *args):
            return getattr(self._val, op)(*args)
        return delegate

    """ a = ['add','radd', 'sub', 'rsub','div', 'rdiv', 'mul', 'rmul',
             'truediv', 'rtruediv', 'floordiv',
             'rfloordiv','mod','rmod', 'pow','rpow', 'pos', 'neg',
             'abs', 'trunc', 'lt', 'gt', 'le', 'ge', 'nonzero',
             'ceil', 'floor', 'round']
        print("\n".join("__%s__ = _delegate('__%s__')" % (s,s) for s in a))
        """

    __add__ = _delegate('__add__')
    __radd__ = _delegate('__radd__')
    __sub__ = _delegate('__sub__')
    __rsub__ = _delegate('__rsub__')
    __div__ = _delegate('__div__')
    __rdiv__ = _delegate('__rdiv__')
    __mul__ = _delegate('__mul__')
    __rmul__ = _delegate('__rmul__')
    __truediv__ = _delegate('__truediv__')
    __rtruediv__ = _delegate('__rtruediv__')
    __floordiv__ = _delegate('__floordiv__')
    __rfloordiv__ = _delegate('__rfloordiv__')
    __mod__ = _delegate('__mod__')
    __rmod__ = _delegate('__rmod__')
    __pow__ = _delegate('__pow__')
    __rpow__ = _delegate('__rpow__')
    __pos__ = _delegate('__pos__')
    __neg__ = _delegate('__neg__')
    __abs__ = _delegate('__abs__')
    __trunc__ = _delegate('__trunc__')
    __lt__ = _delegate('__lt__')
    __gt__ = _delegate('__gt__')
    __le__ = _delegate('__le__')
    __ge__ = _delegate('__ge__')
    __nonzero__ = _delegate('__nonzero__')
    __ceil__ = _delegate('__ceil__')
    __floor__ = _delegate('__floor__')
    __round__ = _delegate('__round__')


class ImageFileDirectory_v2(collections.MutableMapping):
    """This class represents a TIFF tag directory.  To speed things up, we
    don't decode tags unless they're asked for.

    Exposes a dictionary interface of the tags in the directory::

        ifd = ImageFileDirectory_v2()
        ifd[key] = 'Some Data'
        ifd.tagtype[key] = 2
        print(ifd[key])
        'Some Data'

    Individual values are returned as the strings or numbers, sequences are
    returned as tuples of the values.

    The tiff metadata type of each item is stored in a dictionary of
    tag types in
    `~PIL.TiffImagePlugin.ImageFileDirectory_v2.tagtype`. The types
    are read from a tiff file, guessed from the type added, or added
    manually.

    Data Structures:

        * self.tagtype = {}

          * Key: numerical tiff tag number
          * Value: integer corresponding to the data type from `~PIL.TiffTags.TYPES`

    .. versionadded:: 3.0.0
    """
    """
    Documentation:

        'internal' data structures:
        * self._tags_v2 = {} Key: numerical tiff tag number
                             Value: decoded data, as tuple for multiple values
        * self._tagdata = {} Key: numerical tiff tag number
                             Value: undecoded byte string from file
        * self._tags_v1 = {} Key: numerical tiff tag number
                             Value: decoded data in the v1 format

    Tags will be found in the private attributes self._tagdata, and in
    self._tags_v2 once decoded.

    Self.legacy_api is a value for internal use, and shouldn't be
    changed from outside code. In cooperation with the
    ImageFileDirectory_v1 class, if legacy_api is true, then decoded
    tags will be populated into both _tags_v1 and _tags_v2. _Tags_v2
    will be used if this IFD is used in the TIFF save routine. Tags
    should be read from tags_v1 if legacy_api == true.

    """

    def __init__(self, ifh=b"II\052\0\0\0\0\0", prefix=None):
        """Initialize an ImageFileDirectory.

        To construct an ImageFileDirectory from a real file, pass the 8-byte
        magic header to the constructor.  To only set the endianness, pass it
        as the 'prefix' keyword argument.

        :param ifh: One of the accepted magic headers (cf. PREFIXES); also sets
              endianness.
        :param prefix: Override the endianness of the file.
        """
        if ifh[:4] not in PREFIXES:
            raise SyntaxError("not a TIFF file (header %r not valid)" % ifh)
        self._prefix = prefix if prefix is not None else ifh[:2]
        if self._prefix == MM:
            self._endian = ">"
        elif self._prefix == II:
            self._endian = "<"
        else:
            raise SyntaxError("not a TIFF IFD")
        self.reset()
        self.next, = self._unpack("L", ifh[4:])
        self._legacy_api = False

    prefix = property(lambda self: self._prefix)
    offset = property(lambda self: self._offset)
    legacy_api = property(lambda self: self._legacy_api)

    @legacy_api.setter
    def legacy_api(self, value):
        raise Exception("Not allowing setting of legacy api")

    def reset(self):
        self._tags_v1 = {}  # will remain empty if legacy_api is false
        self._tags_v2 = {}  # main tag storage
        self._tagdata = {}
        self.tagtype = {}   # added 2008-06-05 by Florian Hoech
        self._next = None
        self._offset = None

    def __str__(self):
        return str(dict(self))

    def as_dict(self):
        """Return a dictionary of the image's tags.

        .. deprecated:: 3.0.0
        """
        warnings.warn("as_dict() is deprecated. " +
                      "Please use dict(ifd) instead.", DeprecationWarning)
        return dict(self)

    def named(self):
        """
        :returns: dict of name|key: value

        Returns the complete tag dictionary, with named tags where possible.
        """
        return dict((TiffTags.lookup(code).name, value)
                    for code, value in self.items())

    def __len__(self):
        return len(set(self._tagdata) | set(self._tags_v2))

    def __getitem__(self, tag):
        if tag not in self._tags_v2:  # unpack on the fly
            data = self._tagdata[tag]
            typ = self.tagtype[tag]
            size, handler = self._load_dispatch[typ]
            self[tag] = handler(self, data, self.legacy_api)  # check type
        val = self._tags_v2[tag]
        if self.legacy_api and not isinstance(val, (tuple, bytes)):
            val = val,
        return val

    def __contains__(self, tag):
        return tag in self._tags_v2 or tag in self._tagdata

    if bytes is str:
        def has_key(self, tag):
            return tag in self

    def __setitem__(self, tag, value):
        self._setitem(tag, value, self.legacy_api)

    def _setitem(self, tag, value, legacy_api):
        basetypes = (Number, bytes, str)
        if bytes is str:
            basetypes += unicode,

        info = TiffTags.lookup(tag)
        values = [value] if isinstance(value, basetypes) else value

        if tag not in self.tagtype:
            if info.type:
                self.tagtype[tag] = info.type
            else:
                self.tagtype[tag] = 7
                if all(isinstance(v, IFDRational) for v in values):
                    self.tagtype[tag] = 5
                elif all(isinstance(v, int) for v in values):
                    if all(v < 2 ** 16 for v in values):
                        self.tagtype[tag] = 3
                    else:
                        self.tagtype[tag] = 4
                elif all(isinstance(v, float) for v in values):
                    self.tagtype[tag] = 12
                else:
                    if bytes is str:
                        # Never treat data as binary by default on Python 2.
                        self.tagtype[tag] = 2
                    else:
                        if all(isinstance(v, str) for v in values):
                            self.tagtype[tag] = 2

        if self.tagtype[tag] == 7 and bytes is not str:
            values = [value.encode("ascii", 'replace') if isinstance(value, str) else value]

        values = tuple(info.cvt_enum(value) for value in values)

        dest = self._tags_v1 if legacy_api else self._tags_v2

        if info.length == 1:
            if legacy_api and self.tagtype[tag] in [5, 10]:
                values = values,
            dest[tag], = values
        else:
            dest[tag] = values

    def __delitem__(self, tag):
        self._tags_v2.pop(tag, None)
        self._tags_v1.pop(tag, None)
        self._tagdata.pop(tag, None)

    def __iter__(self):
        return iter(set(self._tagdata) | set(self._tags_v2))

    def _unpack(self, fmt, data):
        return struct.unpack(self._endian + fmt, data)

    def _pack(self, fmt, *values):
        return struct.pack(self._endian + fmt, *values)

    def _register_loader(idx, size):
        def decorator(func):
            from .TiffTags import TYPES
            if func.__name__.startswith("load_"):
                TYPES[idx] = func.__name__[5:].replace("_", " ")
            _load_dispatch[idx] = size, func
            return func
        return decorator

    def _register_writer(idx):
        def decorator(func):
            _write_dispatch[idx] = func
            return func
        return decorator

    def _register_basic(idx_fmt_name):
        from .TiffTags import TYPES
        idx, fmt, name = idx_fmt_name
        TYPES[idx] = name
        size = struct.calcsize("=" + fmt)
        _load_dispatch[idx] = size, lambda self, data, legacy_api=True: (
            self._unpack("{}{}".format(len(data) // size, fmt), data))
        _write_dispatch[idx] = lambda self, *values: (
            b"".join(self._pack(fmt, value) for value in values))

    list(map(_register_basic,
             [(3, "H", "short"), (4, "L", "long"),
              (6, "b", "signed byte"), (8, "h", "signed short"),
              (9, "l", "signed long"), (11, "f", "float"), (12, "d", "double")]))

    @_register_loader(1, 1)  # Basic type, except for the legacy API.
    def load_byte(self, data, legacy_api=True):
        return data

    @_register_writer(1)  # Basic type, except for the legacy API.
    def write_byte(self, data):
        return data

    @_register_loader(2, 1)
    def load_string(self, data, legacy_api=True):
        if data.endswith(b"\0"):
            data = data[:-1]
        return data.decode("latin-1", "replace")

    @_register_writer(2)
    def write_string(self, value):
        # remerge of https://github.com/python-pillow/Pillow/pull/1416
        if sys.version_info[0] == 2:
            value = value.decode('ascii', 'replace')
        return b"" + value.encode('ascii', 'replace') + b"\0"

    @_register_loader(5, 8)
    def load_rational(self, data, legacy_api=True):
        vals = self._unpack("{}L".format(len(data) // 4), data)
        combine = lambda a, b: (a, b) if legacy_api else IFDRational(a, b)
        return tuple(combine(num, denom)
                     for num, denom in zip(vals[::2], vals[1::2]))

    @_register_writer(5)
    def write_rational(self, *values):
        return b"".join(self._pack("2L", *_limit_rational(frac, 2 ** 31))
                        for frac in values)

    @_register_loader(7, 1)
    def load_undefined(self, data, legacy_api=True):
        return data

    @_register_writer(7)
    def write_undefined(self, value):
        return value

    @_register_loader(10, 8)
    def load_signed_rational(self, data, legacy_api=True):
        vals = self._unpack("{}l".format(len(data) // 4), data)
        combine = lambda a, b: (a, b) if legacy_api else IFDRational(a, b)
        return tuple(combine(num, denom)
                     for num, denom in zip(vals[::2], vals[1::2]))

    @_register_writer(10)
    def write_signed_rational(self, *values):
        return b"".join(self._pack("2L", *_limit_rational(frac, 2 ** 30))
                        for frac in values)

    def _ensure_read(self, fp, size):
        ret = fp.read(size)
        if len(ret) != size:
            raise IOError("Corrupt EXIF data.  " +
                          "Expecting to read %d bytes but only got %d. " %
                          (size, len(ret)))
        return ret

    def load(self, fp):

        self.reset()
        self._offset = fp.tell()

        try:
            for i in range(self._unpack("H", self._ensure_read(fp, 2))[0]):
                tag, typ, count, data = self._unpack("HHL4s", self._ensure_read(fp, 12))
                if DEBUG:
                    tagname = TiffTags.lookup(tag).name
                    typname = TYPES.get(typ, "unknown")
                    print("tag: %s (%d) - type: %s (%d)" %
                          (tagname, tag, typname, typ), end=" ")

                try:
                    unit_size, handler = self._load_dispatch[typ]
                except KeyError:
                    if DEBUG:
                        print("- unsupported type", typ)
                    continue  # ignore unsupported type
                size = count * unit_size
                if size > 4:
                    here = fp.tell()
                    offset, = self._unpack("L", data)
                    if DEBUG:
                        print("Tag Location: %s - Data Location: %s" %
                              (here, offset), end=" ")
                    fp.seek(offset)
                    data = ImageFile._safe_read(fp, size)
                    fp.seek(here)
                else:
                    data = data[:size]

                if len(data) != size:
                    warnings.warn("Possibly corrupt EXIF data.  "
                                  "Expecting to read %d bytes but only got %d. "
                                  "Skipping tag %s" % (size, len(data), tag))
                    continue

                if not data:
                    continue

                self._tagdata[tag] = data
                self.tagtype[tag] = typ

                if DEBUG:
                    if size > 32:
                        print("- value: <table: %d bytes>" % size)
                    else:
                        print("- value:", self[tag])

            self.next, = self._unpack("L", self._ensure_read(fp, 4))
        except IOError as msg:
            warnings.warn(str(msg))
            return

    def save(self, fp):

        if fp.tell() == 0:  # skip TIFF header on subsequent pages
            # tiff header -- PIL always starts the first IFD at offset 8
            fp.write(self._prefix + self._pack("HL", 42, 8))

        # FIXME What about tagdata?
        fp.write(self._pack("H", len(self._tags_v2)))

        entries = []
        offset = fp.tell() + len(self._tags_v2) * 12 + 4
        stripoffsets = None

        # pass 1: convert tags to binary format
        # always write tags in ascending order
        for tag, value in sorted(self._tags_v2.items()):
            if tag == STRIPOFFSETS:
                stripoffsets = len(entries)
            typ = self.tagtype.get(tag)
            if DEBUG:
                print("Tag %s, Type: %s, Value: %s" % (tag, typ, value))
            values = value if isinstance(value, tuple) else (value,)
            data = self._write_dispatch[typ](self, *values)
            if DEBUG:
                tagname = TiffTags.lookup(tag).name
                typname = TYPES.get(typ, "unknown")
                print("save: %s (%d) - type: %s (%d)" %
                      (tagname, tag, typname, typ), end=" ")
                if len(data) >= 16:
                    print("- value: <table: %d bytes>" % len(data))
                else:
                    print("- value:", values)

            # count is sum of lengths for string and arbitrary data
            count = len(data) if typ in [2, 7] else len(values)
            # figure out if data fits into the entry
            if len(data) <= 4:
                entries.append((tag, typ, count, data.ljust(4, b"\0"), b""))
            else:
                entries.append((tag, typ, count, self._pack("L", offset), data))
                offset += (len(data) + 1) // 2 * 2  # pad to word

        # update strip offset data to point beyond auxiliary data
        if stripoffsets is not None:
            tag, typ, count, value, data = entries[stripoffsets]
            if data:
                raise NotImplementedError(
                    "multistrip support not yet implemented")
            value = self._pack("L", self._unpack("L", value)[0] + offset)
            entries[stripoffsets] = tag, typ, count, value, data

        # pass 2: write entries to file
        for tag, typ, count, value, data in entries:
            if DEBUG > 1:
                print(tag, typ, count, repr(value), repr(data))
            fp.write(self._pack("HHL4s", tag, typ, count, value))

        # -- overwrite here for multi-page --
        fp.write(b"\0\0\0\0")  # end of entries

        # pass 3: write auxiliary data to file
        for tag, typ, count, value, data in entries:
            fp.write(data)
            if len(data) & 1:
                fp.write(b"\0")

        return offset

ImageFileDirectory_v2._load_dispatch = _load_dispatch
ImageFileDirectory_v2._write_dispatch = _write_dispatch
for idx, name in TYPES.items():
    name = name.replace(" ", "_")
    setattr(ImageFileDirectory_v2, "load_" + name, _load_dispatch[idx][1])
    setattr(ImageFileDirectory_v2, "write_" + name, _write_dispatch[idx])
del _load_dispatch, _write_dispatch, idx, name


# Legacy ImageFileDirectory support.
class ImageFileDirectory_v1(ImageFileDirectory_v2):
    """This class represents the **legacy** interface to a TIFF tag directory.

    Exposes a dictionary interface of the tags in the directory::

        ifd = ImageFileDirectory_v1()
        ifd[key] = 'Some Data'
        ifd.tagtype[key] = 2
        print(ifd[key])
        ('Some Data',)

    Also contains a dictionary of tag types as read from the tiff image file,
    `~PIL.TiffImagePlugin.ImageFileDirectory_v1.tagtype`.

    Values are returned as a tuple.

    ..  deprecated:: 3.0.0
    """
    def __init__(self, *args, **kwargs):
        ImageFileDirectory_v2.__init__(self, *args, **kwargs)
        self._legacy_api = True

    tags = property(lambda self: self._tags_v1)
    tagdata = property(lambda self: self._tagdata)

    @classmethod
    def from_v2(cls, original):
        """ Returns an
        :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`
        instance with the same data as is contained in the original
        :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`
        instance.

        :returns: :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`

        """

        ifd = cls(prefix=original.prefix)
        ifd._tagdata = original._tagdata
        ifd.tagtype = original.tagtype
        ifd.next = original.next  # an indicator for multipage tiffs
        return ifd

    def to_v2(self):
        """ Returns an
        :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`
        instance with the same data as is contained in the original
        :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`
        instance.

        :returns: :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`

        """

        ifd = ImageFileDirectory_v2(prefix=self.prefix)
        ifd._tagdata = dict(self._tagdata)
        ifd.tagtype = dict(self.tagtype)
        ifd._tags_v2 = dict(self._tags_v2)
        return ifd

    def __contains__(self, tag):
        return tag in self._tags_v1 or tag in self._tagdata

    def __len__(self):
        return len(set(self._tagdata) | set(self._tags_v1))

    def __iter__(self):
        return iter(set(self._tagdata) | set(self._tags_v1))

    def __setitem__(self, tag, value):
        for legacy_api in (False, True):
            self._setitem(tag, value, legacy_api)

    def __getitem__(self, tag):
        if tag not in self._tags_v1:  # unpack on the fly
            data = self._tagdata[tag]
            typ = self.tagtype[tag]
            size, handler = self._load_dispatch[typ]
            for legacy in (False, True):
                self._setitem(tag, handler(self, data, legacy), legacy)
        val = self._tags_v1[tag]
        if not isinstance(val, (tuple, bytes)):
            val = val,
        return val


# undone -- switch this pointer when IFD_LEGACY_API == False
ImageFileDirectory = ImageFileDirectory_v1


##
# Image plugin for TIFF files.

class TiffImageFile(ImageFile.ImageFile):

    format = "TIFF"
    format_description = "Adobe TIFF"

    def _open(self):
        "Open the first image in a TIFF file"

        # Header
        ifh = self.fp.read(8)

        # image file directory (tag dictionary)
        self.tag_v2 = ImageFileDirectory_v2(ifh)

        # legacy tag/ifd entries will be filled in later
        self.tag = self.ifd = None

        # setup frame pointers
        self.__first = self.__next = self.tag_v2.next
        self.__frame = -1
        self.__fp = self.fp
        self._frame_pos = []
        self._n_frames = None
        self._is_animated = None

        if DEBUG:
            print("*** TiffImageFile._open ***")
            print("- __first:", self.__first)
            print("- ifh: ", ifh)

        # and load the first frame
        self._seek(0)

    @property
    def n_frames(self):
        if self._n_frames is None:
            current = self.tell()
            try:
                while True:
                    self._seek(self.tell() + 1)
            except EOFError:
                self._n_frames = self.tell() + 1
            self.seek(current)
        return self._n_frames

    @property
    def is_animated(self):
        if self._is_animated is None:
            current = self.tell()

            try:
                self.seek(1)
                self._is_animated = True
            except EOFError:
                self._is_animated = False

            self.seek(current)
        return self._is_animated

    def seek(self, frame):
        "Select a given frame as current image"
        self._seek(max(frame, 0))  # Questionable backwards compatibility.
        # Create a new core image object on second and
        # subsequent frames in the image. Image may be
        # different size/mode.
        Image._decompression_bomb_check(self.size)
        self.im = Image.core.new(self.mode, self.size)

    def _seek(self, frame):
        self.fp = self.__fp
        while len(self._frame_pos) <= frame:
            if not self.__next:
                raise EOFError("no more images in TIFF file")
            if DEBUG:
                print("Seeking to frame %s, on frame %s, "
                      "__next %s, location: %s" %
                      (frame, self.__frame, self.__next, self.fp.tell()))
            # reset python3 buffered io handle in case fp
            # was passed to libtiff, invalidating the buffer
            self.fp.tell()
            self.fp.seek(self.__next)
            self._frame_pos.append(self.__next)
            if DEBUG:
                print("Loading tags, location: %s" % self.fp.tell())
            self.tag_v2.load(self.fp)
            self.__next = self.tag_v2.next
            self.__frame += 1
        self.fp.seek(self._frame_pos[frame])
        self.tag_v2.load(self.fp)
        # fill the legacy tag/ifd entries
        self.tag = self.ifd = ImageFileDirectory_v1.from_v2(self.tag_v2)
        self.__frame = frame
        self._setup()

    def tell(self):
        "Return the current frame number"
        return self.__frame

    def _decoder(self, rawmode, layer, tile=None):
        "Setup decoder contexts"

        args = None
        if rawmode == "RGB" and self._planar_configuration == 2:
            rawmode = rawmode[layer]
        compression = self._compression
        if compression == "raw":
            args = (rawmode, 0, 1)
        elif compression == "jpeg":
            args = rawmode, ""
            if JPEGTABLES in self.tag_v2:
                # Hack to handle abbreviated JPEG headers
                # FIXME This will fail with more than one value
                self.tile_prefix, = self.tag_v2[JPEGTABLES]
        elif compression == "packbits":
            args = rawmode
        elif compression == "tiff_lzw":
            args = rawmode
            if PREDICTOR in self.tag_v2:
                # Section 14: Differencing Predictor
                self.decoderconfig = (self.tag_v2[PREDICTOR],)

        return args

    def load(self):
        if self.use_load_libtiff:
            return self._load_libtiff()
        return super(TiffImageFile, self).load()

    def _load_libtiff(self):
        """ Overload method triggered when we detect a compressed tiff
            Calls out to libtiff """

        pixel = Image.Image.load(self)

        if self.tile is None:
            raise IOError("cannot load this image")
        if not self.tile:
            return pixel

        self.load_prepare()

        if not len(self.tile) == 1:
            raise IOError("Not exactly one tile")

        # (self._compression, (extents tuple),
        #   0, (rawmode, self._compression, fp))
        extents = self.tile[0][1]
        args = list(self.tile[0][3]) + [self.tag_v2.offset]

        # To be nice on memory footprint, if there's a
        # file descriptor, use that instead of reading
        # into a string in python.
        # libtiff closes the file descriptor, so pass in a dup.
        try:
            fp = hasattr(self.fp, "fileno") and os.dup(self.fp.fileno())
            # flush the file descriptor, prevents error on pypy 2.4+
            # should also eliminate the need for fp.tell for py3
            # in _seek
            if hasattr(self.fp, "flush"):
                self.fp.flush()
        except IOError:
            # io.BytesIO have a fileno, but returns an IOError if
            # it doesn't use a file descriptor.
            fp = False

        if fp:
            args[2] = fp

        decoder = Image._getdecoder(self.mode, 'libtiff', tuple(args),
                                    self.decoderconfig)
        try:
            decoder.setimage(self.im, extents)
        except ValueError:
            raise IOError("Couldn't set the image")

        if hasattr(self.fp, "getvalue"):
            # We've got a stringio like thing passed in. Yay for all in memory.
            # The decoder needs the entire file in one shot, so there's not
            # a lot we can do here other than give it the entire file.
            # unless we could do something like get the address of the
            # underlying string for stringio.
            #
            # Rearranging for supporting byteio items, since they have a fileno
            # that returns an IOError if there's no underlying fp. Easier to
            # deal with here by reordering.
            if DEBUG:
                print("have getvalue. just sending in a string from getvalue")
            n, err = decoder.decode(self.fp.getvalue())
        elif hasattr(self.fp, "fileno"):
            # we've got a actual file on disk, pass in the fp.
            if DEBUG:
                print("have fileno, calling fileno version of the decoder.")
            self.fp.seek(0)
            # 4 bytes, otherwise the trace might error out
            n, err = decoder.decode(b"fpfp")
        else:
            # we have something else.
            if DEBUG:
                print("don't have fileno or getvalue. just reading")
            # UNDONE -- so much for that buffer size thing.
            n, err = decoder.decode(self.fp.read())

        self.tile = []
        self.readonly = 0
        # libtiff closed the fp in a, we need to close self.fp, if possible
        if hasattr(self.fp, 'close'):
            if not self.__next:
                self.fp.close()
        self.fp = None  # might be shared

        if err < 0:
            raise IOError(err)

        self.load_end()

        return Image.Image.load(self)

    def _setup(self):
        "Setup this image object based on current tags"

        if 0xBC01 in self.tag_v2:
            raise IOError("Windows Media Photo files not yet supported")

        # extract relevant tags
        self._compression = COMPRESSION_INFO[self.tag_v2.get(COMPRESSION, 1)]
        self._planar_configuration = self.tag_v2.get(PLANAR_CONFIGURATION, 1)

        # photometric is a required tag, but not everyone is reading
        # the specification
        photo = self.tag_v2.get(PHOTOMETRIC_INTERPRETATION, 0)

        fillorder = self.tag_v2.get(FILLORDER, 1)

        if DEBUG:
            print("*** Summary ***")
            print("- compression:", self._compression)
            print("- photometric_interpretation:", photo)
            print("- planar_configuration:", self._planar_configuration)
            print("- fill_order:", fillorder)

        # size
        xsize = self.tag_v2.get(IMAGEWIDTH)
        ysize = self.tag_v2.get(IMAGELENGTH)
        self.size = xsize, ysize

        if DEBUG:
            print("- size:", self.size)

        sampleFormat = self.tag_v2.get(SAMPLEFORMAT, (1,))
        if (len(sampleFormat) > 1
            and max(sampleFormat) == min(sampleFormat) == 1):
            # SAMPLEFORMAT is properly per band, so an RGB image will
            # be (1,1,1).  But, we don't support per band pixel types,
            # and anything more than one band is a uint8. So, just
            # take the first element. Revisit this if adding support
            # for more exotic images.
            sampleFormat = (1,)

        # mode: check photometric interpretation and bits per pixel
        key = (
            self.tag_v2.prefix, photo, sampleFormat, fillorder,
            self.tag_v2.get(BITSPERSAMPLE, (1,)),
            self.tag_v2.get(EXTRASAMPLES, ())
            )
        if DEBUG:
            print("format key:", key)
        try:
            self.mode, rawmode = OPEN_INFO[key]
        except KeyError:
            if DEBUG:
                print("- unsupported format")
            raise SyntaxError("unknown pixel mode")

        if DEBUG:
            print("- raw mode:", rawmode)
            print("- pil mode:", self.mode)

        self.info["compression"] = self._compression

        xres = self.tag_v2.get(X_RESOLUTION, 1)
        yres = self.tag_v2.get(Y_RESOLUTION, 1)

        if xres and yres:
            resunit = self.tag_v2.get(RESOLUTION_UNIT, 1)
            if resunit == 2:  # dots per inch
                self.info["dpi"] = xres, yres
            elif resunit == 3:  # dots per centimeter. convert to dpi
                self.info["dpi"] = xres * 2.54, yres * 2.54
            else:  # No absolute unit of measurement
                self.info["resolution"] = xres, yres

        # build tile descriptors
        x = y = l = 0
        self.tile = []
        self.use_load_libtiff = False
        if STRIPOFFSETS in self.tag_v2:
            # striped image
            offsets = self.tag_v2[STRIPOFFSETS]
            h = self.tag_v2.get(ROWSPERSTRIP, ysize)
            w = self.size[0]
            if READ_LIBTIFF or self._compression in ["tiff_ccitt", "group3",
                                                     "group4", "tiff_jpeg",
                                                     "tiff_adobe_deflate",
                                                     "tiff_thunderscan",
                                                     "tiff_deflate",
                                                     "tiff_sgilog",
                                                     "tiff_sgilog24",
                                                     "tiff_raw_16"]:
                # if DEBUG:
                #     print("Activating g4 compression for whole file")

                # Decoder expects entire file as one tile.
                # There's a buffer size limit in load (64k)
                # so large g4 images will fail if we use that
                # function.
                #
                # Setup the one tile for the whole image, then
                # use the _load_libtiff function.

                self.use_load_libtiff = True

                # libtiff handles the fillmode for us, so 1;IR should
                # actually be 1;I. Including the R double reverses the
                # bits, so stripes of the image are reversed.  See
                # https://github.com/python-pillow/Pillow/issues/279
                if fillorder == 2:
                    key = (
                        self.tag_v2.prefix, photo, sampleFormat, 1,
                        self.tag_v2.get(BITSPERSAMPLE, (1,)),
                        self.tag_v2.get(EXTRASAMPLES, ())
                        )
                    if DEBUG:
                        print("format key:", key)
                    # this should always work, since all the
                    # fillorder==2 modes have a corresponding
                    # fillorder=1 mode
                    self.mode, rawmode = OPEN_INFO[key]
                # libtiff always returns the bytes in native order.
                # we're expecting image byte order. So, if the rawmode
                # contains I;16, we need to convert from native to image
                # byte order.
                if self.mode in ('I;16B', 'I;16') and 'I;16' in rawmode:
                    rawmode = 'I;16N'

                # Offset in the tile tuple is 0, we go from 0,0 to
                # w,h, and we only do this once -- eds
                a = (rawmode, self._compression, False)
                self.tile.append(
                    (self._compression,
                     (0, 0, w, ysize),
                     0, a))
                a = None

            else:
                for i, offset in enumerate(offsets):
                    a = self._decoder(rawmode, l, i)
                    self.tile.append(
                        (self._compression,
                            (0, min(y, ysize), w, min(y+h, ysize)),
                            offset, a))
                    if DEBUG:
                        print("tiles: ", self.tile)
                    y = y + h
                    if y >= self.size[1]:
                        x = y = 0
                        l += 1
                    a = None
        elif TILEOFFSETS in self.tag_v2:
            # tiled image
            w = self.tag_v2.get(322)
            h = self.tag_v2.get(323)
            a = None
            for o in self.tag_v2[TILEOFFSETS]:
                if not a:
                    a = self._decoder(rawmode, l)
                # FIXME: this doesn't work if the image size
                # is not a multiple of the tile size...
                self.tile.append(
                    (self._compression,
                        (x, y, x+w, y+h),
                        o, a))
                x = x + w
                if x >= self.size[0]:
                    x, y = 0, y + h
                    if y >= self.size[1]:
                        x = y = 0
                        l += 1
                        a = None
        else:
            if DEBUG:
                print("- unsupported data organization")
            raise SyntaxError("unknown data organization")

        # Fix up info.
        if ICCPROFILE in self.tag_v2:
            self.info['icc_profile'] = self.tag_v2[ICCPROFILE]

        # fixup palette descriptor

        if self.mode == "P":
            palette = [o8(b // 256) for b in self.tag_v2[COLORMAP]]
            self.palette = ImagePalette.raw("RGB;L", b"".join(palette))
#
# --------------------------------------------------------------------
# Write TIFF files

# little endian is default except for image modes with
# explicit big endian byte-order

SAVE_INFO = {
    # mode => rawmode, byteorder, photometrics,
    #           sampleformat, bitspersample, extra
    "1": ("1", II, 1, 1, (1,), None),
    "L": ("L", II, 1, 1, (8,), None),
    "LA": ("LA", II, 1, 1, (8, 8), 2),
    "P": ("P", II, 3, 1, (8,), None),
    "PA": ("PA", II, 3, 1, (8, 8), 2),
    "I": ("I;32S", II, 1, 2, (32,), None),
    "I;16": ("I;16", II, 1, 1, (16,), None),
    "I;16S": ("I;16S", II, 1, 2, (16,), None),
    "F": ("F;32F", II, 1, 3, (32,), None),
    "RGB": ("RGB", II, 2, 1, (8, 8, 8), None),
    "RGBX": ("RGBX", II, 2, 1, (8, 8, 8, 8), 0),
    "RGBA": ("RGBA", II, 2, 1, (8, 8, 8, 8), 2),
    "CMYK": ("CMYK", II, 5, 1, (8, 8, 8, 8), None),
    "YCbCr": ("YCbCr", II, 6, 1, (8, 8, 8), None),
    "LAB": ("LAB", II, 8, 1, (8, 8, 8), None),

    "I;32BS": ("I;32BS", MM, 1, 2, (32,), None),
    "I;16B": ("I;16B", MM, 1, 1, (16,), None),
    "I;16BS": ("I;16BS", MM, 1, 2, (16,), None),
    "F;32BF": ("F;32BF", MM, 1, 3, (32,), None),
}


def _save(im, fp, filename):

    try:
        rawmode, prefix, photo, format, bits, extra = SAVE_INFO[im.mode]
    except KeyError:
        raise IOError("cannot write mode %s as TIFF" % im.mode)

    ifd = ImageFileDirectory_v2(prefix=prefix)

    compression = im.encoderinfo.get('compression',
                                     im.info.get('compression', 'raw'))

    libtiff = WRITE_LIBTIFF or compression != 'raw'

    # required for color libtiff images
    ifd[PLANAR_CONFIGURATION] = getattr(im, '_planar_configuration', 1)

    ifd[IMAGEWIDTH] = im.size[0]
    ifd[IMAGELENGTH] = im.size[1]

    # write any arbitrary tags passed in as an ImageFileDirectory
    info = im.encoderinfo.get("tiffinfo", {})
    if DEBUG:
        print("Tiffinfo Keys: %s" % list(info))
    if isinstance(info, ImageFileDirectory_v1):
        info = info.to_v2()
    for key in info:
        ifd[key] = info.get(key)
        try:
            ifd.tagtype[key] = info.tagtype[key]
        except:
            pass  # might not be an IFD, Might not have populated type

    # additions written by Greg Couch, gregc@cgl.ucsf.edu
    # inspired by image-sig posting from Kevin Cazabon, kcazabon@home.com
    if hasattr(im, 'tag_v2'):
        # preserve tags from original TIFF image file
        for key in (RESOLUTION_UNIT, X_RESOLUTION, Y_RESOLUTION,
                    IPTC_NAA_CHUNK, PHOTOSHOP_CHUNK, XMP):
            if key in im.tag_v2:
                ifd[key] = im.tag_v2[key]
                ifd.tagtype[key] = im.tag_v2.tagtype[key]

    # preserve ICC profile (should also work when saving other formats
    # which support profiles as TIFF) -- 2008-06-06 Florian Hoech
    if "icc_profile" in im.info:
        ifd[ICCPROFILE] = im.info["icc_profile"]

    for key, name in [(IMAGEDESCRIPTION, "description"),
                      (X_RESOLUTION, "resolution"),
                      (Y_RESOLUTION, "resolution"),
                      (X_RESOLUTION, "x_resolution"),
                      (Y_RESOLUTION, "y_resolution"),
                      (RESOLUTION_UNIT, "resolution_unit"),
                      (SOFTWARE, "software"),
                      (DATE_TIME, "date_time"),
                      (ARTIST, "artist"),
                      (COPYRIGHT, "copyright")]:
        name_with_spaces = name.replace("_", " ")
        if "_" in name and name_with_spaces in im.encoderinfo:
            warnings.warn("%r is deprecated; use %r instead" %
                          (name_with_spaces, name), DeprecationWarning)
            ifd[key] = im.encoderinfo[name.replace("_", " ")]
        if name in im.encoderinfo:
            ifd[key] = im.encoderinfo[name]

    dpi = im.encoderinfo.get("dpi")
    if dpi:
        ifd[RESOLUTION_UNIT] = 2
        ifd[X_RESOLUTION] = dpi[0]
        ifd[Y_RESOLUTION] = dpi[1]

    if bits != (1,):
        ifd[BITSPERSAMPLE] = bits
        if len(bits) != 1:
            ifd[SAMPLESPERPIXEL] = len(bits)
    if extra is not None:
        ifd[EXTRASAMPLES] = extra
    if format != 1:
        ifd[SAMPLEFORMAT] = format

    ifd[PHOTOMETRIC_INTERPRETATION] = photo

    if im.mode == "P":
        lut = im.im.getpalette("RGB", "RGB;L")
        ifd[COLORMAP] = tuple(i8(v) * 256 for v in lut)
    # data orientation
    stride = len(bits) * ((im.size[0]*bits[0]+7)//8)
    ifd[ROWSPERSTRIP] = im.size[1]
    ifd[STRIPBYTECOUNTS] = stride * im.size[1]
    ifd[STRIPOFFSETS] = 0  # this is adjusted by IFD writer
    # no compression by default:
    ifd[COMPRESSION] = COMPRESSION_INFO_REV.get(compression, 1)

    if libtiff:
        if DEBUG:
            print("Saving using libtiff encoder")
            print("Items: %s" % sorted(ifd.items()))
        _fp = 0
        if hasattr(fp, "fileno"):
            try:
                fp.seek(0)
                _fp = os.dup(fp.fileno())
            except io.UnsupportedOperation:
                pass

        # STRIPOFFSETS and STRIPBYTECOUNTS are added by the library
        # based on the data in the strip.
        blocklist = [STRIPOFFSETS, STRIPBYTECOUNTS]
        atts = {}
        # bits per sample is a single short in the tiff directory, not a list.
        atts[BITSPERSAMPLE] = bits[0]
        # Merge the ones that we have with (optional) more bits from
        # the original file, e.g x,y resolution so that we can
        # save(load('')) == original file.
        legacy_ifd = {}
        if hasattr(im, 'tag'):
            legacy_ifd = im.tag.to_v2()
        for tag, value in itertools.chain(ifd.items(),
                                          getattr(im, 'tag_v2', {}).items(),
                                          legacy_ifd.items()):
            # Libtiff can only process certain core items without adding
            # them to the custom dictionary. It will segfault if it attempts
            # to add a custom tag without the dictionary entry
            #
            # UNDONE --  add code for the custom dictionary
            if tag not in TiffTags.LIBTIFF_CORE:
                continue
            if tag not in atts and tag not in blocklist:
                if isinstance(value, unicode if bytes is str else str):
                    atts[tag] = value.encode('ascii', 'replace') + b"\0"
                elif isinstance(value, IFDRational):
                    atts[tag] = float(value)
                else:
                    atts[tag] = value

        if DEBUG:
            print("Converted items: %s" % sorted(atts.items()))

        # libtiff always expects the bytes in native order.
        # we're storing image byte order. So, if the rawmode
        # contains I;16, we need to convert from native to image
        # byte order.
        if im.mode in ('I;16B', 'I;16'):
            rawmode = 'I;16N'

        a = (rawmode, compression, _fp, filename, atts)
        # print(im.mode, compression, a, im.encoderconfig)
        e = Image._getencoder(im.mode, 'libtiff', a, im.encoderconfig)
        e.setimage(im.im, (0, 0)+im.size)
        while True:
            # undone, change to self.decodermaxblock:
            l, s, d = e.encode(16*1024)
            if not _fp:
                fp.write(d)
            if s:
                break
        if s < 0:
            raise IOError("encoder error %d when writing image file" % s)

    else:
        offset = ifd.save(fp)

        ImageFile._save(im, fp, [
            ("raw", (0, 0)+im.size, offset, (rawmode, stride, 1))
            ])

    # -- helper for multi-page save --
    if "_debug_multipage" in im.encoderinfo:
        # just to access o32 and o16 (using correct byte order)
        im._debug_multipage = ifd

class AppendingTiffWriter:
    fieldSizes = [
        0,  # None
        1,  # byte
        1,  # ascii
        2,  # short
        4,  # long
        8,  # rational
        1,  # sbyte
        1,  # undefined
        2,  # sshort
        4,  # slong
        8,  # srational
        4,  # float
        8,  # double
    ]

    #    StripOffsets = 273
    #    FreeOffsets = 288
    #    TileOffsets = 324
    #    JPEGQTables = 519
    #    JPEGDCTables = 520
    #    JPEGACTables = 521
    Tags = {273, 288, 324, 519, 520, 521}

    def __init__(self, fn, new=False):
        if hasattr(fn, 'read'):
            self.f = fn
            self.close_fp = False
        else:
            self.name = fn
            self.close_fp = True
            try:
                self.f = io.open(fn, "w+b" if new else "r+b")
            except IOError:
                self.f = io.open(fn, "w+b")
        self.beginning = self.f.tell()
        self.setup()

    def setup(self):
        # Reset everything.
        self.f.seek(self.beginning, os.SEEK_SET)

        self.whereToWriteNewIFDOffset = None
        self.offsetOfNewPage = 0

        self.IIMM = IIMM = self.f.read(4)
        if not IIMM:
            # empty file - first page
            self.isFirst = True
            return

        self.isFirst = False
        if IIMM == b"II\x2a\x00":
            self.setEndian("<")
        elif IIMM == b"MM\x00\x2a":
            self.setEndian(">")
        else:
            raise RuntimeError("Invalid TIFF file header")

        self.skipIFDs()
        self.goToEnd()

    def finalize(self):
        if self.isFirst:
            return

        # fix offsets
        self.f.seek(self.offsetOfNewPage)

        IIMM = self.f.read(4)
        if not IIMM:
            # raise RuntimeError("nothing written into new page")
            # Make it easy to finish a frame without committing to a new one.
            return

        if IIMM != self.IIMM:
            raise RuntimeError("IIMM of new page doesn't match IIMM of "
                               "first page")

        IFDoffset = self.readLong()
        IFDoffset += self.offsetOfNewPage
        self.f.seek(self.whereToWriteNewIFDOffset)
        self.writeLong(IFDoffset)
        self.f.seek(IFDoffset)
        self.fixIFD()

    def newFrame(self):
        # Call this to finish a frame.
        self.finalize()
        self.setup()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        if self.close_fp:
            self.close()
        return False

    def tell(self):
        return self.f.tell() - self.offsetOfNewPage

    def seek(self, offset, whence):
        if whence == os.SEEK_SET:
            offset += self.offsetOfNewPage

        self.f.seek(offset, whence)
        return self.tell()

    def goToEnd(self):
        self.f.seek(0, os.SEEK_END)
        pos = self.f.tell()

        # pad to 16 byte boundary
        padBytes = 16 - pos % 16
        if 0 < padBytes < 16:
            self.f.write(bytes(bytearray(padBytes)))
        self.offsetOfNewPage = self.f.tell()

    def setEndian(self, endian):
        self.endian = endian
        self.longFmt = self.endian + "L"
        self.shortFmt = self.endian + "H"
        self.tagFormat = self.endian + "HHL"

    def skipIFDs(self):
        while True:
            IFDoffset = self.readLong()
            if IFDoffset == 0:
                self.whereToWriteNewIFDOffset = self.f.tell() - 4
                break

            self.f.seek(IFDoffset)
            numTags = self.readShort()
            self.f.seek(numTags * 12, os.SEEK_CUR)

    def write(self, data):
        return self.f.write(data)

    def readShort(self):
        value, = struct.unpack(self.shortFmt, self.f.read(2))
        return value

    def readLong(self):
        value, = struct.unpack(self.longFmt, self.f.read(4))
        return value

    def rewriteLastShortToLong(self, value):
        self.f.seek(-2, os.SEEK_CUR)
        bytesWritten = self.f.write(struct.pack(self.longFmt, value))
        if bytesWritten is not None and bytesWritten != 4:
            raise RuntimeError("wrote only %u bytes but wanted 4" %
                               bytesWritten)

    def rewriteLastShort(self, value):
        self.f.seek(-2, os.SEEK_CUR)
        bytesWritten = self.f.write(struct.pack(self.shortFmt, value))
        if bytesWritten is not None and bytesWritten != 2:
            raise RuntimeError("wrote only %u bytes but wanted 2" %
                               bytesWritten)

    def rewriteLastLong(self, value):
        self.f.seek(-4, os.SEEK_CUR)
        bytesWritten = self.f.write(struct.pack(self.longFmt, value))
        if bytesWritten is not None and bytesWritten != 4:
            raise RuntimeError("wrote only %u bytes but wanted 4" %
                               bytesWritten)

    def writeShort(self, value):
        bytesWritten = self.f.write(struct.pack(self.shortFmt, value))
        if bytesWritten is not None and bytesWritten != 2:
            raise RuntimeError("wrote only %u bytes but wanted 2" %
                               bytesWritten)

    def writeLong(self, value):
        bytesWritten = self.f.write(struct.pack(self.longFmt, value))
        if bytesWritten is not None and bytesWritten != 4:
            raise RuntimeError("wrote only %u bytes but wanted 4" %
                               bytesWritten)

    def close(self):
        self.finalize()
        self.f.close()

    def fixIFD(self):
        numTags = self.readShort()
        #trace("fixing IFD at %X; number of tags: %u (0x%X)", self.f.tell()-2,
        #      numTags, numTags)

        for i in range(numTags):
            tag, fieldType, count = struct.unpack(self.tagFormat, self.f.read(8))
            #trace("  at %X: tag %u (0x%X), type %u, count %u", self.f.tell()-8,
            #      tag, tag, fieldType, count)

            fieldSize = self.fieldSizes[fieldType]
            totalSize = fieldSize * count
            isLocal = (totalSize <= 4)
            if not isLocal:
                offset = self.readLong()
                offset += self.offsetOfNewPage
                self.rewriteLastLong(offset)

            if tag in self.Tags:
                curPos = self.f.tell()

                if isLocal:
                    self.fixOffsets(count, isShort=(fieldSize == 2),
                                    isLong=(fieldSize == 4))
                    self.f.seek(curPos + 4)
                else:
                    self.f.seek(offset)
                    self.fixOffsets(count, isShort=(fieldSize == 2),
                                    isLong=(fieldSize == 4))
                    self.f.seek(curPos)

                offset = curPos = None

            elif isLocal:
                # skip the locally stored value that is not an offset
                self.f.seek(4, os.SEEK_CUR)

    def fixOffsets(self, count, isShort=False, isLong=False):
        if not isShort and not isLong:
            raise RuntimeError("offset is neither short nor long")

        for i in range(count):
            offset = self.readShort() if isShort else self.readLong()
            offset += self.offsetOfNewPage
            if isShort and offset >= 65536:
                # offset is now too large - we must convert shorts to longs
                if count != 1:
                    raise RuntimeError("not implemented")  # XXX TODO

                # simple case - the offset is just one and therefore it is
                # local (not referenced with another offset)
                self.rewriteLastShortToLong(offset)
                self.f.seek(-10, os.SEEK_CUR)
                self.writeShort(4)  # rewrite the type to LONG
                self.f.seek(8, os.SEEK_CUR)
            elif isShort:
                self.rewriteLastShort(offset)
            else:
                self.rewriteLastLong(offset)

def _save_all(im, fp, filename):
    if not hasattr(im, "n_frames"):
        return _save(im, fp, filename)

    cur_idx = im.tell()
    try:
        with AppendingTiffWriter(fp) as tf:
            for idx in range(im.n_frames):
                im.seek(idx)
                im.load()
                _save(im, tf, filename)
                tf.newFrame()
    finally:
        im.seek(cur_idx)

#
# --------------------------------------------------------------------
# Register

Image.register_open(TiffImageFile.format, TiffImageFile, _accept)
Image.register_save(TiffImageFile.format, _save)
Image.register_save_all(TiffImageFile.format, _save_all)

Image.register_extension(TiffImageFile.format, ".tif")
Image.register_extension(TiffImageFile.format, ".tiff")

Image.register_mime(TiffImageFile.format, "image/tiff")

```
--- END FILE ---

Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.

Every *SEARCH/REPLACE* edit must use this format:
1. The file path
2. The start of search block: <<<<<<< SEARCH
3. A contiguous chunk of lines to search for in the existing source code
4. The dividing line: =======
5. The lines to replace into the source code
6. The end of the replace block: >>>>>>> REPLACE

Here is an example:

```python
### mathweb/flask/app.py
<<<<<<< SEARCH
from flask import Flask
=======
import math
from flask import Flask
>>>>>>> REPLACE
```
</solution>

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
user