{
    "file_diffs": [
        {
            "old_file_content": "import os\nimport re\nfrom io import BytesIO\n\nimport pytest\nfrom PIL import ExifTags, Image, ImageFile, JpegImagePlugin\n\nfrom .helper import (\n    assert_image,\n    assert_image_equal,\n    assert_image_similar,\n    cjpeg_available,\n    djpeg_available,\n    hopper,\n    is_win32,\n    skip_unless_feature,\n)\n\nTEST_FILE = \"Tests/images/hopper.jpg\"\n\n\n@skip_unless_feature(\"jpg\")\nclass TestFileJpeg:\n    def roundtrip(self, im, **options):\n        out = BytesIO()\n        im.save(out, \"JPEG\", **options)\n        test_bytes = out.tell()\n        out.seek(0)\n        im = Image.open(out)\n        im.bytes = test_bytes  # for testing only\n        return im\n\n    def gen_random_image(self, size, mode=\"RGB\"):\n        \"\"\" Generates a very hard to compress file\n        :param size: tuple\n        :param mode: optional image mode\n\n        \"\"\"\n        return Image.frombytes(mode, size, os.urandom(size[0] * size[1] * len(mode)))\n\n    def test_sanity(self):\n\n        # internal version number\n        assert re.search(r\"\\d+\\.\\d+$\", Image.core.jpeglib_version)\n\n        with Image.open(TEST_FILE) as im:\n            im.load()\n            assert im.mode == \"RGB\"\n            assert im.size == (128, 128)\n            assert im.format == \"JPEG\"\n            assert im.get_format_mimetype() == \"image/jpeg\"\n\n    def test_app(self):\n        # Test APP/COM reader (@PIL135)\n        with Image.open(TEST_FILE) as im:\n            assert im.applist[0] == (\"APP0\", b\"JFIF\\x00\\x01\\x01\\x01\\x00`\\x00`\\x00\\x00\")\n            assert im.applist[1] == (\n                \"COM\",\n                b\"File written by Adobe Photoshop\\xa8 4.0\\x00\",\n            )\n            assert len(im.applist) == 2\n\n            assert im.info[\"comment\"] == b\"File written by Adobe Photoshop\\xa8 4.0\\x00\"\n\n    def test_cmyk(self):\n        # Test CMYK handling.  Thanks to Tim and Charlie for test data,\n        # Michael for getting me to look one more time.\n        f = \"Tests/images/pil_sample_cmyk.jpg\"\n        with Image.open(f) as im:\n            # the source image has red pixels in the upper left corner.\n            c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))]\n            assert c == 0.0\n            assert m > 0.8\n            assert y > 0.8\n            assert k == 0.0\n            # the opposite corner is black\n            c, m, y, k = [\n                x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1))\n            ]\n            assert k > 0.9\n            # roundtrip, and check again\n            im = self.roundtrip(im)\n            c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))]\n            assert c == 0.0\n            assert m > 0.8\n            assert y > 0.8\n            assert k == 0.0\n            c, m, y, k = [\n                x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1))\n            ]\n            assert k > 0.9\n\n    def test_dpi(self):\n        def test(xdpi, ydpi=None):\n            with Image.open(TEST_FILE) as im:\n                im = self.roundtrip(im, dpi=(xdpi, ydpi or xdpi))\n            return im.info.get(\"dpi\")\n\n        assert test(72) == (72, 72)\n        assert test(300) == (300, 300)\n        assert test(100, 200) == (100, 200)\n        assert test(0) is None  # square pixels\n\n    def test_icc(self, tmp_path):\n        # Test ICC support\n        with Image.open(\"Tests/images/rgb.jpg\") as im1:\n            icc_profile = im1.info[\"icc_profile\"]\n            assert len(icc_profile) == 3144\n            # Roundtrip via physical file.\n            f = str(tmp_path / \"temp.jpg\")\n            im1.save(f, icc_profile=icc_profile)\n        with Image.open(f) as im2:\n            assert im2.info.get(\"icc_profile\") == icc_profile\n            # Roundtrip via memory buffer.\n            im1 = self.roundtrip(hopper())\n            im2 = self.roundtrip(hopper(), icc_profile=icc_profile)\n            assert_image_equal(im1, im2)\n            assert not im1.info.get(\"icc_profile\")\n            assert im2.info.get(\"icc_profile\")\n\n    def test_icc_big(self):\n        # Make sure that the \"extra\" support handles large blocks\n        def test(n):\n            # The ICC APP marker can store 65519 bytes per marker, so\n            # using a 4-byte test code should allow us to detect out of\n            # order issues.\n            icc_profile = (b\"Test\" * int(n / 4 + 1))[:n]\n            assert len(icc_profile) == n  # sanity\n            im1 = self.roundtrip(hopper(), icc_profile=icc_profile)\n            assert im1.info.get(\"icc_profile\") == (icc_profile or None)\n\n        test(0)\n        test(1)\n        test(3)\n        test(4)\n        test(5)\n        test(65533 - 14)  # full JPEG marker block\n        test(65533 - 14 + 1)  # full block plus one byte\n        test(ImageFile.MAXBLOCK)  # full buffer block\n        test(ImageFile.MAXBLOCK + 1)  # full buffer block plus one byte\n        test(ImageFile.MAXBLOCK * 4 + 3)  # large block\n\n    def test_large_icc_meta(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        # Sometimes the meta data on the icc_profile block is bigger than\n        # Image.MAXBLOCK or the image size.\n        with Image.open(\"Tests/images/icc_profile_big.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            icc_profile = im.info[\"icc_profile\"]\n            # Should not raise OSError for image with icc larger than image size.\n            im.save(\n                f,\n                format=\"JPEG\",\n                progressive=True,\n                quality=95,\n                icc_profile=icc_profile,\n                optimize=True,\n            )\n\n    def test_optimize(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), optimize=0)\n        im3 = self.roundtrip(hopper(), optimize=1)\n        assert_image_equal(im1, im2)\n        assert_image_equal(im1, im3)\n        assert im1.bytes >= im2.bytes\n        assert im1.bytes >= im3.bytes\n\n    def test_optimize_large_buffer(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        f = str(tmp_path / \"temp.jpg\")\n        # this requires ~ 1.5x Image.MAXBLOCK\n        im = Image.new(\"RGB\", (4096, 4096), 0xFF3333)\n        im.save(f, format=\"JPEG\", optimize=True)\n\n    def test_progressive(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), progressive=False)\n        im3 = self.roundtrip(hopper(), progressive=True)\n        assert not im1.info.get(\"progressive\")\n        assert not im2.info.get(\"progressive\")\n        assert im3.info.get(\"progressive\")\n\n        assert_image_equal(im1, im3)\n        assert im1.bytes >= im3.bytes\n\n    def test_progressive_large_buffer(self, tmp_path):\n        f = str(tmp_path / \"temp.jpg\")\n        # this requires ~ 1.5x Image.MAXBLOCK\n        im = Image.new(\"RGB\", (4096, 4096), 0xFF3333)\n        im.save(f, format=\"JPEG\", progressive=True)\n\n    def test_progressive_large_buffer_highest_quality(self, tmp_path):\n        f = str(tmp_path / \"temp.jpg\")\n        im = self.gen_random_image((255, 255))\n        # this requires more bytes than pixels in the image\n        im.save(f, format=\"JPEG\", progressive=True, quality=100)\n\n    def test_progressive_cmyk_buffer(self):\n        # Issue 2272, quality 90 cmyk image is tripping the large buffer bug.\n        f = BytesIO()\n        im = self.gen_random_image((256, 256), \"CMYK\")\n        im.save(f, format=\"JPEG\", progressive=True, quality=94)\n\n    def test_large_exif(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        f = str(tmp_path / \"temp.jpg\")\n        im = hopper()\n        im.save(f, \"JPEG\", quality=90, exif=b\"1\" * 65532)\n\n    def test_exif_typeerror(self):\n        with Image.open(\"Tests/images/exif_typeerror.jpg\") as im:\n            # Should not raise a TypeError\n            im._getexif()\n\n    def test_exif_gps(self):\n        # Arrange\n        with Image.open(\"Tests/images/exif_gps.jpg\") as im:\n            gps_index = 34853\n            expected_exif_gps = {\n                0: b\"\\x00\\x00\\x00\\x01\",\n                2: (4294967295, 1),\n                5: b\"\\x01\",\n                30: 65535,\n                29: \"1999:99:99 99:99:99\",\n            }\n\n            # Act\n            exif = im._getexif()\n\n        # Assert\n        assert exif[gps_index] == expected_exif_gps\n\n    def test_exif_rollback(self):\n        # rolling back exif support in 3.1 to pre-3.0 formatting.\n        # expected from 2.9, with b/u qualifiers switched for 3.2 compatibility\n        # this test passes on 2.9 and 3.1, but not 3.0\n        expected_exif = {\n            34867: 4294967295,\n            258: (24, 24, 24),\n            36867: \"2099:09:29 10:10:10\",\n            34853: {\n                0: b\"\\x00\\x00\\x00\\x01\",\n                2: (4294967295, 1),\n                5: b\"\\x01\",\n                30: 65535,\n                29: \"1999:99:99 99:99:99\",\n            },\n            296: 65535,\n            34665: 185,\n            41994: 65535,\n            514: 4294967295,\n            271: \"Make\",\n            272: \"XXX-XXX\",\n            305: \"PIL\",\n            42034: ((1, 1), (1, 1), (1, 1), (1, 1)),\n            42035: \"LensMake\",\n            34856: b\"\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa\",\n            282: (4294967295, 1),\n            33434: (4294967295, 1),\n        }\n\n        with Image.open(\"Tests/images/exif_gps.jpg\") as im:\n            exif = im._getexif()\n\n        for tag, value in expected_exif.items():\n            assert value == exif[tag]\n\n    def test_exif_gps_typeerror(self):\n        with Image.open(\"Tests/images/exif_gps_typeerror.jpg\") as im:\n\n            # Should not raise a TypeError\n            im._getexif()\n\n    def test_progressive_compat(self):\n        im1 = self.roundtrip(hopper())\n        assert not im1.info.get(\"progressive\")\n        assert not im1.info.get(\"progression\")\n\n        im2 = self.roundtrip(hopper(), progressive=0)\n        im3 = self.roundtrip(hopper(), progression=0)  # compatibility\n        assert not im2.info.get(\"progressive\")\n        assert not im2.info.get(\"progression\")\n        assert not im3.info.get(\"progressive\")\n        assert not im3.info.get(\"progression\")\n\n        im2 = self.roundtrip(hopper(), progressive=1)\n        im3 = self.roundtrip(hopper(), progression=1)  # compatibility\n        assert_image_equal(im1, im2)\n        assert_image_equal(im1, im3)\n        assert im2.info.get(\"progressive\")\n        assert im2.info.get(\"progression\")\n        assert im3.info.get(\"progressive\")\n        assert im3.info.get(\"progression\")\n\n    def test_quality(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), quality=50)\n        assert_image(im1, im2.mode, im2.size)\n        assert im1.bytes >= im2.bytes\n\n        im3 = self.roundtrip(hopper(), quality=0)\n        assert_image(im1, im3.mode, im3.size)\n        assert im2.bytes > im3.bytes\n\n    def test_smooth(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), smooth=100)\n        assert_image(im1, im2.mode, im2.size)\n\n    def test_subsampling(self):\n        def getsampling(im):\n            layer = im.layer\n            return layer[0][1:3] + layer[1][1:3] + layer[2][1:3]\n\n        # experimental API\n        im = self.roundtrip(hopper(), subsampling=-1)  # default\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=0)  # 4:4:4\n        assert getsampling(im) == (1, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=1)  # 4:2:2\n        assert getsampling(im) == (2, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=2)  # 4:2:0\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=3)  # default (undefined)\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n\n        im = self.roundtrip(hopper(), subsampling=\"4:4:4\")\n        assert getsampling(im) == (1, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:2:2\")\n        assert getsampling(im) == (2, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:2:0\")\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:1:1\")\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n\n        with pytest.raises(TypeError):\n            self.roundtrip(hopper(), subsampling=\"1:1:1\")\n\n    def test_exif(self):\n        with Image.open(\"Tests/images/pil_sample_rgb.jpg\") as im:\n            info = im._getexif()\n            assert info[305] == \"Adobe Photoshop CS Macintosh\"\n\n    def test_mp(self):\n        with Image.open(\"Tests/images/pil_sample_rgb.jpg\") as im:\n            assert im._getmp() is None\n\n    def test_quality_keep(self, tmp_path):\n        # RGB\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n        # Grayscale\n        with Image.open(\"Tests/images/hopper_gray.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n        # CMYK\n        with Image.open(\"Tests/images/pil_sample_cmyk.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n\n    def test_junk_jpeg_header(self):\n        # https://github.com/python-pillow/Pillow/issues/630\n        filename = \"Tests/images/junk_jpeg_header.jpg\"\n        with Image.open(filename):\n            pass\n\n    def test_ff00_jpeg_header(self):\n        filename = \"Tests/images/jpeg_ff00_header.jpg\"\n        with Image.open(filename):\n            pass\n\n    def test_truncated_jpeg_should_read_all_the_data(self):\n        filename = \"Tests/images/truncated_jpeg.jpg\"\n        ImageFile.LOAD_TRUNCATED_IMAGES = True\n        with Image.open(filename) as im:\n            im.load()\n            ImageFile.LOAD_TRUNCATED_IMAGES = False\n            assert im.getbbox() is not None\n\n    def test_truncated_jpeg_throws_oserror(self):\n        filename = \"Tests/images/truncated_jpeg.jpg\"\n        with Image.open(filename) as im:\n            with pytest.raises(OSError):\n                im.load()\n\n            # Test that the error is raised if loaded a second time\n            with pytest.raises(OSError):\n                im.load()\n\n    def test_qtables(self, tmp_path):\n        def _n_qtables_helper(n, test_file):\n            with Image.open(test_file) as im:\n                f = str(tmp_path / \"temp.jpg\")\n                im.save(f, qtables=[[n] * 64] * n)\n            with Image.open(f) as im:\n                assert len(im.quantization) == n\n                reloaded = self.roundtrip(im, qtables=\"keep\")\n                assert im.quantization == reloaded.quantization\n\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            qtables = im.quantization\n            reloaded = self.roundtrip(im, qtables=qtables, subsampling=0)\n            assert im.quantization == reloaded.quantization\n            assert_image_similar(im, self.roundtrip(im, qtables=\"web_low\"), 30)\n            assert_image_similar(im, self.roundtrip(im, qtables=\"web_high\"), 30)\n            assert_image_similar(im, self.roundtrip(im, qtables=\"keep\"), 30)\n\n            # valid bounds for baseline qtable\n            bounds_qtable = [int(s) for s in (\"255 1 \" * 32).split(None)]\n            self.roundtrip(im, qtables=[bounds_qtable])\n\n            # values from wizard.txt in jpeg9-a src package.\n            standard_l_qtable = [\n                int(s)\n                for s in \"\"\"\n                16  11  10  16  24  40  51  61\n                12  12  14  19  26  58  60  55\n                14  13  16  24  40  57  69  56\n                14  17  22  29  51  87  80  62\n                18  22  37  56  68 109 103  77\n                24  35  55  64  81 104 113  92\n                49  64  78  87 103 121 120 101\n                72  92  95  98 112 100 103  99\n                \"\"\".split(\n                    None\n                )\n            ]\n\n            standard_chrominance_qtable = [\n                int(s)\n                for s in \"\"\"\n                17  18  24  47  99  99  99  99\n                18  21  26  66  99  99  99  99\n                24  26  56  99  99  99  99  99\n                47  66  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                \"\"\".split(\n                    None\n                )\n            ]\n            # list of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables=[standard_l_qtable, standard_chrominance_qtable]\n                ),\n                30,\n            )\n\n            # tuple of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables=(standard_l_qtable, standard_chrominance_qtable)\n                ),\n                30,\n            )\n\n            # dict of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables={0: standard_l_qtable, 1: standard_chrominance_qtable}\n                ),\n                30,\n            )\n\n            _n_qtables_helper(1, \"Tests/images/hopper_gray.jpg\")\n            _n_qtables_helper(1, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(2, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(3, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(1, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(2, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(3, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(4, \"Tests/images/pil_sample_cmyk.jpg\")\n\n            # not a sequence\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=\"a\")\n            # sequence wrong length\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[])\n            # sequence wrong length\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[1, 2, 3, 4, 5])\n\n            # qtable entry not a sequence\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[1])\n            # qtable entry has wrong number of items\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[[1, 2, 3, 4]])\n\n    @pytest.mark.skipif(not djpeg_available(), reason=\"djpeg not available\")\n    def test_load_djpeg(self):\n        with Image.open(TEST_FILE) as img:\n            img.load_djpeg()\n            assert_image_similar(img, Image.open(TEST_FILE), 5)\n\n    @pytest.mark.skipif(not cjpeg_available(), reason=\"cjpeg not available\")\n    def test_save_cjpeg(self, tmp_path):\n        with Image.open(TEST_FILE) as img:\n            tempfile = str(tmp_path / \"temp.jpg\")\n            JpegImagePlugin._save_cjpeg(img, 0, tempfile)\n            # Default save quality is 75%, so a tiny bit of difference is alright\n            assert_image_similar(img, Image.open(tempfile), 17)\n\n    def test_no_duplicate_0x1001_tag(self):\n        # Arrange\n        tag_ids = {v: k for k, v in ExifTags.TAGS.items()}\n\n        # Assert\n        assert tag_ids[\"RelatedImageWidth\"] == 0x1001\n        assert tag_ids[\"RelatedImageLength\"] == 0x1002\n\n    def test_MAXBLOCK_scaling(self, tmp_path):\n        im = self.gen_random_image((512, 512))\n        f = str(tmp_path / \"temp.jpeg\")\n        im.save(f, quality=100, optimize=True)\n\n        with Image.open(f) as reloaded:\n            # none of these should crash\n            reloaded.save(f, quality=\"keep\")\n            reloaded.save(f, quality=\"keep\", progressive=True)\n            reloaded.save(f, quality=\"keep\", optimize=True)\n\n    def test_bad_mpo_header(self):\n        \"\"\" Treat unknown MPO as JPEG \"\"\"\n        # Arrange\n\n        # Act\n        # Shouldn't raise error\n        fn = \"Tests/images/sugarshack_bad_mpo_header.jpg\"\n        with pytest.warns(UserWarning, Image.open, fn) as im:\n\n            # Assert\n            assert im.format == \"JPEG\"\n\n    def test_save_correct_modes(self):\n        out = BytesIO()\n        for mode in [\"1\", \"L\", \"RGB\", \"RGBX\", \"CMYK\", \"YCbCr\"]:\n            img = Image.new(mode, (20, 20))\n            img.save(out, \"JPEG\")\n\n    def test_save_wrong_modes(self):\n        # ref https://github.com/python-pillow/Pillow/issues/2005\n        out = BytesIO()\n        for mode in [\"LA\", \"La\", \"RGBA\", \"RGBa\", \"P\"]:\n            img = Image.new(mode, (20, 20))\n            with pytest.raises(OSError):\n                img.save(out, \"JPEG\")\n\n    def test_save_tiff_with_dpi(self, tmp_path):\n        # Arrange\n        outfile = str(tmp_path / \"temp.tif\")\n        with Image.open(\"Tests/images/hopper.tif\") as im:\n\n            # Act\n            im.save(outfile, \"JPEG\", dpi=im.info[\"dpi\"])\n\n            # Assert\n            with Image.open(outfile) as reloaded:\n                reloaded.load()\n                assert im.info[\"dpi\"] == reloaded.info[\"dpi\"]\n\n    def test_load_dpi_rounding(self):\n        # Round up\n        with Image.open(\"Tests/images/iptc_roundUp.jpg\") as im:\n            assert im.info[\"dpi\"] == (44, 44)\n\n        # Round down\n        with Image.open(\"Tests/images/iptc_roundDown.jpg\") as im:\n            assert im.info[\"dpi\"] == (2, 2)\n\n    def test_save_dpi_rounding(self, tmp_path):\n        outfile = str(tmp_path / \"temp.jpg\")\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            im.save(outfile, dpi=(72.2, 72.2))\n\n            with Image.open(outfile) as reloaded:\n                assert reloaded.info[\"dpi\"] == (72, 72)\n\n            im.save(outfile, dpi=(72.8, 72.8))\n\n        with Image.open(outfile) as reloaded:\n            assert reloaded.info[\"dpi\"] == (73, 73)\n\n    def test_dpi_tuple_from_exif(self):\n        # Arrange\n        # This Photoshop CC 2017 image has DPI in EXIF not metadata\n        # EXIF XResolution is (2000000, 10000)\n        with Image.open(\"Tests/images/photoshop-200dpi.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (200, 200)\n\n    def test_dpi_int_from_exif(self):\n        # Arrange\n        # This image has DPI in EXIF not metadata\n        # EXIF XResolution is 72\n        with Image.open(\"Tests/images/exif-72dpi-int.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_dpi_from_dpcm_exif(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with EXIF resolution unit set to cm:\n        # exiftool -exif:ResolutionUnit=cm photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/exif-200dpcm.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (508, 508)\n\n    def test_dpi_exif_zero_division(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with EXIF resolution set to 0/0:\n        # exiftool -XResolution=0/0 -YResolution=0/0 photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/exif-dpi-zerodivision.jpg\") as im:\n\n            # Act / Assert\n            # This should return the default, and not raise a ZeroDivisionError\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_no_dpi_in_exif(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with resolution removed from EXIF:\n        # exiftool \"-*resolution*\"= photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/no-dpi-in-exif.jpg\") as im:\n\n            # Act / Assert\n            # \"When the image resolution is unknown, 72 [dpi] is designated.\"\n            # http://www.exiv2.org/tags.html\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_invalid_exif(self):\n        # This is no-dpi-in-exif with the tiff header of the exif block\n        # hexedited from MM * to FF FF FF FF\n        with Image.open(\"Tests/images/invalid-exif.jpg\") as im:\n\n            # This should return the default, and not a SyntaxError or\n            # OSError for unidentified image.\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_invalid_exif_x_resolution(self):\n        # When no x or y resolution is defined in EXIF\n        with Image.open(\"Tests/images/invalid-exif-without-x-resolution.jpg\") as im:\n\n            # This should return the default, and not a ValueError or\n            # OSError for an unidentified image.\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_ifd_offset_exif(self):\n        # Arrange\n        # This image has been manually hexedited to have an IFD offset of 10,\n        # in contrast to normal 8\n        with Image.open(\"Tests/images/exif-ifd-offset.jpg\") as im:\n\n            # Act / Assert\n            assert im._getexif()[306] == \"2017:03:13 23:03:09\"\n\n    def test_photoshop(self):\n        with Image.open(\"Tests/images/photoshop-200dpi.jpg\") as im:\n            assert im.info[\"photoshop\"][0x03ED] == {\n                \"XResolution\": 200.0,\n                \"DisplayedUnitsX\": 1,\n                \"YResolution\": 200.0,\n                \"DisplayedUnitsY\": 1,\n            }\n\n            # Test that the image can still load, even with broken Photoshop data\n            # This image had the APP13 length hexedited to be smaller\n            with Image.open(\"Tests/images/photoshop-200dpi-broken.jpg\") as im_broken:\n                assert_image_equal(im_broken, im)\n\n        # This image does not contain a Photoshop header string\n        with Image.open(\"Tests/images/app13.jpg\") as im:\n            assert \"photoshop\" not in im.info\n\n    def test_photoshop_malformed_and_multiple(self):\n        with Image.open(\"Tests/images/app13-multiple.jpg\") as im:\n            assert \"photoshop\" in im.info\n            assert 24 == len(im.info[\"photoshop\"])\n            apps_13_lengths = [len(v) for k, v in im.applist if k == \"APP13\"]\n            assert [65504, 24] == apps_13_lengths\n\n    def test_icc_after_SOF(self):\n        with Image.open(\"Tests/images/icc-after-SOF.jpg\") as im:\n            assert im.info[\"icc_profile\"] == b\"profile\"\n\n\n@pytest.mark.skipif(not is_win32(), reason=\"Windows only\")\n@skip_unless_feature(\"jpg\")\nclass TestFileCloseW32:\n    def test_fd_leak(self, tmp_path):\n        tmpfile = str(tmp_path / \"temp.jpg\")\n\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            im.save(tmpfile)\n\n        im = Image.open(tmpfile)\n        fp = im.fp\n        assert not fp.closed\n        with pytest.raises(OSError):\n            os.remove(tmpfile)\n        im.load()\n        assert fp.closed\n        # this should not fail, as load should have closed the file.\n        os.remove(tmpfile)\n",
            "new_file_content": "import os\nimport re\nfrom io import BytesIO\n\nimport pytest\nfrom PIL import ExifTags, Image, ImageFile, JpegImagePlugin\n\nfrom .helper import (\n    assert_image,\n    assert_image_equal,\n    assert_image_similar,\n    cjpeg_available,\n    djpeg_available,\n    hopper,\n    is_win32,\n    skip_unless_feature,\n)\n\nTEST_FILE = \"Tests/images/hopper.jpg\"\n\n\n@skip_unless_feature(\"jpg\")\nclass TestFileJpeg:\n    def roundtrip(self, im, **options):\n        out = BytesIO()\n        im.save(out, \"JPEG\", **options)\n        test_bytes = out.tell()\n        out.seek(0)\n        im = Image.open(out)\n        im.bytes = test_bytes  # for testing only\n        return im\n\n    def gen_random_image(self, size, mode=\"RGB\"):\n        \"\"\" Generates a very hard to compress file\n        :param size: tuple\n        :param mode: optional image mode\n\n        \"\"\"\n        return Image.frombytes(mode, size, os.urandom(size[0] * size[1] * len(mode)))\n\n    def test_sanity(self):\n\n        # internal version number\n        assert re.search(r\"\\d+\\.\\d+$\", Image.core.jpeglib_version)\n\n        with Image.open(TEST_FILE) as im:\n            im.load()\n            assert im.mode == \"RGB\"\n            assert im.size == (128, 128)\n            assert im.format == \"JPEG\"\n            assert im.get_format_mimetype() == \"image/jpeg\"\n\n    def test_app(self):\n        # Test APP/COM reader (@PIL135)\n        with Image.open(TEST_FILE) as im:\n            assert im.applist[0] == (\"APP0\", b\"JFIF\\x00\\x01\\x01\\x01\\x00`\\x00`\\x00\\x00\")\n            assert im.applist[1] == (\n                \"COM\",\n                b\"File written by Adobe Photoshop\\xa8 4.0\\x00\",\n            )\n            assert len(im.applist) == 2\n\n            assert im.info[\"comment\"] == b\"File written by Adobe Photoshop\\xa8 4.0\\x00\"\n\n    def test_cmyk(self):\n        # Test CMYK handling.  Thanks to Tim and Charlie for test data,\n        # Michael for getting me to look one more time.\n        f = \"Tests/images/pil_sample_cmyk.jpg\"\n        with Image.open(f) as im:\n            # the source image has red pixels in the upper left corner.\n            c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))]\n            assert c == 0.0\n            assert m > 0.8\n            assert y > 0.8\n            assert k == 0.0\n            # the opposite corner is black\n            c, m, y, k = [\n                x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1))\n            ]\n            assert k > 0.9\n            # roundtrip, and check again\n            im = self.roundtrip(im)\n            c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))]\n            assert c == 0.0\n            assert m > 0.8\n            assert y > 0.8\n            assert k == 0.0\n            c, m, y, k = [\n                x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1))\n            ]\n            assert k > 0.9\n\n    def test_dpi(self):\n        def test(xdpi, ydpi=None):\n            with Image.open(TEST_FILE) as im:\n                im = self.roundtrip(im, dpi=(xdpi, ydpi or xdpi))\n            return im.info.get(\"dpi\")\n\n        assert test(72) == (72, 72)\n        assert test(300) == (300, 300)\n        assert test(100, 200) == (100, 200)\n        assert test(0) is None  # square pixels\n\n    def test_icc(self, tmp_path):\n        # Test ICC support\n        with Image.open(\"Tests/images/rgb.jpg\") as im1:\n            icc_profile = im1.info[\"icc_profile\"]\n            assert len(icc_profile) == 3144\n            # Roundtrip via physical file.\n            f = str(tmp_path / \"temp.jpg\")\n            im1.save(f, icc_profile=icc_profile)\n        with Image.open(f) as im2:\n            assert im2.info.get(\"icc_profile\") == icc_profile\n            # Roundtrip via memory buffer.\n            im1 = self.roundtrip(hopper())\n            im2 = self.roundtrip(hopper(), icc_profile=icc_profile)\n            assert_image_equal(im1, im2)\n            assert not im1.info.get(\"icc_profile\")\n            assert im2.info.get(\"icc_profile\")\n\n    def test_icc_big(self):\n        # Make sure that the \"extra\" support handles large blocks\n        def test(n):\n            # The ICC APP marker can store 65519 bytes per marker, so\n            # using a 4-byte test code should allow us to detect out of\n            # order issues.\n            icc_profile = (b\"Test\" * int(n / 4 + 1))[:n]\n            assert len(icc_profile) == n  # sanity\n            im1 = self.roundtrip(hopper(), icc_profile=icc_profile)\n            assert im1.info.get(\"icc_profile\") == (icc_profile or None)\n\n        test(0)\n        test(1)\n        test(3)\n        test(4)\n        test(5)\n        test(65533 - 14)  # full JPEG marker block\n        test(65533 - 14 + 1)  # full block plus one byte\n        test(ImageFile.MAXBLOCK)  # full buffer block\n        test(ImageFile.MAXBLOCK + 1)  # full buffer block plus one byte\n        test(ImageFile.MAXBLOCK * 4 + 3)  # large block\n\n    def test_large_icc_meta(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        # Sometimes the meta data on the icc_profile block is bigger than\n        # Image.MAXBLOCK or the image size.\n        with Image.open(\"Tests/images/icc_profile_big.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            icc_profile = im.info[\"icc_profile\"]\n            # Should not raise OSError for image with icc larger than image size.\n            im.save(\n                f,\n                format=\"JPEG\",\n                progressive=True,\n                quality=95,\n                icc_profile=icc_profile,\n                optimize=True,\n            )\n\n    def test_optimize(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), optimize=0)\n        im3 = self.roundtrip(hopper(), optimize=1)\n        assert_image_equal(im1, im2)\n        assert_image_equal(im1, im3)\n        assert im1.bytes >= im2.bytes\n        assert im1.bytes >= im3.bytes\n\n    def test_optimize_large_buffer(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        f = str(tmp_path / \"temp.jpg\")\n        # this requires ~ 1.5x Image.MAXBLOCK\n        im = Image.new(\"RGB\", (4096, 4096), 0xFF3333)\n        im.save(f, format=\"JPEG\", optimize=True)\n\n    def test_progressive(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), progressive=False)\n        im3 = self.roundtrip(hopper(), progressive=True)\n        assert not im1.info.get(\"progressive\")\n        assert not im2.info.get(\"progressive\")\n        assert im3.info.get(\"progressive\")\n\n        assert_image_equal(im1, im3)\n        assert im1.bytes >= im3.bytes\n\n    def test_progressive_large_buffer(self, tmp_path):\n        f = str(tmp_path / \"temp.jpg\")\n        # this requires ~ 1.5x Image.MAXBLOCK\n        im = Image.new(\"RGB\", (4096, 4096), 0xFF3333)\n        im.save(f, format=\"JPEG\", progressive=True)\n\n    def test_progressive_large_buffer_highest_quality(self, tmp_path):\n        f = str(tmp_path / \"temp.jpg\")\n        im = self.gen_random_image((255, 255))\n        # this requires more bytes than pixels in the image\n        im.save(f, format=\"JPEG\", progressive=True, quality=100)\n\n    def test_progressive_cmyk_buffer(self):\n        # Issue 2272, quality 90 cmyk image is tripping the large buffer bug.\n        f = BytesIO()\n        im = self.gen_random_image((256, 256), \"CMYK\")\n        im.save(f, format=\"JPEG\", progressive=True, quality=94)\n\n    def test_large_exif(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        f = str(tmp_path / \"temp.jpg\")\n        im = hopper()\n        im.save(f, \"JPEG\", quality=90, exif=b\"1\" * 65532)\n\n    def test_exif_typeerror(self):\n        with Image.open(\"Tests/images/exif_typeerror.jpg\") as im:\n            # Should not raise a TypeError\n            im._getexif()\n\n    def test_exif_gps(self):\n        # Arrange\n        with Image.open(\"Tests/images/exif_gps.jpg\") as im:\n            gps_index = 34853\n            expected_exif_gps = {\n                0: b\"\\x00\\x00\\x00\\x01\",\n                2: 4294967295,\n                5: b\"\\x01\",\n                30: 65535,\n                29: \"1999:99:99 99:99:99\",\n            }\n\n            # Act\n            exif = im._getexif()\n\n        # Assert\n        assert exif[gps_index] == expected_exif_gps\n\n    def test_exif_rollback(self):\n        # rolling back exif support in 3.1 to pre-3.0 formatting.\n        # expected from 2.9, with b/u qualifiers switched for 3.2 compatibility\n        # this test passes on 2.9 and 3.1, but not 3.0\n        expected_exif = {\n            34867: 4294967295,\n            258: (24, 24, 24),\n            36867: \"2099:09:29 10:10:10\",\n            34853: {\n                0: b\"\\x00\\x00\\x00\\x01\",\n                2: 4294967295,\n                5: b\"\\x01\",\n                30: 65535,\n                29: \"1999:99:99 99:99:99\",\n            },\n            296: 65535,\n            34665: 185,\n            41994: 65535,\n            514: 4294967295,\n            271: \"Make\",\n            272: \"XXX-XXX\",\n            305: \"PIL\",\n            42034: (1, 1, 1, 1),\n            42035: \"LensMake\",\n            34856: b\"\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa\",\n            282: 4294967295,\n            33434: 4294967295,\n        }\n\n        with Image.open(\"Tests/images/exif_gps.jpg\") as im:\n            exif = im._getexif()\n\n        for tag, value in expected_exif.items():\n            assert value == exif[tag]\n\n    def test_exif_gps_typeerror(self):\n        with Image.open(\"Tests/images/exif_gps_typeerror.jpg\") as im:\n\n            # Should not raise a TypeError\n            im._getexif()\n\n    def test_progressive_compat(self):\n        im1 = self.roundtrip(hopper())\n        assert not im1.info.get(\"progressive\")\n        assert not im1.info.get(\"progression\")\n\n        im2 = self.roundtrip(hopper(), progressive=0)\n        im3 = self.roundtrip(hopper(), progression=0)  # compatibility\n        assert not im2.info.get(\"progressive\")\n        assert not im2.info.get(\"progression\")\n        assert not im3.info.get(\"progressive\")\n        assert not im3.info.get(\"progression\")\n\n        im2 = self.roundtrip(hopper(), progressive=1)\n        im3 = self.roundtrip(hopper(), progression=1)  # compatibility\n        assert_image_equal(im1, im2)\n        assert_image_equal(im1, im3)\n        assert im2.info.get(\"progressive\")\n        assert im2.info.get(\"progression\")\n        assert im3.info.get(\"progressive\")\n        assert im3.info.get(\"progression\")\n\n    def test_quality(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), quality=50)\n        assert_image(im1, im2.mode, im2.size)\n        assert im1.bytes >= im2.bytes\n\n        im3 = self.roundtrip(hopper(), quality=0)\n        assert_image(im1, im3.mode, im3.size)\n        assert im2.bytes > im3.bytes\n\n    def test_smooth(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), smooth=100)\n        assert_image(im1, im2.mode, im2.size)\n\n    def test_subsampling(self):\n        def getsampling(im):\n            layer = im.layer\n            return layer[0][1:3] + layer[1][1:3] + layer[2][1:3]\n\n        # experimental API\n        im = self.roundtrip(hopper(), subsampling=-1)  # default\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=0)  # 4:4:4\n        assert getsampling(im) == (1, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=1)  # 4:2:2\n        assert getsampling(im) == (2, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=2)  # 4:2:0\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=3)  # default (undefined)\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n\n        im = self.roundtrip(hopper(), subsampling=\"4:4:4\")\n        assert getsampling(im) == (1, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:2:2\")\n        assert getsampling(im) == (2, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:2:0\")\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:1:1\")\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n\n        with pytest.raises(TypeError):\n            self.roundtrip(hopper(), subsampling=\"1:1:1\")\n\n    def test_exif(self):\n        with Image.open(\"Tests/images/pil_sample_rgb.jpg\") as im:\n            info = im._getexif()\n            assert info[305] == \"Adobe Photoshop CS Macintosh\"\n\n    def test_mp(self):\n        with Image.open(\"Tests/images/pil_sample_rgb.jpg\") as im:\n            assert im._getmp() is None\n\n    def test_quality_keep(self, tmp_path):\n        # RGB\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n        # Grayscale\n        with Image.open(\"Tests/images/hopper_gray.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n        # CMYK\n        with Image.open(\"Tests/images/pil_sample_cmyk.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n\n    def test_junk_jpeg_header(self):\n        # https://github.com/python-pillow/Pillow/issues/630\n        filename = \"Tests/images/junk_jpeg_header.jpg\"\n        with Image.open(filename):\n            pass\n\n    def test_ff00_jpeg_header(self):\n        filename = \"Tests/images/jpeg_ff00_header.jpg\"\n        with Image.open(filename):\n            pass\n\n    def test_truncated_jpeg_should_read_all_the_data(self):\n        filename = \"Tests/images/truncated_jpeg.jpg\"\n        ImageFile.LOAD_TRUNCATED_IMAGES = True\n        with Image.open(filename) as im:\n            im.load()\n            ImageFile.LOAD_TRUNCATED_IMAGES = False\n            assert im.getbbox() is not None\n\n    def test_truncated_jpeg_throws_oserror(self):\n        filename = \"Tests/images/truncated_jpeg.jpg\"\n        with Image.open(filename) as im:\n            with pytest.raises(OSError):\n                im.load()\n\n            # Test that the error is raised if loaded a second time\n            with pytest.raises(OSError):\n                im.load()\n\n    def test_qtables(self, tmp_path):\n        def _n_qtables_helper(n, test_file):\n            with Image.open(test_file) as im:\n                f = str(tmp_path / \"temp.jpg\")\n                im.save(f, qtables=[[n] * 64] * n)\n            with Image.open(f) as im:\n                assert len(im.quantization) == n\n                reloaded = self.roundtrip(im, qtables=\"keep\")\n                assert im.quantization == reloaded.quantization\n\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            qtables = im.quantization\n            reloaded = self.roundtrip(im, qtables=qtables, subsampling=0)\n            assert im.quantization == reloaded.quantization\n            assert_image_similar(im, self.roundtrip(im, qtables=\"web_low\"), 30)\n            assert_image_similar(im, self.roundtrip(im, qtables=\"web_high\"), 30)\n            assert_image_similar(im, self.roundtrip(im, qtables=\"keep\"), 30)\n\n            # valid bounds for baseline qtable\n            bounds_qtable = [int(s) for s in (\"255 1 \" * 32).split(None)]\n            self.roundtrip(im, qtables=[bounds_qtable])\n\n            # values from wizard.txt in jpeg9-a src package.\n            standard_l_qtable = [\n                int(s)\n                for s in \"\"\"\n                16  11  10  16  24  40  51  61\n                12  12  14  19  26  58  60  55\n                14  13  16  24  40  57  69  56\n                14  17  22  29  51  87  80  62\n                18  22  37  56  68 109 103  77\n                24  35  55  64  81 104 113  92\n                49  64  78  87 103 121 120 101\n                72  92  95  98 112 100 103  99\n                \"\"\".split(\n                    None\n                )\n            ]\n\n            standard_chrominance_qtable = [\n                int(s)\n                for s in \"\"\"\n                17  18  24  47  99  99  99  99\n                18  21  26  66  99  99  99  99\n                24  26  56  99  99  99  99  99\n                47  66  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                \"\"\".split(\n                    None\n                )\n            ]\n            # list of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables=[standard_l_qtable, standard_chrominance_qtable]\n                ),\n                30,\n            )\n\n            # tuple of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables=(standard_l_qtable, standard_chrominance_qtable)\n                ),\n                30,\n            )\n\n            # dict of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables={0: standard_l_qtable, 1: standard_chrominance_qtable}\n                ),\n                30,\n            )\n\n            _n_qtables_helper(1, \"Tests/images/hopper_gray.jpg\")\n            _n_qtables_helper(1, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(2, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(3, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(1, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(2, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(3, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(4, \"Tests/images/pil_sample_cmyk.jpg\")\n\n            # not a sequence\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=\"a\")\n            # sequence wrong length\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[])\n            # sequence wrong length\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[1, 2, 3, 4, 5])\n\n            # qtable entry not a sequence\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[1])\n            # qtable entry has wrong number of items\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[[1, 2, 3, 4]])\n\n    @pytest.mark.skipif(not djpeg_available(), reason=\"djpeg not available\")\n    def test_load_djpeg(self):\n        with Image.open(TEST_FILE) as img:\n            img.load_djpeg()\n            assert_image_similar(img, Image.open(TEST_FILE), 5)\n\n    @pytest.mark.skipif(not cjpeg_available(), reason=\"cjpeg not available\")\n    def test_save_cjpeg(self, tmp_path):\n        with Image.open(TEST_FILE) as img:\n            tempfile = str(tmp_path / \"temp.jpg\")\n            JpegImagePlugin._save_cjpeg(img, 0, tempfile)\n            # Default save quality is 75%, so a tiny bit of difference is alright\n            assert_image_similar(img, Image.open(tempfile), 17)\n\n    def test_no_duplicate_0x1001_tag(self):\n        # Arrange\n        tag_ids = {v: k for k, v in ExifTags.TAGS.items()}\n\n        # Assert\n        assert tag_ids[\"RelatedImageWidth\"] == 0x1001\n        assert tag_ids[\"RelatedImageLength\"] == 0x1002\n\n    def test_MAXBLOCK_scaling(self, tmp_path):\n        im = self.gen_random_image((512, 512))\n        f = str(tmp_path / \"temp.jpeg\")\n        im.save(f, quality=100, optimize=True)\n\n        with Image.open(f) as reloaded:\n            # none of these should crash\n            reloaded.save(f, quality=\"keep\")\n            reloaded.save(f, quality=\"keep\", progressive=True)\n            reloaded.save(f, quality=\"keep\", optimize=True)\n\n    def test_bad_mpo_header(self):\n        \"\"\" Treat unknown MPO as JPEG \"\"\"\n        # Arrange\n\n        # Act\n        # Shouldn't raise error\n        fn = \"Tests/images/sugarshack_bad_mpo_header.jpg\"\n        with pytest.warns(UserWarning, Image.open, fn) as im:\n\n            # Assert\n            assert im.format == \"JPEG\"\n\n    def test_save_correct_modes(self):\n        out = BytesIO()\n        for mode in [\"1\", \"L\", \"RGB\", \"RGBX\", \"CMYK\", \"YCbCr\"]:\n            img = Image.new(mode, (20, 20))\n            img.save(out, \"JPEG\")\n\n    def test_save_wrong_modes(self):\n        # ref https://github.com/python-pillow/Pillow/issues/2005\n        out = BytesIO()\n        for mode in [\"LA\", \"La\", \"RGBA\", \"RGBa\", \"P\"]:\n            img = Image.new(mode, (20, 20))\n            with pytest.raises(OSError):\n                img.save(out, \"JPEG\")\n\n    def test_save_tiff_with_dpi(self, tmp_path):\n        # Arrange\n        outfile = str(tmp_path / \"temp.tif\")\n        with Image.open(\"Tests/images/hopper.tif\") as im:\n\n            # Act\n            im.save(outfile, \"JPEG\", dpi=im.info[\"dpi\"])\n\n            # Assert\n            with Image.open(outfile) as reloaded:\n                reloaded.load()\n                assert im.info[\"dpi\"] == reloaded.info[\"dpi\"]\n\n    def test_load_dpi_rounding(self):\n        # Round up\n        with Image.open(\"Tests/images/iptc_roundUp.jpg\") as im:\n            assert im.info[\"dpi\"] == (44, 44)\n\n        # Round down\n        with Image.open(\"Tests/images/iptc_roundDown.jpg\") as im:\n            assert im.info[\"dpi\"] == (2, 2)\n\n    def test_save_dpi_rounding(self, tmp_path):\n        outfile = str(tmp_path / \"temp.jpg\")\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            im.save(outfile, dpi=(72.2, 72.2))\n\n            with Image.open(outfile) as reloaded:\n                assert reloaded.info[\"dpi\"] == (72, 72)\n\n            im.save(outfile, dpi=(72.8, 72.8))\n\n        with Image.open(outfile) as reloaded:\n            assert reloaded.info[\"dpi\"] == (73, 73)\n\n    def test_dpi_tuple_from_exif(self):\n        # Arrange\n        # This Photoshop CC 2017 image has DPI in EXIF not metadata\n        # EXIF XResolution is (2000000, 10000)\n        with Image.open(\"Tests/images/photoshop-200dpi.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (200, 200)\n\n    def test_dpi_int_from_exif(self):\n        # Arrange\n        # This image has DPI in EXIF not metadata\n        # EXIF XResolution is 72\n        with Image.open(\"Tests/images/exif-72dpi-int.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_dpi_from_dpcm_exif(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with EXIF resolution unit set to cm:\n        # exiftool -exif:ResolutionUnit=cm photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/exif-200dpcm.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (508, 508)\n\n    def test_dpi_exif_zero_division(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with EXIF resolution set to 0/0:\n        # exiftool -XResolution=0/0 -YResolution=0/0 photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/exif-dpi-zerodivision.jpg\") as im:\n\n            # Act / Assert\n            # This should return the default, and not raise a ZeroDivisionError\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_no_dpi_in_exif(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with resolution removed from EXIF:\n        # exiftool \"-*resolution*\"= photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/no-dpi-in-exif.jpg\") as im:\n\n            # Act / Assert\n            # \"When the image resolution is unknown, 72 [dpi] is designated.\"\n            # http://www.exiv2.org/tags.html\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_invalid_exif(self):\n        # This is no-dpi-in-exif with the tiff header of the exif block\n        # hexedited from MM * to FF FF FF FF\n        with Image.open(\"Tests/images/invalid-exif.jpg\") as im:\n\n            # This should return the default, and not a SyntaxError or\n            # OSError for unidentified image.\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_exif_x_resolution(self, tmp_path):\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            exif = im.getexif()\n            assert exif[282] == 180\n\n            out = str(tmp_path / \"out.jpg\")\n            with pytest.warns(None) as record:\n                im.save(out, exif=exif)\n            assert len(record) == 0\n\n        with Image.open(out) as reloaded:\n            assert reloaded.getexif()[282] == 180\n\n    def test_invalid_exif_x_resolution(self):\n        # When no x or y resolution is defined in EXIF\n        with Image.open(\"Tests/images/invalid-exif-without-x-resolution.jpg\") as im:\n\n            # This should return the default, and not a ValueError or\n            # OSError for an unidentified image.\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_ifd_offset_exif(self):\n        # Arrange\n        # This image has been manually hexedited to have an IFD offset of 10,\n        # in contrast to normal 8\n        with Image.open(\"Tests/images/exif-ifd-offset.jpg\") as im:\n\n            # Act / Assert\n            assert im._getexif()[306] == \"2017:03:13 23:03:09\"\n\n    def test_photoshop(self):\n        with Image.open(\"Tests/images/photoshop-200dpi.jpg\") as im:\n            assert im.info[\"photoshop\"][0x03ED] == {\n                \"XResolution\": 200.0,\n                \"DisplayedUnitsX\": 1,\n                \"YResolution\": 200.0,\n                \"DisplayedUnitsY\": 1,\n            }\n\n            # Test that the image can still load, even with broken Photoshop data\n            # This image had the APP13 length hexedited to be smaller\n            with Image.open(\"Tests/images/photoshop-200dpi-broken.jpg\") as im_broken:\n                assert_image_equal(im_broken, im)\n\n        # This image does not contain a Photoshop header string\n        with Image.open(\"Tests/images/app13.jpg\") as im:\n            assert \"photoshop\" not in im.info\n\n    def test_photoshop_malformed_and_multiple(self):\n        with Image.open(\"Tests/images/app13-multiple.jpg\") as im:\n            assert \"photoshop\" in im.info\n            assert 24 == len(im.info[\"photoshop\"])\n            apps_13_lengths = [len(v) for k, v in im.applist if k == \"APP13\"]\n            assert [65504, 24] == apps_13_lengths\n\n    def test_icc_after_SOF(self):\n        with Image.open(\"Tests/images/icc-after-SOF.jpg\") as im:\n            assert im.info[\"icc_profile\"] == b\"profile\"\n\n\n@pytest.mark.skipif(not is_win32(), reason=\"Windows only\")\n@skip_unless_feature(\"jpg\")\nclass TestFileCloseW32:\n    def test_fd_leak(self, tmp_path):\n        tmpfile = str(tmp_path / \"temp.jpg\")\n\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            im.save(tmpfile)\n\n        im = Image.open(tmpfile)\n        fp = im.fp\n        assert not fp.closed\n        with pytest.raises(OSError):\n            os.remove(tmpfile)\n        im.load()\n        assert fp.closed\n        # this should not fail, as load should have closed the file.\n        os.remove(tmpfile)\n",
            "header": {
                "file": {
                    "path": "Tests/test_file_jpeg.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "08db11645",
                "new_commit_hash": "afca875de",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/Tests/test_file_jpeg.py"
            },
            "plus_file": {
                "path": "b/Tests/test_file_jpeg.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 219,
                            "length": 7
                        },
                        "new_range": {
                            "start": 219,
                            "length": 7
                        },
                        "section": "class TestFileJpeg:"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "            gps_index = 34853",
                                "type": "context"
                            },
                            {
                                "content": "            expected_exif_gps = {",
                                "type": "context"
                            },
                            {
                                "content": "                0: b\"\\x00\\x00\\x00\\x01\",",
                                "type": "context"
                            },
                            {
                                "content": "                2: (4294967295, 1),",
                                "type": "deleted"
                            },
                            {
                                "content": "                2: 4294967295,",
                                "type": "added"
                            },
                            {
                                "content": "                5: b\"\\x01\",",
                                "type": "context"
                            },
                            {
                                "content": "                30: 65535,",
                                "type": "context"
                            },
                            {
                                "content": "                29: \"1999:99:99 99:99:99\",",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Tests/test_file_jpeg.py",
                            "type": "class",
                            "name": "TestFileJpeg",
                            "content": "class TestFileJpeg:\n    def roundtrip(self, im, **options):\n        out = BytesIO()\n        im.save(out, \"JPEG\", **options)\n        test_bytes = out.tell()\n        out.seek(0)\n        im = Image.open(out)\n        im.bytes = test_bytes  # for testing only\n        return im\n\n    def gen_random_image(self, size, mode=\"RGB\"):\n        \"\"\" Generates a very hard to compress file\n        :param size: tuple\n        :param mode: optional image mode\n\n        \"\"\"\n        return Image.frombytes(mode, size, os.urandom(size[0] * size[1] * len(mode)))\n\n    def test_sanity(self):\n\n        # internal version number\n        assert re.search(r\"\\d+\\.\\d+$\", Image.core.jpeglib_version)\n\n        with Image.open(TEST_FILE) as im:\n            im.load()\n            assert im.mode == \"RGB\"\n            assert im.size == (128, 128)\n            assert im.format == \"JPEG\"\n            assert im.get_format_mimetype() == \"image/jpeg\"\n\n    def test_app(self):\n        # Test APP/COM reader (@PIL135)\n        with Image.open(TEST_FILE) as im:\n            assert im.applist[0] == (\"APP0\", b\"JFIF\\x00\\x01\\x01\\x01\\x00`\\x00`\\x00\\x00\")\n            assert im.applist[1] == (\n                \"COM\",\n                b\"File written by Adobe Photoshop\\xa8 4.0\\x00\",\n            )\n            assert len(im.applist) == 2\n\n            assert im.info[\"comment\"] == b\"File written by Adobe Photoshop\\xa8 4.0\\x00\"\n\n    def test_cmyk(self):\n        # Test CMYK handling.  Thanks to Tim and Charlie for test data,\n        # Michael for getting me to look one more time.\n        f = \"Tests/images/pil_sample_cmyk.jpg\"\n        with Image.open(f) as im:\n            # the source image has red pixels in the upper left corner.\n            c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))]\n            assert c == 0.0\n            assert m > 0.8\n            assert y > 0.8\n            assert k == 0.0\n            # the opposite corner is black\n            c, m, y, k = [\n                x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1))\n            ]\n            assert k > 0.9\n            # roundtrip, and check again\n            im = self.roundtrip(im)\n            c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))]\n            assert c == 0.0\n            assert m > 0.8\n            assert y > 0.8\n            assert k == 0.0\n            c, m, y, k = [\n                x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1))\n            ]\n            assert k > 0.9\n\n    def test_dpi(self):\n        def test(xdpi, ydpi=None):\n            with Image.open(TEST_FILE) as im:\n                im = self.roundtrip(im, dpi=(xdpi, ydpi or xdpi))\n            return im.info.get(\"dpi\")\n\n        assert test(72) == (72, 72)\n        assert test(300) == (300, 300)\n        assert test(100, 200) == (100, 200)\n        assert test(0) is None  # square pixels\n\n    def test_icc(self, tmp_path):\n        # Test ICC support\n        with Image.open(\"Tests/images/rgb.jpg\") as im1:\n            icc_profile = im1.info[\"icc_profile\"]\n            assert len(icc_profile) == 3144\n            # Roundtrip via physical file.\n            f = str(tmp_path / \"temp.jpg\")\n            im1.save(f, icc_profile=icc_profile)\n        with Image.open(f) as im2:\n            assert im2.info.get(\"icc_profile\") == icc_profile\n            # Roundtrip via memory buffer.\n            im1 = self.roundtrip(hopper())\n            im2 = self.roundtrip(hopper(), icc_profile=icc_profile)\n            assert_image_equal(im1, im2)\n            assert not im1.info.get(\"icc_profile\")\n            assert im2.info.get(\"icc_profile\")\n\n    def test_icc_big(self):\n        # Make sure that the \"extra\" support handles large blocks\n        def test(n):\n            # The ICC APP marker can store 65519 bytes per marker, so\n            # using a 4-byte test code should allow us to detect out of\n            # order issues.\n            icc_profile = (b\"Test\" * int(n / 4 + 1))[:n]\n            assert len(icc_profile) == n  # sanity\n            im1 = self.roundtrip(hopper(), icc_profile=icc_profile)\n            assert im1.info.get(\"icc_profile\") == (icc_profile or None)\n\n        test(0)\n        test(1)\n        test(3)\n        test(4)\n        test(5)\n        test(65533 - 14)  # full JPEG marker block\n        test(65533 - 14 + 1)  # full block plus one byte\n        test(ImageFile.MAXBLOCK)  # full buffer block\n        test(ImageFile.MAXBLOCK + 1)  # full buffer block plus one byte\n        test(ImageFile.MAXBLOCK * 4 + 3)  # large block\n\n    def test_large_icc_meta(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        # Sometimes the meta data on the icc_profile block is bigger than\n        # Image.MAXBLOCK or the image size.\n        with Image.open(\"Tests/images/icc_profile_big.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            icc_profile = im.info[\"icc_profile\"]\n            # Should not raise OSError for image with icc larger than image size.\n            im.save(\n                f,\n                format=\"JPEG\",\n                progressive=True,\n                quality=95,\n                icc_profile=icc_profile,\n                optimize=True,\n            )\n\n    def test_optimize(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), optimize=0)\n        im3 = self.roundtrip(hopper(), optimize=1)\n        assert_image_equal(im1, im2)\n        assert_image_equal(im1, im3)\n        assert im1.bytes >= im2.bytes\n        assert im1.bytes >= im3.bytes\n\n    def test_optimize_large_buffer(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        f = str(tmp_path / \"temp.jpg\")\n        # this requires ~ 1.5x Image.MAXBLOCK\n        im = Image.new(\"RGB\", (4096, 4096), 0xFF3333)\n        im.save(f, format=\"JPEG\", optimize=True)\n\n    def test_progressive(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), progressive=False)\n        im3 = self.roundtrip(hopper(), progressive=True)\n        assert not im1.info.get(\"progressive\")\n        assert not im2.info.get(\"progressive\")\n        assert im3.info.get(\"progressive\")\n\n        assert_image_equal(im1, im3)\n        assert im1.bytes >= im3.bytes\n\n    def test_progressive_large_buffer(self, tmp_path):\n        f = str(tmp_path / \"temp.jpg\")\n        # this requires ~ 1.5x Image.MAXBLOCK\n        im = Image.new(\"RGB\", (4096, 4096), 0xFF3333)\n        im.save(f, format=\"JPEG\", progressive=True)\n\n    def test_progressive_large_buffer_highest_quality(self, tmp_path):\n        f = str(tmp_path / \"temp.jpg\")\n        im = self.gen_random_image((255, 255))\n        # this requires more bytes than pixels in the image\n        im.save(f, format=\"JPEG\", progressive=True, quality=100)\n\n    def test_progressive_cmyk_buffer(self):\n        # Issue 2272, quality 90 cmyk image is tripping the large buffer bug.\n        f = BytesIO()\n        im = self.gen_random_image((256, 256), \"CMYK\")\n        im.save(f, format=\"JPEG\", progressive=True, quality=94)\n\n    def test_large_exif(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        f = str(tmp_path / \"temp.jpg\")\n        im = hopper()\n        im.save(f, \"JPEG\", quality=90, exif=b\"1\" * 65532)\n\n    def test_exif_typeerror(self):\n        with Image.open(\"Tests/images/exif_typeerror.jpg\") as im:\n            # Should not raise a TypeError\n            im._getexif()\n\n    def test_exif_gps(self):\n        # Arrange\n        with Image.open(\"Tests/images/exif_gps.jpg\") as im:\n            gps_index = 34853\n            expected_exif_gps = {\n                0: b\"\\x00\\x00\\x00\\x01\",\n                2: (4294967295, 1),\n                5: b\"\\x01\",\n                30: 65535,\n                29: \"1999:99:99 99:99:99\",\n            }\n\n            # Act\n            exif = im._getexif()\n\n        # Assert\n        assert exif[gps_index] == expected_exif_gps\n\n    def test_exif_rollback(self):\n        # rolling back exif support in 3.1 to pre-3.0 formatting.\n        # expected from 2.9, with b/u qualifiers switched for 3.2 compatibility\n        # this test passes on 2.9 and 3.1, but not 3.0\n        expected_exif = {\n            34867: 4294967295,\n            258: (24, 24, 24),\n            36867: \"2099:09:29 10:10:10\",\n            34853: {\n                0: b\"\\x00\\x00\\x00\\x01\",\n                2: (4294967295, 1),\n                5: b\"\\x01\",\n                30: 65535,\n                29: \"1999:99:99 99:99:99\",\n            },\n            296: 65535,\n            34665: 185,\n            41994: 65535,\n            514: 4294967295,\n            271: \"Make\",\n            272: \"XXX-XXX\",\n            305: \"PIL\",\n            42034: ((1, 1), (1, 1), (1, 1), (1, 1)),\n            42035: \"LensMake\",\n            34856: b\"\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa\",\n            282: (4294967295, 1),\n            33434: (4294967295, 1),\n        }\n\n        with Image.open(\"Tests/images/exif_gps.jpg\") as im:\n            exif = im._getexif()\n\n        for tag, value in expected_exif.items():\n            assert value == exif[tag]\n\n    def test_exif_gps_typeerror(self):\n        with Image.open(\"Tests/images/exif_gps_typeerror.jpg\") as im:\n\n            # Should not raise a TypeError\n            im._getexif()\n\n    def test_progressive_compat(self):\n        im1 = self.roundtrip(hopper())\n        assert not im1.info.get(\"progressive\")\n        assert not im1.info.get(\"progression\")\n\n        im2 = self.roundtrip(hopper(), progressive=0)\n        im3 = self.roundtrip(hopper(), progression=0)  # compatibility\n        assert not im2.info.get(\"progressive\")\n        assert not im2.info.get(\"progression\")\n        assert not im3.info.get(\"progressive\")\n        assert not im3.info.get(\"progression\")\n\n        im2 = self.roundtrip(hopper(), progressive=1)\n        im3 = self.roundtrip(hopper(), progression=1)  # compatibility\n        assert_image_equal(im1, im2)\n        assert_image_equal(im1, im3)\n        assert im2.info.get(\"progressive\")\n        assert im2.info.get(\"progression\")\n        assert im3.info.get(\"progressive\")\n        assert im3.info.get(\"progression\")\n\n    def test_quality(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), quality=50)\n        assert_image(im1, im2.mode, im2.size)\n        assert im1.bytes >= im2.bytes\n\n        im3 = self.roundtrip(hopper(), quality=0)\n        assert_image(im1, im3.mode, im3.size)\n        assert im2.bytes > im3.bytes\n\n    def test_smooth(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), smooth=100)\n        assert_image(im1, im2.mode, im2.size)\n\n    def test_subsampling(self):\n        def getsampling(im):\n            layer = im.layer\n            return layer[0][1:3] + layer[1][1:3] + layer[2][1:3]\n\n        # experimental API\n        im = self.roundtrip(hopper(), subsampling=-1)  # default\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=0)  # 4:4:4\n        assert getsampling(im) == (1, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=1)  # 4:2:2\n        assert getsampling(im) == (2, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=2)  # 4:2:0\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=3)  # default (undefined)\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n\n        im = self.roundtrip(hopper(), subsampling=\"4:4:4\")\n        assert getsampling(im) == (1, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:2:2\")\n        assert getsampling(im) == (2, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:2:0\")\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:1:1\")\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n\n        with pytest.raises(TypeError):\n            self.roundtrip(hopper(), subsampling=\"1:1:1\")\n\n    def test_exif(self):\n        with Image.open(\"Tests/images/pil_sample_rgb.jpg\") as im:\n            info = im._getexif()\n            assert info[305] == \"Adobe Photoshop CS Macintosh\"\n\n    def test_mp(self):\n        with Image.open(\"Tests/images/pil_sample_rgb.jpg\") as im:\n            assert im._getmp() is None\n\n    def test_quality_keep(self, tmp_path):\n        # RGB\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n        # Grayscale\n        with Image.open(\"Tests/images/hopper_gray.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n        # CMYK\n        with Image.open(\"Tests/images/pil_sample_cmyk.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n\n    def test_junk_jpeg_header(self):\n        # https://github.com/python-pillow/Pillow/issues/630\n        filename = \"Tests/images/junk_jpeg_header.jpg\"\n        with Image.open(filename):\n            pass\n\n    def test_ff00_jpeg_header(self):\n        filename = \"Tests/images/jpeg_ff00_header.jpg\"\n        with Image.open(filename):\n            pass\n\n    def test_truncated_jpeg_should_read_all_the_data(self):\n        filename = \"Tests/images/truncated_jpeg.jpg\"\n        ImageFile.LOAD_TRUNCATED_IMAGES = True\n        with Image.open(filename) as im:\n            im.load()\n            ImageFile.LOAD_TRUNCATED_IMAGES = False\n            assert im.getbbox() is not None\n\n    def test_truncated_jpeg_throws_oserror(self):\n        filename = \"Tests/images/truncated_jpeg.jpg\"\n        with Image.open(filename) as im:\n            with pytest.raises(OSError):\n                im.load()\n\n            # Test that the error is raised if loaded a second time\n            with pytest.raises(OSError):\n                im.load()\n\n    def test_qtables(self, tmp_path):\n        def _n_qtables_helper(n, test_file):\n            with Image.open(test_file) as im:\n                f = str(tmp_path / \"temp.jpg\")\n                im.save(f, qtables=[[n] * 64] * n)\n            with Image.open(f) as im:\n                assert len(im.quantization) == n\n                reloaded = self.roundtrip(im, qtables=\"keep\")\n                assert im.quantization == reloaded.quantization\n\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            qtables = im.quantization\n            reloaded = self.roundtrip(im, qtables=qtables, subsampling=0)\n            assert im.quantization == reloaded.quantization\n            assert_image_similar(im, self.roundtrip(im, qtables=\"web_low\"), 30)\n            assert_image_similar(im, self.roundtrip(im, qtables=\"web_high\"), 30)\n            assert_image_similar(im, self.roundtrip(im, qtables=\"keep\"), 30)\n\n            # valid bounds for baseline qtable\n            bounds_qtable = [int(s) for s in (\"255 1 \" * 32).split(None)]\n            self.roundtrip(im, qtables=[bounds_qtable])\n\n            # values from wizard.txt in jpeg9-a src package.\n            standard_l_qtable = [\n                int(s)\n                for s in \"\"\"\n                16  11  10  16  24  40  51  61\n                12  12  14  19  26  58  60  55\n                14  13  16  24  40  57  69  56\n                14  17  22  29  51  87  80  62\n                18  22  37  56  68 109 103  77\n                24  35  55  64  81 104 113  92\n                49  64  78  87 103 121 120 101\n                72  92  95  98 112 100 103  99\n                \"\"\".split(\n                    None\n                )\n            ]\n\n            standard_chrominance_qtable = [\n                int(s)\n                for s in \"\"\"\n                17  18  24  47  99  99  99  99\n                18  21  26  66  99  99  99  99\n                24  26  56  99  99  99  99  99\n                47  66  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                \"\"\".split(\n                    None\n                )\n            ]\n            # list of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables=[standard_l_qtable, standard_chrominance_qtable]\n                ),\n                30,\n            )\n\n            # tuple of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables=(standard_l_qtable, standard_chrominance_qtable)\n                ),\n                30,\n            )\n\n            # dict of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables={0: standard_l_qtable, 1: standard_chrominance_qtable}\n                ),\n                30,\n            )\n\n            _n_qtables_helper(1, \"Tests/images/hopper_gray.jpg\")\n            _n_qtables_helper(1, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(2, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(3, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(1, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(2, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(3, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(4, \"Tests/images/pil_sample_cmyk.jpg\")\n\n            # not a sequence\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=\"a\")\n            # sequence wrong length\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[])\n            # sequence wrong length\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[1, 2, 3, 4, 5])\n\n            # qtable entry not a sequence\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[1])\n            # qtable entry has wrong number of items\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[[1, 2, 3, 4]])\n\n    @pytest.mark.skipif(not djpeg_available(), reason=\"djpeg not available\")\n    def test_load_djpeg(self):\n        with Image.open(TEST_FILE) as img:\n            img.load_djpeg()\n            assert_image_similar(img, Image.open(TEST_FILE), 5)\n\n    @pytest.mark.skipif(not cjpeg_available(), reason=\"cjpeg not available\")\n    def test_save_cjpeg(self, tmp_path):\n        with Image.open(TEST_FILE) as img:\n            tempfile = str(tmp_path / \"temp.jpg\")\n            JpegImagePlugin._save_cjpeg(img, 0, tempfile)\n            # Default save quality is 75%, so a tiny bit of difference is alright\n            assert_image_similar(img, Image.open(tempfile), 17)\n\n    def test_no_duplicate_0x1001_tag(self):\n        # Arrange\n        tag_ids = {v: k for k, v in ExifTags.TAGS.items()}\n\n        # Assert\n        assert tag_ids[\"RelatedImageWidth\"] == 0x1001\n        assert tag_ids[\"RelatedImageLength\"] == 0x1002\n\n    def test_MAXBLOCK_scaling(self, tmp_path):\n        im = self.gen_random_image((512, 512))\n        f = str(tmp_path / \"temp.jpeg\")\n        im.save(f, quality=100, optimize=True)\n\n        with Image.open(f) as reloaded:\n            # none of these should crash\n            reloaded.save(f, quality=\"keep\")\n            reloaded.save(f, quality=\"keep\", progressive=True)\n            reloaded.save(f, quality=\"keep\", optimize=True)\n\n    def test_bad_mpo_header(self):\n        \"\"\" Treat unknown MPO as JPEG \"\"\"\n        # Arrange\n\n        # Act\n        # Shouldn't raise error\n        fn = \"Tests/images/sugarshack_bad_mpo_header.jpg\"\n        with pytest.warns(UserWarning, Image.open, fn) as im:\n\n            # Assert\n            assert im.format == \"JPEG\"\n\n    def test_save_correct_modes(self):\n        out = BytesIO()\n        for mode in [\"1\", \"L\", \"RGB\", \"RGBX\", \"CMYK\", \"YCbCr\"]:\n            img = Image.new(mode, (20, 20))\n            img.save(out, \"JPEG\")\n\n    def test_save_wrong_modes(self):\n        # ref https://github.com/python-pillow/Pillow/issues/2005\n        out = BytesIO()\n        for mode in [\"LA\", \"La\", \"RGBA\", \"RGBa\", \"P\"]:\n            img = Image.new(mode, (20, 20))\n            with pytest.raises(OSError):\n                img.save(out, \"JPEG\")\n\n    def test_save_tiff_with_dpi(self, tmp_path):\n        # Arrange\n        outfile = str(tmp_path / \"temp.tif\")\n        with Image.open(\"Tests/images/hopper.tif\") as im:\n\n            # Act\n            im.save(outfile, \"JPEG\", dpi=im.info[\"dpi\"])\n\n            # Assert\n            with Image.open(outfile) as reloaded:\n                reloaded.load()\n                assert im.info[\"dpi\"] == reloaded.info[\"dpi\"]\n\n    def test_load_dpi_rounding(self):\n        # Round up\n        with Image.open(\"Tests/images/iptc_roundUp.jpg\") as im:\n            assert im.info[\"dpi\"] == (44, 44)\n\n        # Round down\n        with Image.open(\"Tests/images/iptc_roundDown.jpg\") as im:\n            assert im.info[\"dpi\"] == (2, 2)\n\n    def test_save_dpi_rounding(self, tmp_path):\n        outfile = str(tmp_path / \"temp.jpg\")\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            im.save(outfile, dpi=(72.2, 72.2))\n\n            with Image.open(outfile) as reloaded:\n                assert reloaded.info[\"dpi\"] == (72, 72)\n\n            im.save(outfile, dpi=(72.8, 72.8))\n\n        with Image.open(outfile) as reloaded:\n            assert reloaded.info[\"dpi\"] == (73, 73)\n\n    def test_dpi_tuple_from_exif(self):\n        # Arrange\n        # This Photoshop CC 2017 image has DPI in EXIF not metadata\n        # EXIF XResolution is (2000000, 10000)\n        with Image.open(\"Tests/images/photoshop-200dpi.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (200, 200)\n\n    def test_dpi_int_from_exif(self):\n        # Arrange\n        # This image has DPI in EXIF not metadata\n        # EXIF XResolution is 72\n        with Image.open(\"Tests/images/exif-72dpi-int.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_dpi_from_dpcm_exif(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with EXIF resolution unit set to cm:\n        # exiftool -exif:ResolutionUnit=cm photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/exif-200dpcm.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (508, 508)\n\n    def test_dpi_exif_zero_division(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with EXIF resolution set to 0/0:\n        # exiftool -XResolution=0/0 -YResolution=0/0 photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/exif-dpi-zerodivision.jpg\") as im:\n\n            # Act / Assert\n            # This should return the default, and not raise a ZeroDivisionError\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_no_dpi_in_exif(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with resolution removed from EXIF:\n        # exiftool \"-*resolution*\"= photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/no-dpi-in-exif.jpg\") as im:\n\n            # Act / Assert\n            # \"When the image resolution is unknown, 72 [dpi] is designated.\"\n            # http://www.exiv2.org/tags.html\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_invalid_exif(self):\n        # This is no-dpi-in-exif with the tiff header of the exif block\n        # hexedited from MM * to FF FF FF FF\n        with Image.open(\"Tests/images/invalid-exif.jpg\") as im:\n\n            # This should return the default, and not a SyntaxError or\n            # OSError for unidentified image.\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_invalid_exif_x_resolution(self):\n        # When no x or y resolution is defined in EXIF\n        with Image.open(\"Tests/images/invalid-exif-without-x-resolution.jpg\") as im:\n\n            # This should return the default, and not a ValueError or\n            # OSError for an unidentified image.\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_ifd_offset_exif(self):\n        # Arrange\n        # This image has been manually hexedited to have an IFD offset of 10,\n        # in contrast to normal 8\n        with Image.open(\"Tests/images/exif-ifd-offset.jpg\") as im:\n\n            # Act / Assert\n            assert im._getexif()[306] == \"2017:03:13 23:03:09\"\n\n    def test_photoshop(self):\n        with Image.open(\"Tests/images/photoshop-200dpi.jpg\") as im:\n            assert im.info[\"photoshop\"][0x03ED] == {\n                \"XResolution\": 200.0,\n                \"DisplayedUnitsX\": 1,\n                \"YResolution\": 200.0,\n                \"DisplayedUnitsY\": 1,\n            }\n\n            # Test that the image can still load, even with broken Photoshop data\n            # This image had the APP13 length hexedited to be smaller\n            with Image.open(\"Tests/images/photoshop-200dpi-broken.jpg\") as im_broken:\n                assert_image_equal(im_broken, im)\n\n        # This image does not contain a Photoshop header string\n        with Image.open(\"Tests/images/app13.jpg\") as im:\n            assert \"photoshop\" not in im.info\n\n    def test_photoshop_malformed_and_multiple(self):\n        with Image.open(\"Tests/images/app13-multiple.jpg\") as im:\n            assert \"photoshop\" in im.info\n            assert 24 == len(im.info[\"photoshop\"])\n            apps_13_lengths = [len(v) for k, v in im.applist if k == \"APP13\"]\n            assert [65504, 24] == apps_13_lengths\n\n    def test_icc_after_SOF(self):\n        with Image.open(\"Tests/images/icc-after-SOF.jpg\") as im:\n            assert im.info[\"icc_profile\"] == b\"profile\"",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 23,
                            "end_lineno": 694,
                            "parent": null
                        },
                        {
                            "file_name": "Tests/test_file_jpeg.py",
                            "type": "method",
                            "name": "TestFileJpeg.test_exif_gps",
                            "content": "class TestFileJpeg:\n    def roundtrip(self, im, **options):\n        out = BytesIO()\n        im.save(out, \"JPEG\", **options)\n        test_bytes = out.tell()\n        out.seek(0)\n        im = Image.open(out)\n        im.bytes = test_bytes  # for testing only\n        return im\n\n    def gen_random_image(self, size, mode=\"RGB\"):\n        \"\"\" Generates a very hard to compress file\n        :param size: tuple\n        :param mode: optional image mode\n\n        \"\"\"\n        return Image.frombytes(mode, size, os.urandom(size[0] * size[1] * len(mode)))\n\n    def test_sanity(self):\n\n        # internal version number\n        assert re.search(r\"\\d+\\.\\d+$\", Image.core.jpeglib_version)\n\n        with Image.open(TEST_FILE) as im:\n            im.load()\n            assert im.mode == \"RGB\"\n            assert im.size == (128, 128)\n            assert im.format == \"JPEG\"\n            assert im.get_format_mimetype() == \"image/jpeg\"\n\n    def test_app(self):\n        # Test APP/COM reader (@PIL135)\n        with Image.open(TEST_FILE) as im:\n            assert im.applist[0] == (\"APP0\", b\"JFIF\\x00\\x01\\x01\\x01\\x00`\\x00`\\x00\\x00\")\n            assert im.applist[1] == (\n                \"COM\",\n                b\"File written by Adobe Photoshop\\xa8 4.0\\x00\",\n            )\n            assert len(im.applist) == 2\n\n            assert im.info[\"comment\"] == b\"File written by Adobe Photoshop\\xa8 4.0\\x00\"\n\n    def test_cmyk(self):\n        # Test CMYK handling.  Thanks to Tim and Charlie for test data,\n        # Michael for getting me to look one more time.\n        f = \"Tests/images/pil_sample_cmyk.jpg\"\n        with Image.open(f) as im:\n            # the source image has red pixels in the upper left corner.\n            c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))]\n            assert c == 0.0\n            assert m > 0.8\n            assert y > 0.8\n            assert k == 0.0\n            # the opposite corner is black\n            c, m, y, k = [\n                x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1))\n            ]\n            assert k > 0.9\n            # roundtrip, and check again\n            im = self.roundtrip(im)\n            c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))]\n            assert c == 0.0\n            assert m > 0.8\n            assert y > 0.8\n            assert k == 0.0\n            c, m, y, k = [\n                x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1))\n            ]\n            assert k > 0.9\n\n    def test_dpi(self):\n        def test(xdpi, ydpi=None):\n            with Image.open(TEST_FILE) as im:\n                im = self.roundtrip(im, dpi=(xdpi, ydpi or xdpi))\n            return im.info.get(\"dpi\")\n\n        assert test(72) == (72, 72)\n        assert test(300) == (300, 300)\n        assert test(100, 200) == (100, 200)\n        assert test(0) is None  # square pixels\n\n    def test_icc(self, tmp_path):\n        # Test ICC support\n        with Image.open(\"Tests/images/rgb.jpg\") as im1:\n            icc_profile = im1.info[\"icc_profile\"]\n            assert len(icc_profile) == 3144\n            # Roundtrip via physical file.\n            f = str(tmp_path / \"temp.jpg\")\n            im1.save(f, icc_profile=icc_profile)\n        with Image.open(f) as im2:\n            assert im2.info.get(\"icc_profile\") == icc_profile\n            # Roundtrip via memory buffer.\n            im1 = self.roundtrip(hopper())\n            im2 = self.roundtrip(hopper(), icc_profile=icc_profile)\n            assert_image_equal(im1, im2)\n            assert not im1.info.get(\"icc_profile\")\n            assert im2.info.get(\"icc_profile\")\n\n    def test_icc_big(self):\n        # Make sure that the \"extra\" support handles large blocks\n        def test(n):\n            # The ICC APP marker can store 65519 bytes per marker, so\n            # using a 4-byte test code should allow us to detect out of\n            # order issues.\n            icc_profile = (b\"Test\" * int(n / 4 + 1))[:n]\n            assert len(icc_profile) == n  # sanity\n            im1 = self.roundtrip(hopper(), icc_profile=icc_profile)\n            assert im1.info.get(\"icc_profile\") == (icc_profile or None)\n\n        test(0)\n        test(1)\n        test(3)\n        test(4)\n        test(5)\n        test(65533 - 14)  # full JPEG marker block\n        test(65533 - 14 + 1)  # full block plus one byte\n        test(ImageFile.MAXBLOCK)  # full buffer block\n        test(ImageFile.MAXBLOCK + 1)  # full buffer block plus one byte\n        test(ImageFile.MAXBLOCK * 4 + 3)  # large block\n\n    def test_large_icc_meta(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        # Sometimes the meta data on the icc_profile block is bigger than\n        # Image.MAXBLOCK or the image size.\n        with Image.open(\"Tests/images/icc_profile_big.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            icc_profile = im.info[\"icc_profile\"]\n            # Should not raise OSError for image with icc larger than image size.\n            im.save(\n                f,\n                format=\"JPEG\",\n                progressive=True,\n                quality=95,\n                icc_profile=icc_profile,\n                optimize=True,\n            )\n\n    def test_optimize(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), optimize=0)\n        im3 = self.roundtrip(hopper(), optimize=1)\n        assert_image_equal(im1, im2)\n        assert_image_equal(im1, im3)\n        assert im1.bytes >= im2.bytes\n        assert im1.bytes >= im3.bytes\n\n    def test_optimize_large_buffer(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        f = str(tmp_path / \"temp.jpg\")\n        # this requires ~ 1.5x Image.MAXBLOCK\n        im = Image.new(\"RGB\", (4096, 4096), 0xFF3333)\n        im.save(f, format=\"JPEG\", optimize=True)\n\n    def test_progressive(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), progressive=False)\n        im3 = self.roundtrip(hopper(), progressive=True)\n        assert not im1.info.get(\"progressive\")\n        assert not im2.info.get(\"progressive\")\n        assert im3.info.get(\"progressive\")\n\n        assert_image_equal(im1, im3)\n        assert im1.bytes >= im3.bytes\n\n    def test_progressive_large_buffer(self, tmp_path):\n        f = str(tmp_path / \"temp.jpg\")\n        # this requires ~ 1.5x Image.MAXBLOCK\n        im = Image.new(\"RGB\", (4096, 4096), 0xFF3333)\n        im.save(f, format=\"JPEG\", progressive=True)\n\n    def test_progressive_large_buffer_highest_quality(self, tmp_path):\n        f = str(tmp_path / \"temp.jpg\")\n        im = self.gen_random_image((255, 255))\n        # this requires more bytes than pixels in the image\n        im.save(f, format=\"JPEG\", progressive=True, quality=100)\n\n    def test_progressive_cmyk_buffer(self):\n        # Issue 2272, quality 90 cmyk image is tripping the large buffer bug.\n        f = BytesIO()\n        im = self.gen_random_image((256, 256), \"CMYK\")\n        im.save(f, format=\"JPEG\", progressive=True, quality=94)\n\n    def test_large_exif(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        f = str(tmp_path / \"temp.jpg\")\n        im = hopper()\n        im.save(f, \"JPEG\", quality=90, exif=b\"1\" * 65532)\n\n    def test_exif_typeerror(self):\n        with Image.open(\"Tests/images/exif_typeerror.jpg\") as im:\n            # Should not raise a TypeError\n            im._getexif()\n\n    def test_exif_gps(self):\n        # Arrange\n        with Image.open(\"Tests/images/exif_gps.jpg\") as im:\n            gps_index = 34853\n            expected_exif_gps = {\n                0: b\"\\x00\\x00\\x00\\x01\",\n                2: (4294967295, 1),\n                5: b\"\\x01\",\n                30: 65535,\n                29: \"1999:99:99 99:99:99\",\n            }\n\n            # Act\n            exif = im._getexif()\n\n        # Assert\n        assert exif[gps_index] == expected_exif_gps\n\n    def test_exif_rollback(self):\n        # rolling back exif support in 3.1 to pre-3.0 formatting.\n        # expected from 2.9, with b/u qualifiers switched for 3.2 compatibility\n        # this test passes on 2.9 and 3.1, but not 3.0\n        expected_exif = {\n            34867: 4294967295,\n            258: (24, 24, 24),\n            36867: \"2099:09:29 10:10:10\",\n            34853: {\n                0: b\"\\x00\\x00\\x00\\x01\",\n                2: (4294967295, 1),\n                5: b\"\\x01\",\n                30: 65535,\n                29: \"1999:99:99 99:99:99\",\n            },\n            296: 65535,\n            34665: 185,\n            41994: 65535,\n            514: 4294967295,\n            271: \"Make\",\n            272: \"XXX-XXX\",\n            305: \"PIL\",\n            42034: ((1, 1), (1, 1), (1, 1), (1, 1)),\n            42035: \"LensMake\",\n            34856: b\"\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa\",\n            282: (4294967295, 1),\n            33434: (4294967295, 1),\n        }\n\n        with Image.open(\"Tests/images/exif_gps.jpg\") as im:\n            exif = im._getexif()\n\n        for tag, value in expected_exif.items():\n            assert value == exif[tag]\n\n    def test_exif_gps_typeerror(self):\n        with Image.open(\"Tests/images/exif_gps_typeerror.jpg\") as im:\n\n            # Should not raise a TypeError\n            im._getexif()\n\n    def test_progressive_compat(self):\n        im1 = self.roundtrip(hopper())\n        assert not im1.info.get(\"progressive\")\n        assert not im1.info.get(\"progression\")\n\n        im2 = self.roundtrip(hopper(), progressive=0)\n        im3 = self.roundtrip(hopper(), progression=0)  # compatibility\n        assert not im2.info.get(\"progressive\")\n        assert not im2.info.get(\"progression\")\n        assert not im3.info.get(\"progressive\")\n        assert not im3.info.get(\"progression\")\n\n        im2 = self.roundtrip(hopper(), progressive=1)\n        im3 = self.roundtrip(hopper(), progression=1)  # compatibility\n        assert_image_equal(im1, im2)\n        assert_image_equal(im1, im3)\n        assert im2.info.get(\"progressive\")\n        assert im2.info.get(\"progression\")\n        assert im3.info.get(\"progressive\")\n        assert im3.info.get(\"progression\")\n\n    def test_quality(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), quality=50)\n        assert_image(im1, im2.mode, im2.size)\n        assert im1.bytes >= im2.bytes\n\n        im3 = self.roundtrip(hopper(), quality=0)\n        assert_image(im1, im3.mode, im3.size)\n        assert im2.bytes > im3.bytes\n\n    def test_smooth(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), smooth=100)\n        assert_image(im1, im2.mode, im2.size)\n\n    def test_subsampling(self):\n        def getsampling(im):\n            layer = im.layer\n            return layer[0][1:3] + layer[1][1:3] + layer[2][1:3]\n\n        # experimental API\n        im = self.roundtrip(hopper(), subsampling=-1)  # default\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=0)  # 4:4:4\n        assert getsampling(im) == (1, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=1)  # 4:2:2\n        assert getsampling(im) == (2, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=2)  # 4:2:0\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=3)  # default (undefined)\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n\n        im = self.roundtrip(hopper(), subsampling=\"4:4:4\")\n        assert getsampling(im) == (1, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:2:2\")\n        assert getsampling(im) == (2, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:2:0\")\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:1:1\")\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n\n        with pytest.raises(TypeError):\n            self.roundtrip(hopper(), subsampling=\"1:1:1\")\n\n    def test_exif(self):\n        with Image.open(\"Tests/images/pil_sample_rgb.jpg\") as im:\n            info = im._getexif()\n            assert info[305] == \"Adobe Photoshop CS Macintosh\"\n\n    def test_mp(self):\n        with Image.open(\"Tests/images/pil_sample_rgb.jpg\") as im:\n            assert im._getmp() is None\n\n    def test_quality_keep(self, tmp_path):\n        # RGB\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n        # Grayscale\n        with Image.open(\"Tests/images/hopper_gray.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n        # CMYK\n        with Image.open(\"Tests/images/pil_sample_cmyk.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n\n    def test_junk_jpeg_header(self):\n        # https://github.com/python-pillow/Pillow/issues/630\n        filename = \"Tests/images/junk_jpeg_header.jpg\"\n        with Image.open(filename):\n            pass\n\n    def test_ff00_jpeg_header(self):\n        filename = \"Tests/images/jpeg_ff00_header.jpg\"\n        with Image.open(filename):\n            pass\n\n    def test_truncated_jpeg_should_read_all_the_data(self):\n        filename = \"Tests/images/truncated_jpeg.jpg\"\n        ImageFile.LOAD_TRUNCATED_IMAGES = True\n        with Image.open(filename) as im:\n            im.load()\n            ImageFile.LOAD_TRUNCATED_IMAGES = False\n            assert im.getbbox() is not None\n\n    def test_truncated_jpeg_throws_oserror(self):\n        filename = \"Tests/images/truncated_jpeg.jpg\"\n        with Image.open(filename) as im:\n            with pytest.raises(OSError):\n                im.load()\n\n            # Test that the error is raised if loaded a second time\n            with pytest.raises(OSError):\n                im.load()\n\n    def test_qtables(self, tmp_path):\n        def _n_qtables_helper(n, test_file):\n            with Image.open(test_file) as im:\n                f = str(tmp_path / \"temp.jpg\")\n                im.save(f, qtables=[[n] * 64] * n)\n            with Image.open(f) as im:\n                assert len(im.quantization) == n\n                reloaded = self.roundtrip(im, qtables=\"keep\")\n                assert im.quantization == reloaded.quantization\n\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            qtables = im.quantization\n            reloaded = self.roundtrip(im, qtables=qtables, subsampling=0)\n            assert im.quantization == reloaded.quantization\n            assert_image_similar(im, self.roundtrip(im, qtables=\"web_low\"), 30)\n            assert_image_similar(im, self.roundtrip(im, qtables=\"web_high\"), 30)\n            assert_image_similar(im, self.roundtrip(im, qtables=\"keep\"), 30)\n\n            # valid bounds for baseline qtable\n            bounds_qtable = [int(s) for s in (\"255 1 \" * 32).split(None)]\n            self.roundtrip(im, qtables=[bounds_qtable])\n\n            # values from wizard.txt in jpeg9-a src package.\n            standard_l_qtable = [\n                int(s)\n                for s in \"\"\"\n                16  11  10  16  24  40  51  61\n                12  12  14  19  26  58  60  55\n                14  13  16  24  40  57  69  56\n                14  17  22  29  51  87  80  62\n                18  22  37  56  68 109 103  77\n                24  35  55  64  81 104 113  92\n                49  64  78  87 103 121 120 101\n                72  92  95  98 112 100 103  99\n                \"\"\".split(\n                    None\n                )\n            ]\n\n            standard_chrominance_qtable = [\n                int(s)\n                for s in \"\"\"\n                17  18  24  47  99  99  99  99\n                18  21  26  66  99  99  99  99\n                24  26  56  99  99  99  99  99\n                47  66  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                \"\"\".split(\n                    None\n                )\n            ]\n            # list of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables=[standard_l_qtable, standard_chrominance_qtable]\n                ),\n                30,\n            )\n\n            # tuple of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables=(standard_l_qtable, standard_chrominance_qtable)\n                ),\n                30,\n            )\n\n            # dict of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables={0: standard_l_qtable, 1: standard_chrominance_qtable}\n                ),\n                30,\n            )\n\n            _n_qtables_helper(1, \"Tests/images/hopper_gray.jpg\")\n            _n_qtables_helper(1, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(2, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(3, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(1, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(2, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(3, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(4, \"Tests/images/pil_sample_cmyk.jpg\")\n\n            # not a sequence\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=\"a\")\n            # sequence wrong length\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[])\n            # sequence wrong length\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[1, 2, 3, 4, 5])\n\n            # qtable entry not a sequence\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[1])\n            # qtable entry has wrong number of items\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[[1, 2, 3, 4]])\n\n    @pytest.mark.skipif(not djpeg_available(), reason=\"djpeg not available\")\n    def test_load_djpeg(self):\n        with Image.open(TEST_FILE) as img:\n            img.load_djpeg()\n            assert_image_similar(img, Image.open(TEST_FILE), 5)\n\n    @pytest.mark.skipif(not cjpeg_available(), reason=\"cjpeg not available\")\n    def test_save_cjpeg(self, tmp_path):\n        with Image.open(TEST_FILE) as img:\n            tempfile = str(tmp_path / \"temp.jpg\")\n            JpegImagePlugin._save_cjpeg(img, 0, tempfile)\n            # Default save quality is 75%, so a tiny bit of difference is alright\n            assert_image_similar(img, Image.open(tempfile), 17)\n\n    def test_no_duplicate_0x1001_tag(self):\n        # Arrange\n        tag_ids = {v: k for k, v in ExifTags.TAGS.items()}\n\n        # Assert\n        assert tag_ids[\"RelatedImageWidth\"] == 0x1001\n        assert tag_ids[\"RelatedImageLength\"] == 0x1002\n\n    def test_MAXBLOCK_scaling(self, tmp_path):\n        im = self.gen_random_image((512, 512))\n        f = str(tmp_path / \"temp.jpeg\")\n        im.save(f, quality=100, optimize=True)\n\n        with Image.open(f) as reloaded:\n            # none of these should crash\n            reloaded.save(f, quality=\"keep\")\n            reloaded.save(f, quality=\"keep\", progressive=True)\n            reloaded.save(f, quality=\"keep\", optimize=True)\n\n    def test_bad_mpo_header(self):\n        \"\"\" Treat unknown MPO as JPEG \"\"\"\n        # Arrange\n\n        # Act\n        # Shouldn't raise error\n        fn = \"Tests/images/sugarshack_bad_mpo_header.jpg\"\n        with pytest.warns(UserWarning, Image.open, fn) as im:\n\n            # Assert\n            assert im.format == \"JPEG\"\n\n    def test_save_correct_modes(self):\n        out = BytesIO()\n        for mode in [\"1\", \"L\", \"RGB\", \"RGBX\", \"CMYK\", \"YCbCr\"]:\n            img = Image.new(mode, (20, 20))\n            img.save(out, \"JPEG\")\n\n    def test_save_wrong_modes(self):\n        # ref https://github.com/python-pillow/Pillow/issues/2005\n        out = BytesIO()\n        for mode in [\"LA\", \"La\", \"RGBA\", \"RGBa\", \"P\"]:\n            img = Image.new(mode, (20, 20))\n            with pytest.raises(OSError):\n                img.save(out, \"JPEG\")\n\n    def test_save_tiff_with_dpi(self, tmp_path):\n        # Arrange\n        outfile = str(tmp_path / \"temp.tif\")\n        with Image.open(\"Tests/images/hopper.tif\") as im:\n\n            # Act\n            im.save(outfile, \"JPEG\", dpi=im.info[\"dpi\"])\n\n            # Assert\n            with Image.open(outfile) as reloaded:\n                reloaded.load()\n                assert im.info[\"dpi\"] == reloaded.info[\"dpi\"]\n\n    def test_load_dpi_rounding(self):\n        # Round up\n        with Image.open(\"Tests/images/iptc_roundUp.jpg\") as im:\n            assert im.info[\"dpi\"] == (44, 44)\n\n        # Round down\n        with Image.open(\"Tests/images/iptc_roundDown.jpg\") as im:\n            assert im.info[\"dpi\"] == (2, 2)\n\n    def test_save_dpi_rounding(self, tmp_path):\n        outfile = str(tmp_path / \"temp.jpg\")\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            im.save(outfile, dpi=(72.2, 72.2))\n\n            with Image.open(outfile) as reloaded:\n                assert reloaded.info[\"dpi\"] == (72, 72)\n\n            im.save(outfile, dpi=(72.8, 72.8))\n\n        with Image.open(outfile) as reloaded:\n            assert reloaded.info[\"dpi\"] == (73, 73)\n\n    def test_dpi_tuple_from_exif(self):\n        # Arrange\n        # This Photoshop CC 2017 image has DPI in EXIF not metadata\n        # EXIF XResolution is (2000000, 10000)\n        with Image.open(\"Tests/images/photoshop-200dpi.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (200, 200)\n\n    def test_dpi_int_from_exif(self):\n        # Arrange\n        # This image has DPI in EXIF not metadata\n        # EXIF XResolution is 72\n        with Image.open(\"Tests/images/exif-72dpi-int.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_dpi_from_dpcm_exif(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with EXIF resolution unit set to cm:\n        # exiftool -exif:ResolutionUnit=cm photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/exif-200dpcm.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (508, 508)\n\n    def test_dpi_exif_zero_division(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with EXIF resolution set to 0/0:\n        # exiftool -XResolution=0/0 -YResolution=0/0 photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/exif-dpi-zerodivision.jpg\") as im:\n\n            # Act / Assert\n            # This should return the default, and not raise a ZeroDivisionError\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_no_dpi_in_exif(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with resolution removed from EXIF:\n        # exiftool \"-*resolution*\"= photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/no-dpi-in-exif.jpg\") as im:\n\n            # Act / Assert\n            # \"When the image resolution is unknown, 72 [dpi] is designated.\"\n            # http://www.exiv2.org/tags.html\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_invalid_exif(self):\n        # This is no-dpi-in-exif with the tiff header of the exif block\n        # hexedited from MM * to FF FF FF FF\n        with Image.open(\"Tests/images/invalid-exif.jpg\") as im:\n\n            # This should return the default, and not a SyntaxError or\n            # OSError for unidentified image.\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_invalid_exif_x_resolution(self):\n        # When no x or y resolution is defined in EXIF\n        with Image.open(\"Tests/images/invalid-exif-without-x-resolution.jpg\") as im:\n\n            # This should return the default, and not a ValueError or\n            # OSError for an unidentified image.\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_ifd_offset_exif(self):\n        # Arrange\n        # This image has been manually hexedited to have an IFD offset of 10,\n        # in contrast to normal 8\n        with Image.open(\"Tests/images/exif-ifd-offset.jpg\") as im:\n\n            # Act / Assert\n            assert im._getexif()[306] == \"2017:03:13 23:03:09\"\n\n    def test_photoshop(self):\n        with Image.open(\"Tests/images/photoshop-200dpi.jpg\") as im:\n            assert im.info[\"photoshop\"][0x03ED] == {\n                \"XResolution\": 200.0,\n                \"DisplayedUnitsX\": 1,\n                \"YResolution\": 200.0,\n                \"DisplayedUnitsY\": 1,\n            }\n\n            # Test that the image can still load, even with broken Photoshop data\n            # This image had the APP13 length hexedited to be smaller\n            with Image.open(\"Tests/images/photoshop-200dpi-broken.jpg\") as im_broken:\n                assert_image_equal(im_broken, im)\n\n        # This image does not contain a Photoshop header string\n        with Image.open(\"Tests/images/app13.jpg\") as im:\n            assert \"photoshop\" not in im.info\n\n    def test_photoshop_malformed_and_multiple(self):\n        with Image.open(\"Tests/images/app13-multiple.jpg\") as im:\n            assert \"photoshop\" in im.info\n            assert 24 == len(im.info[\"photoshop\"])\n            apps_13_lengths = [len(v) for k, v in im.applist if k == \"APP13\"]\n            assert [65504, 24] == apps_13_lengths\n\n    def test_icc_after_SOF(self):\n        with Image.open(\"Tests/images/icc-after-SOF.jpg\") as im:\n            assert im.info[\"icc_profile\"] == b\"profile\"",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 216,
                            "end_lineno": 232,
                            "parent": {
                                "file_name": "Tests/test_file_jpeg.py",
                                "type": "class",
                                "name": "TestFileJpeg",
                                "content": "class TestFileJpeg:\n    def roundtrip(self, im, **options):\n        out = BytesIO()\n        im.save(out, \"JPEG\", **options)\n        test_bytes = out.tell()\n        out.seek(0)\n        im = Image.open(out)\n        im.bytes = test_bytes  # for testing only\n        return im\n\n    def gen_random_image(self, size, mode=\"RGB\"):\n        \"\"\" Generates a very hard to compress file\n        :param size: tuple\n        :param mode: optional image mode\n\n        \"\"\"\n        return Image.frombytes(mode, size, os.urandom(size[0] * size[1] * len(mode)))\n\n    def test_sanity(self):\n\n        # internal version number\n        assert re.search(r\"\\d+\\.\\d+$\", Image.core.jpeglib_version)\n\n        with Image.open(TEST_FILE) as im:\n            im.load()\n            assert im.mode == \"RGB\"\n            assert im.size == (128, 128)\n            assert im.format == \"JPEG\"\n            assert im.get_format_mimetype() == \"image/jpeg\"\n\n    def test_app(self):\n        # Test APP/COM reader (@PIL135)\n        with Image.open(TEST_FILE) as im:\n            assert im.applist[0] == (\"APP0\", b\"JFIF\\x00\\x01\\x01\\x01\\x00`\\x00`\\x00\\x00\")\n            assert im.applist[1] == (\n                \"COM\",\n                b\"File written by Adobe Photoshop\\xa8 4.0\\x00\",\n            )\n            assert len(im.applist) == 2\n\n            assert im.info[\"comment\"] == b\"File written by Adobe Photoshop\\xa8 4.0\\x00\"\n\n    def test_cmyk(self):\n        # Test CMYK handling.  Thanks to Tim and Charlie for test data,\n        # Michael for getting me to look one more time.\n        f = \"Tests/images/pil_sample_cmyk.jpg\"\n        with Image.open(f) as im:\n            # the source image has red pixels in the upper left corner.\n            c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))]\n            assert c == 0.0\n            assert m > 0.8\n            assert y > 0.8\n            assert k == 0.0\n            # the opposite corner is black\n            c, m, y, k = [\n                x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1))\n            ]\n            assert k > 0.9\n            # roundtrip, and check again\n            im = self.roundtrip(im)\n            c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))]\n            assert c == 0.0\n            assert m > 0.8\n            assert y > 0.8\n            assert k == 0.0\n            c, m, y, k = [\n                x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1))\n            ]\n            assert k > 0.9\n\n    def test_dpi(self):\n        def test(xdpi, ydpi=None):\n            with Image.open(TEST_FILE) as im:\n                im = self.roundtrip(im, dpi=(xdpi, ydpi or xdpi))\n            return im.info.get(\"dpi\")\n\n        assert test(72) == (72, 72)\n        assert test(300) == (300, 300)\n        assert test(100, 200) == (100, 200)\n        assert test(0) is None  # square pixels\n\n    def test_icc(self, tmp_path):\n        # Test ICC support\n        with Image.open(\"Tests/images/rgb.jpg\") as im1:\n            icc_profile = im1.info[\"icc_profile\"]\n            assert len(icc_profile) == 3144\n            # Roundtrip via physical file.\n            f = str(tmp_path / \"temp.jpg\")\n            im1.save(f, icc_profile=icc_profile)\n        with Image.open(f) as im2:\n            assert im2.info.get(\"icc_profile\") == icc_profile\n            # Roundtrip via memory buffer.\n            im1 = self.roundtrip(hopper())\n            im2 = self.roundtrip(hopper(), icc_profile=icc_profile)\n            assert_image_equal(im1, im2)\n            assert not im1.info.get(\"icc_profile\")\n            assert im2.info.get(\"icc_profile\")\n\n    def test_icc_big(self):\n        # Make sure that the \"extra\" support handles large blocks\n        def test(n):\n            # The ICC APP marker can store 65519 bytes per marker, so\n            # using a 4-byte test code should allow us to detect out of\n            # order issues.\n            icc_profile = (b\"Test\" * int(n / 4 + 1))[:n]\n            assert len(icc_profile) == n  # sanity\n            im1 = self.roundtrip(hopper(), icc_profile=icc_profile)\n            assert im1.info.get(\"icc_profile\") == (icc_profile or None)\n\n        test(0)\n        test(1)\n        test(3)\n        test(4)\n        test(5)\n        test(65533 - 14)  # full JPEG marker block\n        test(65533 - 14 + 1)  # full block plus one byte\n        test(ImageFile.MAXBLOCK)  # full buffer block\n        test(ImageFile.MAXBLOCK + 1)  # full buffer block plus one byte\n        test(ImageFile.MAXBLOCK * 4 + 3)  # large block\n\n    def test_large_icc_meta(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        # Sometimes the meta data on the icc_profile block is bigger than\n        # Image.MAXBLOCK or the image size.\n        with Image.open(\"Tests/images/icc_profile_big.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            icc_profile = im.info[\"icc_profile\"]\n            # Should not raise OSError for image with icc larger than image size.\n            im.save(\n                f,\n                format=\"JPEG\",\n                progressive=True,\n                quality=95,\n                icc_profile=icc_profile,\n                optimize=True,\n            )\n\n    def test_optimize(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), optimize=0)\n        im3 = self.roundtrip(hopper(), optimize=1)\n        assert_image_equal(im1, im2)\n        assert_image_equal(im1, im3)\n        assert im1.bytes >= im2.bytes\n        assert im1.bytes >= im3.bytes\n\n    def test_optimize_large_buffer(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        f = str(tmp_path / \"temp.jpg\")\n        # this requires ~ 1.5x Image.MAXBLOCK\n        im = Image.new(\"RGB\", (4096, 4096), 0xFF3333)\n        im.save(f, format=\"JPEG\", optimize=True)\n\n    def test_progressive(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), progressive=False)\n        im3 = self.roundtrip(hopper(), progressive=True)\n        assert not im1.info.get(\"progressive\")\n        assert not im2.info.get(\"progressive\")\n        assert im3.info.get(\"progressive\")\n\n        assert_image_equal(im1, im3)\n        assert im1.bytes >= im3.bytes\n\n    def test_progressive_large_buffer(self, tmp_path):\n        f = str(tmp_path / \"temp.jpg\")\n        # this requires ~ 1.5x Image.MAXBLOCK\n        im = Image.new(\"RGB\", (4096, 4096), 0xFF3333)\n        im.save(f, format=\"JPEG\", progressive=True)\n\n    def test_progressive_large_buffer_highest_quality(self, tmp_path):\n        f = str(tmp_path / \"temp.jpg\")\n        im = self.gen_random_image((255, 255))\n        # this requires more bytes than pixels in the image\n        im.save(f, format=\"JPEG\", progressive=True, quality=100)\n\n    def test_progressive_cmyk_buffer(self):\n        # Issue 2272, quality 90 cmyk image is tripping the large buffer bug.\n        f = BytesIO()\n        im = self.gen_random_image((256, 256), \"CMYK\")\n        im.save(f, format=\"JPEG\", progressive=True, quality=94)\n\n    def test_large_exif(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        f = str(tmp_path / \"temp.jpg\")\n        im = hopper()\n        im.save(f, \"JPEG\", quality=90, exif=b\"1\" * 65532)\n\n    def test_exif_typeerror(self):\n        with Image.open(\"Tests/images/exif_typeerror.jpg\") as im:\n            # Should not raise a TypeError\n            im._getexif()\n\n    def test_exif_gps(self):\n        # Arrange\n        with Image.open(\"Tests/images/exif_gps.jpg\") as im:\n            gps_index = 34853\n            expected_exif_gps = {\n                0: b\"\\x00\\x00\\x00\\x01\",\n                2: (4294967295, 1),\n                5: b\"\\x01\",\n                30: 65535,\n                29: \"1999:99:99 99:99:99\",\n            }\n\n            # Act\n            exif = im._getexif()\n\n        # Assert\n        assert exif[gps_index] == expected_exif_gps\n\n    def test_exif_rollback(self):\n        # rolling back exif support in 3.1 to pre-3.0 formatting.\n        # expected from 2.9, with b/u qualifiers switched for 3.2 compatibility\n        # this test passes on 2.9 and 3.1, but not 3.0\n        expected_exif = {\n            34867: 4294967295,\n            258: (24, 24, 24),\n            36867: \"2099:09:29 10:10:10\",\n            34853: {\n                0: b\"\\x00\\x00\\x00\\x01\",\n                2: (4294967295, 1),\n                5: b\"\\x01\",\n                30: 65535,\n                29: \"1999:99:99 99:99:99\",\n            },\n            296: 65535,\n            34665: 185,\n            41994: 65535,\n            514: 4294967295,\n            271: \"Make\",\n            272: \"XXX-XXX\",\n            305: \"PIL\",\n            42034: ((1, 1), (1, 1), (1, 1), (1, 1)),\n            42035: \"LensMake\",\n            34856: b\"\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa\",\n            282: (4294967295, 1),\n            33434: (4294967295, 1),\n        }\n\n        with Image.open(\"Tests/images/exif_gps.jpg\") as im:\n            exif = im._getexif()\n\n        for tag, value in expected_exif.items():\n            assert value == exif[tag]\n\n    def test_exif_gps_typeerror(self):\n        with Image.open(\"Tests/images/exif_gps_typeerror.jpg\") as im:\n\n            # Should not raise a TypeError\n            im._getexif()\n\n    def test_progressive_compat(self):\n        im1 = self.roundtrip(hopper())\n        assert not im1.info.get(\"progressive\")\n        assert not im1.info.get(\"progression\")\n\n        im2 = self.roundtrip(hopper(), progressive=0)\n        im3 = self.roundtrip(hopper(), progression=0)  # compatibility\n        assert not im2.info.get(\"progressive\")\n        assert not im2.info.get(\"progression\")\n        assert not im3.info.get(\"progressive\")\n        assert not im3.info.get(\"progression\")\n\n        im2 = self.roundtrip(hopper(), progressive=1)\n        im3 = self.roundtrip(hopper(), progression=1)  # compatibility\n        assert_image_equal(im1, im2)\n        assert_image_equal(im1, im3)\n        assert im2.info.get(\"progressive\")\n        assert im2.info.get(\"progression\")\n        assert im3.info.get(\"progressive\")\n        assert im3.info.get(\"progression\")\n\n    def test_quality(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), quality=50)\n        assert_image(im1, im2.mode, im2.size)\n        assert im1.bytes >= im2.bytes\n\n        im3 = self.roundtrip(hopper(), quality=0)\n        assert_image(im1, im3.mode, im3.size)\n        assert im2.bytes > im3.bytes\n\n    def test_smooth(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), smooth=100)\n        assert_image(im1, im2.mode, im2.size)\n\n    def test_subsampling(self):\n        def getsampling(im):\n            layer = im.layer\n            return layer[0][1:3] + layer[1][1:3] + layer[2][1:3]\n\n        # experimental API\n        im = self.roundtrip(hopper(), subsampling=-1)  # default\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=0)  # 4:4:4\n        assert getsampling(im) == (1, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=1)  # 4:2:2\n        assert getsampling(im) == (2, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=2)  # 4:2:0\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=3)  # default (undefined)\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n\n        im = self.roundtrip(hopper(), subsampling=\"4:4:4\")\n        assert getsampling(im) == (1, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:2:2\")\n        assert getsampling(im) == (2, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:2:0\")\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:1:1\")\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n\n        with pytest.raises(TypeError):\n            self.roundtrip(hopper(), subsampling=\"1:1:1\")\n\n    def test_exif(self):\n        with Image.open(\"Tests/images/pil_sample_rgb.jpg\") as im:\n            info = im._getexif()\n            assert info[305] == \"Adobe Photoshop CS Macintosh\"\n\n    def test_mp(self):\n        with Image.open(\"Tests/images/pil_sample_rgb.jpg\") as im:\n            assert im._getmp() is None\n\n    def test_quality_keep(self, tmp_path):\n        # RGB\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n        # Grayscale\n        with Image.open(\"Tests/images/hopper_gray.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n        # CMYK\n        with Image.open(\"Tests/images/pil_sample_cmyk.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n\n    def test_junk_jpeg_header(self):\n        # https://github.com/python-pillow/Pillow/issues/630\n        filename = \"Tests/images/junk_jpeg_header.jpg\"\n        with Image.open(filename):\n            pass\n\n    def test_ff00_jpeg_header(self):\n        filename = \"Tests/images/jpeg_ff00_header.jpg\"\n        with Image.open(filename):\n            pass\n\n    def test_truncated_jpeg_should_read_all_the_data(self):\n        filename = \"Tests/images/truncated_jpeg.jpg\"\n        ImageFile.LOAD_TRUNCATED_IMAGES = True\n        with Image.open(filename) as im:\n            im.load()\n            ImageFile.LOAD_TRUNCATED_IMAGES = False\n            assert im.getbbox() is not None\n\n    def test_truncated_jpeg_throws_oserror(self):\n        filename = \"Tests/images/truncated_jpeg.jpg\"\n        with Image.open(filename) as im:\n            with pytest.raises(OSError):\n                im.load()\n\n            # Test that the error is raised if loaded a second time\n            with pytest.raises(OSError):\n                im.load()\n\n    def test_qtables(self, tmp_path):\n        def _n_qtables_helper(n, test_file):\n            with Image.open(test_file) as im:\n                f = str(tmp_path / \"temp.jpg\")\n                im.save(f, qtables=[[n] * 64] * n)\n            with Image.open(f) as im:\n                assert len(im.quantization) == n\n                reloaded = self.roundtrip(im, qtables=\"keep\")\n                assert im.quantization == reloaded.quantization\n\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            qtables = im.quantization\n            reloaded = self.roundtrip(im, qtables=qtables, subsampling=0)\n            assert im.quantization == reloaded.quantization\n            assert_image_similar(im, self.roundtrip(im, qtables=\"web_low\"), 30)\n            assert_image_similar(im, self.roundtrip(im, qtables=\"web_high\"), 30)\n            assert_image_similar(im, self.roundtrip(im, qtables=\"keep\"), 30)\n\n            # valid bounds for baseline qtable\n            bounds_qtable = [int(s) for s in (\"255 1 \" * 32).split(None)]\n            self.roundtrip(im, qtables=[bounds_qtable])\n\n            # values from wizard.txt in jpeg9-a src package.\n            standard_l_qtable = [\n                int(s)\n                for s in \"\"\"\n                16  11  10  16  24  40  51  61\n                12  12  14  19  26  58  60  55\n                14  13  16  24  40  57  69  56\n                14  17  22  29  51  87  80  62\n                18  22  37  56  68 109 103  77\n                24  35  55  64  81 104 113  92\n                49  64  78  87 103 121 120 101\n                72  92  95  98 112 100 103  99\n                \"\"\".split(\n                    None\n                )\n            ]\n\n            standard_chrominance_qtable = [\n                int(s)\n                for s in \"\"\"\n                17  18  24  47  99  99  99  99\n                18  21  26  66  99  99  99  99\n                24  26  56  99  99  99  99  99\n                47  66  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                \"\"\".split(\n                    None\n                )\n            ]\n            # list of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables=[standard_l_qtable, standard_chrominance_qtable]\n                ),\n                30,\n            )\n\n            # tuple of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables=(standard_l_qtable, standard_chrominance_qtable)\n                ),\n                30,\n            )\n\n            # dict of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables={0: standard_l_qtable, 1: standard_chrominance_qtable}\n                ),\n                30,\n            )\n\n            _n_qtables_helper(1, \"Tests/images/hopper_gray.jpg\")\n            _n_qtables_helper(1, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(2, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(3, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(1, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(2, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(3, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(4, \"Tests/images/pil_sample_cmyk.jpg\")\n\n            # not a sequence\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=\"a\")\n            # sequence wrong length\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[])\n            # sequence wrong length\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[1, 2, 3, 4, 5])\n\n            # qtable entry not a sequence\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[1])\n            # qtable entry has wrong number of items\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[[1, 2, 3, 4]])\n\n    @pytest.mark.skipif(not djpeg_available(), reason=\"djpeg not available\")\n    def test_load_djpeg(self):\n        with Image.open(TEST_FILE) as img:\n            img.load_djpeg()\n            assert_image_similar(img, Image.open(TEST_FILE), 5)\n\n    @pytest.mark.skipif(not cjpeg_available(), reason=\"cjpeg not available\")\n    def test_save_cjpeg(self, tmp_path):\n        with Image.open(TEST_FILE) as img:\n            tempfile = str(tmp_path / \"temp.jpg\")\n            JpegImagePlugin._save_cjpeg(img, 0, tempfile)\n            # Default save quality is 75%, so a tiny bit of difference is alright\n            assert_image_similar(img, Image.open(tempfile), 17)\n\n    def test_no_duplicate_0x1001_tag(self):\n        # Arrange\n        tag_ids = {v: k for k, v in ExifTags.TAGS.items()}\n\n        # Assert\n        assert tag_ids[\"RelatedImageWidth\"] == 0x1001\n        assert tag_ids[\"RelatedImageLength\"] == 0x1002\n\n    def test_MAXBLOCK_scaling(self, tmp_path):\n        im = self.gen_random_image((512, 512))\n        f = str(tmp_path / \"temp.jpeg\")\n        im.save(f, quality=100, optimize=True)\n\n        with Image.open(f) as reloaded:\n            # none of these should crash\n            reloaded.save(f, quality=\"keep\")\n            reloaded.save(f, quality=\"keep\", progressive=True)\n            reloaded.save(f, quality=\"keep\", optimize=True)\n\n    def test_bad_mpo_header(self):\n        \"\"\" Treat unknown MPO as JPEG \"\"\"\n        # Arrange\n\n        # Act\n        # Shouldn't raise error\n        fn = \"Tests/images/sugarshack_bad_mpo_header.jpg\"\n        with pytest.warns(UserWarning, Image.open, fn) as im:\n\n            # Assert\n            assert im.format == \"JPEG\"\n\n    def test_save_correct_modes(self):\n        out = BytesIO()\n        for mode in [\"1\", \"L\", \"RGB\", \"RGBX\", \"CMYK\", \"YCbCr\"]:\n            img = Image.new(mode, (20, 20))\n            img.save(out, \"JPEG\")\n\n    def test_save_wrong_modes(self):\n        # ref https://github.com/python-pillow/Pillow/issues/2005\n        out = BytesIO()\n        for mode in [\"LA\", \"La\", \"RGBA\", \"RGBa\", \"P\"]:\n            img = Image.new(mode, (20, 20))\n            with pytest.raises(OSError):\n                img.save(out, \"JPEG\")\n\n    def test_save_tiff_with_dpi(self, tmp_path):\n        # Arrange\n        outfile = str(tmp_path / \"temp.tif\")\n        with Image.open(\"Tests/images/hopper.tif\") as im:\n\n            # Act\n            im.save(outfile, \"JPEG\", dpi=im.info[\"dpi\"])\n\n            # Assert\n            with Image.open(outfile) as reloaded:\n                reloaded.load()\n                assert im.info[\"dpi\"] == reloaded.info[\"dpi\"]\n\n    def test_load_dpi_rounding(self):\n        # Round up\n        with Image.open(\"Tests/images/iptc_roundUp.jpg\") as im:\n            assert im.info[\"dpi\"] == (44, 44)\n\n        # Round down\n        with Image.open(\"Tests/images/iptc_roundDown.jpg\") as im:\n            assert im.info[\"dpi\"] == (2, 2)\n\n    def test_save_dpi_rounding(self, tmp_path):\n        outfile = str(tmp_path / \"temp.jpg\")\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            im.save(outfile, dpi=(72.2, 72.2))\n\n            with Image.open(outfile) as reloaded:\n                assert reloaded.info[\"dpi\"] == (72, 72)\n\n            im.save(outfile, dpi=(72.8, 72.8))\n\n        with Image.open(outfile) as reloaded:\n            assert reloaded.info[\"dpi\"] == (73, 73)\n\n    def test_dpi_tuple_from_exif(self):\n        # Arrange\n        # This Photoshop CC 2017 image has DPI in EXIF not metadata\n        # EXIF XResolution is (2000000, 10000)\n        with Image.open(\"Tests/images/photoshop-200dpi.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (200, 200)\n\n    def test_dpi_int_from_exif(self):\n        # Arrange\n        # This image has DPI in EXIF not metadata\n        # EXIF XResolution is 72\n        with Image.open(\"Tests/images/exif-72dpi-int.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_dpi_from_dpcm_exif(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with EXIF resolution unit set to cm:\n        # exiftool -exif:ResolutionUnit=cm photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/exif-200dpcm.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (508, 508)\n\n    def test_dpi_exif_zero_division(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with EXIF resolution set to 0/0:\n        # exiftool -XResolution=0/0 -YResolution=0/0 photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/exif-dpi-zerodivision.jpg\") as im:\n\n            # Act / Assert\n            # This should return the default, and not raise a ZeroDivisionError\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_no_dpi_in_exif(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with resolution removed from EXIF:\n        # exiftool \"-*resolution*\"= photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/no-dpi-in-exif.jpg\") as im:\n\n            # Act / Assert\n            # \"When the image resolution is unknown, 72 [dpi] is designated.\"\n            # http://www.exiv2.org/tags.html\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_invalid_exif(self):\n        # This is no-dpi-in-exif with the tiff header of the exif block\n        # hexedited from MM * to FF FF FF FF\n        with Image.open(\"Tests/images/invalid-exif.jpg\") as im:\n\n            # This should return the default, and not a SyntaxError or\n            # OSError for unidentified image.\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_invalid_exif_x_resolution(self):\n        # When no x or y resolution is defined in EXIF\n        with Image.open(\"Tests/images/invalid-exif-without-x-resolution.jpg\") as im:\n\n            # This should return the default, and not a ValueError or\n            # OSError for an unidentified image.\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_ifd_offset_exif(self):\n        # Arrange\n        # This image has been manually hexedited to have an IFD offset of 10,\n        # in contrast to normal 8\n        with Image.open(\"Tests/images/exif-ifd-offset.jpg\") as im:\n\n            # Act / Assert\n            assert im._getexif()[306] == \"2017:03:13 23:03:09\"\n\n    def test_photoshop(self):\n        with Image.open(\"Tests/images/photoshop-200dpi.jpg\") as im:\n            assert im.info[\"photoshop\"][0x03ED] == {\n                \"XResolution\": 200.0,\n                \"DisplayedUnitsX\": 1,\n                \"YResolution\": 200.0,\n                \"DisplayedUnitsY\": 1,\n            }\n\n            # Test that the image can still load, even with broken Photoshop data\n            # This image had the APP13 length hexedited to be smaller\n            with Image.open(\"Tests/images/photoshop-200dpi-broken.jpg\") as im_broken:\n                assert_image_equal(im_broken, im)\n\n        # This image does not contain a Photoshop header string\n        with Image.open(\"Tests/images/app13.jpg\") as im:\n            assert \"photoshop\" not in im.info\n\n    def test_photoshop_malformed_and_multiple(self):\n        with Image.open(\"Tests/images/app13-multiple.jpg\") as im:\n            assert \"photoshop\" in im.info\n            assert 24 == len(im.info[\"photoshop\"])\n            apps_13_lengths = [len(v) for k, v in im.applist if k == \"APP13\"]\n            assert [65504, 24] == apps_13_lengths\n\n    def test_icc_after_SOF(self):\n        with Image.open(\"Tests/images/icc-after-SOF.jpg\") as im:\n            assert im.info[\"icc_profile\"] == b\"profile\"",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 23,
                                "end_lineno": 694,
                                "parent": null
                            }
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 241,
                            "length": 7
                        },
                        "new_range": {
                            "start": 241,
                            "length": 7
                        },
                        "section": "class TestFileJpeg:"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "            36867: \"2099:09:29 10:10:10\",",
                                "type": "context"
                            },
                            {
                                "content": "            34853: {",
                                "type": "context"
                            },
                            {
                                "content": "                0: b\"\\x00\\x00\\x00\\x01\",",
                                "type": "context"
                            },
                            {
                                "content": "                2: (4294967295, 1),",
                                "type": "deleted"
                            },
                            {
                                "content": "                2: 4294967295,",
                                "type": "added"
                            },
                            {
                                "content": "                5: b\"\\x01\",",
                                "type": "context"
                            },
                            {
                                "content": "                30: 65535,",
                                "type": "context"
                            },
                            {
                                "content": "                29: \"1999:99:99 99:99:99\",",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Tests/test_file_jpeg.py",
                            "type": "method",
                            "name": "TestFileJpeg.test_exif_rollback",
                            "content": "class TestFileJpeg:\n    def roundtrip(self, im, **options):\n        out = BytesIO()\n        im.save(out, \"JPEG\", **options)\n        test_bytes = out.tell()\n        out.seek(0)\n        im = Image.open(out)\n        im.bytes = test_bytes  # for testing only\n        return im\n\n    def gen_random_image(self, size, mode=\"RGB\"):\n        \"\"\" Generates a very hard to compress file\n        :param size: tuple\n        :param mode: optional image mode\n\n        \"\"\"\n        return Image.frombytes(mode, size, os.urandom(size[0] * size[1] * len(mode)))\n\n    def test_sanity(self):\n\n        # internal version number\n        assert re.search(r\"\\d+\\.\\d+$\", Image.core.jpeglib_version)\n\n        with Image.open(TEST_FILE) as im:\n            im.load()\n            assert im.mode == \"RGB\"\n            assert im.size == (128, 128)\n            assert im.format == \"JPEG\"\n            assert im.get_format_mimetype() == \"image/jpeg\"\n\n    def test_app(self):\n        # Test APP/COM reader (@PIL135)\n        with Image.open(TEST_FILE) as im:\n            assert im.applist[0] == (\"APP0\", b\"JFIF\\x00\\x01\\x01\\x01\\x00`\\x00`\\x00\\x00\")\n            assert im.applist[1] == (\n                \"COM\",\n                b\"File written by Adobe Photoshop\\xa8 4.0\\x00\",\n            )\n            assert len(im.applist) == 2\n\n            assert im.info[\"comment\"] == b\"File written by Adobe Photoshop\\xa8 4.0\\x00\"\n\n    def test_cmyk(self):\n        # Test CMYK handling.  Thanks to Tim and Charlie for test data,\n        # Michael for getting me to look one more time.\n        f = \"Tests/images/pil_sample_cmyk.jpg\"\n        with Image.open(f) as im:\n            # the source image has red pixels in the upper left corner.\n            c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))]\n            assert c == 0.0\n            assert m > 0.8\n            assert y > 0.8\n            assert k == 0.0\n            # the opposite corner is black\n            c, m, y, k = [\n                x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1))\n            ]\n            assert k > 0.9\n            # roundtrip, and check again\n            im = self.roundtrip(im)\n            c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))]\n            assert c == 0.0\n            assert m > 0.8\n            assert y > 0.8\n            assert k == 0.0\n            c, m, y, k = [\n                x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1))\n            ]\n            assert k > 0.9\n\n    def test_dpi(self):\n        def test(xdpi, ydpi=None):\n            with Image.open(TEST_FILE) as im:\n                im = self.roundtrip(im, dpi=(xdpi, ydpi or xdpi))\n            return im.info.get(\"dpi\")\n\n        assert test(72) == (72, 72)\n        assert test(300) == (300, 300)\n        assert test(100, 200) == (100, 200)\n        assert test(0) is None  # square pixels\n\n    def test_icc(self, tmp_path):\n        # Test ICC support\n        with Image.open(\"Tests/images/rgb.jpg\") as im1:\n            icc_profile = im1.info[\"icc_profile\"]\n            assert len(icc_profile) == 3144\n            # Roundtrip via physical file.\n            f = str(tmp_path / \"temp.jpg\")\n            im1.save(f, icc_profile=icc_profile)\n        with Image.open(f) as im2:\n            assert im2.info.get(\"icc_profile\") == icc_profile\n            # Roundtrip via memory buffer.\n            im1 = self.roundtrip(hopper())\n            im2 = self.roundtrip(hopper(), icc_profile=icc_profile)\n            assert_image_equal(im1, im2)\n            assert not im1.info.get(\"icc_profile\")\n            assert im2.info.get(\"icc_profile\")\n\n    def test_icc_big(self):\n        # Make sure that the \"extra\" support handles large blocks\n        def test(n):\n            # The ICC APP marker can store 65519 bytes per marker, so\n            # using a 4-byte test code should allow us to detect out of\n            # order issues.\n            icc_profile = (b\"Test\" * int(n / 4 + 1))[:n]\n            assert len(icc_profile) == n  # sanity\n            im1 = self.roundtrip(hopper(), icc_profile=icc_profile)\n            assert im1.info.get(\"icc_profile\") == (icc_profile or None)\n\n        test(0)\n        test(1)\n        test(3)\n        test(4)\n        test(5)\n        test(65533 - 14)  # full JPEG marker block\n        test(65533 - 14 + 1)  # full block plus one byte\n        test(ImageFile.MAXBLOCK)  # full buffer block\n        test(ImageFile.MAXBLOCK + 1)  # full buffer block plus one byte\n        test(ImageFile.MAXBLOCK * 4 + 3)  # large block\n\n    def test_large_icc_meta(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        # Sometimes the meta data on the icc_profile block is bigger than\n        # Image.MAXBLOCK or the image size.\n        with Image.open(\"Tests/images/icc_profile_big.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            icc_profile = im.info[\"icc_profile\"]\n            # Should not raise OSError for image with icc larger than image size.\n            im.save(\n                f,\n                format=\"JPEG\",\n                progressive=True,\n                quality=95,\n                icc_profile=icc_profile,\n                optimize=True,\n            )\n\n    def test_optimize(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), optimize=0)\n        im3 = self.roundtrip(hopper(), optimize=1)\n        assert_image_equal(im1, im2)\n        assert_image_equal(im1, im3)\n        assert im1.bytes >= im2.bytes\n        assert im1.bytes >= im3.bytes\n\n    def test_optimize_large_buffer(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        f = str(tmp_path / \"temp.jpg\")\n        # this requires ~ 1.5x Image.MAXBLOCK\n        im = Image.new(\"RGB\", (4096, 4096), 0xFF3333)\n        im.save(f, format=\"JPEG\", optimize=True)\n\n    def test_progressive(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), progressive=False)\n        im3 = self.roundtrip(hopper(), progressive=True)\n        assert not im1.info.get(\"progressive\")\n        assert not im2.info.get(\"progressive\")\n        assert im3.info.get(\"progressive\")\n\n        assert_image_equal(im1, im3)\n        assert im1.bytes >= im3.bytes\n\n    def test_progressive_large_buffer(self, tmp_path):\n        f = str(tmp_path / \"temp.jpg\")\n        # this requires ~ 1.5x Image.MAXBLOCK\n        im = Image.new(\"RGB\", (4096, 4096), 0xFF3333)\n        im.save(f, format=\"JPEG\", progressive=True)\n\n    def test_progressive_large_buffer_highest_quality(self, tmp_path):\n        f = str(tmp_path / \"temp.jpg\")\n        im = self.gen_random_image((255, 255))\n        # this requires more bytes than pixels in the image\n        im.save(f, format=\"JPEG\", progressive=True, quality=100)\n\n    def test_progressive_cmyk_buffer(self):\n        # Issue 2272, quality 90 cmyk image is tripping the large buffer bug.\n        f = BytesIO()\n        im = self.gen_random_image((256, 256), \"CMYK\")\n        im.save(f, format=\"JPEG\", progressive=True, quality=94)\n\n    def test_large_exif(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        f = str(tmp_path / \"temp.jpg\")\n        im = hopper()\n        im.save(f, \"JPEG\", quality=90, exif=b\"1\" * 65532)\n\n    def test_exif_typeerror(self):\n        with Image.open(\"Tests/images/exif_typeerror.jpg\") as im:\n            # Should not raise a TypeError\n            im._getexif()\n\n    def test_exif_gps(self):\n        # Arrange\n        with Image.open(\"Tests/images/exif_gps.jpg\") as im:\n            gps_index = 34853\n            expected_exif_gps = {\n                0: b\"\\x00\\x00\\x00\\x01\",\n                2: (4294967295, 1),\n                5: b\"\\x01\",\n                30: 65535,\n                29: \"1999:99:99 99:99:99\",\n            }\n\n            # Act\n            exif = im._getexif()\n\n        # Assert\n        assert exif[gps_index] == expected_exif_gps\n\n    def test_exif_rollback(self):\n        # rolling back exif support in 3.1 to pre-3.0 formatting.\n        # expected from 2.9, with b/u qualifiers switched for 3.2 compatibility\n        # this test passes on 2.9 and 3.1, but not 3.0\n        expected_exif = {\n            34867: 4294967295,\n            258: (24, 24, 24),\n            36867: \"2099:09:29 10:10:10\",\n            34853: {\n                0: b\"\\x00\\x00\\x00\\x01\",\n                2: (4294967295, 1),\n                5: b\"\\x01\",\n                30: 65535,\n                29: \"1999:99:99 99:99:99\",\n            },\n            296: 65535,\n            34665: 185,\n            41994: 65535,\n            514: 4294967295,\n            271: \"Make\",\n            272: \"XXX-XXX\",\n            305: \"PIL\",\n            42034: ((1, 1), (1, 1), (1, 1), (1, 1)),\n            42035: \"LensMake\",\n            34856: b\"\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa\",\n            282: (4294967295, 1),\n            33434: (4294967295, 1),\n        }\n\n        with Image.open(\"Tests/images/exif_gps.jpg\") as im:\n            exif = im._getexif()\n\n        for tag, value in expected_exif.items():\n            assert value == exif[tag]\n\n    def test_exif_gps_typeerror(self):\n        with Image.open(\"Tests/images/exif_gps_typeerror.jpg\") as im:\n\n            # Should not raise a TypeError\n            im._getexif()\n\n    def test_progressive_compat(self):\n        im1 = self.roundtrip(hopper())\n        assert not im1.info.get(\"progressive\")\n        assert not im1.info.get(\"progression\")\n\n        im2 = self.roundtrip(hopper(), progressive=0)\n        im3 = self.roundtrip(hopper(), progression=0)  # compatibility\n        assert not im2.info.get(\"progressive\")\n        assert not im2.info.get(\"progression\")\n        assert not im3.info.get(\"progressive\")\n        assert not im3.info.get(\"progression\")\n\n        im2 = self.roundtrip(hopper(), progressive=1)\n        im3 = self.roundtrip(hopper(), progression=1)  # compatibility\n        assert_image_equal(im1, im2)\n        assert_image_equal(im1, im3)\n        assert im2.info.get(\"progressive\")\n        assert im2.info.get(\"progression\")\n        assert im3.info.get(\"progressive\")\n        assert im3.info.get(\"progression\")\n\n    def test_quality(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), quality=50)\n        assert_image(im1, im2.mode, im2.size)\n        assert im1.bytes >= im2.bytes\n\n        im3 = self.roundtrip(hopper(), quality=0)\n        assert_image(im1, im3.mode, im3.size)\n        assert im2.bytes > im3.bytes\n\n    def test_smooth(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), smooth=100)\n        assert_image(im1, im2.mode, im2.size)\n\n    def test_subsampling(self):\n        def getsampling(im):\n            layer = im.layer\n            return layer[0][1:3] + layer[1][1:3] + layer[2][1:3]\n\n        # experimental API\n        im = self.roundtrip(hopper(), subsampling=-1)  # default\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=0)  # 4:4:4\n        assert getsampling(im) == (1, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=1)  # 4:2:2\n        assert getsampling(im) == (2, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=2)  # 4:2:0\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=3)  # default (undefined)\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n\n        im = self.roundtrip(hopper(), subsampling=\"4:4:4\")\n        assert getsampling(im) == (1, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:2:2\")\n        assert getsampling(im) == (2, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:2:0\")\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:1:1\")\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n\n        with pytest.raises(TypeError):\n            self.roundtrip(hopper(), subsampling=\"1:1:1\")\n\n    def test_exif(self):\n        with Image.open(\"Tests/images/pil_sample_rgb.jpg\") as im:\n            info = im._getexif()\n            assert info[305] == \"Adobe Photoshop CS Macintosh\"\n\n    def test_mp(self):\n        with Image.open(\"Tests/images/pil_sample_rgb.jpg\") as im:\n            assert im._getmp() is None\n\n    def test_quality_keep(self, tmp_path):\n        # RGB\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n        # Grayscale\n        with Image.open(\"Tests/images/hopper_gray.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n        # CMYK\n        with Image.open(\"Tests/images/pil_sample_cmyk.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n\n    def test_junk_jpeg_header(self):\n        # https://github.com/python-pillow/Pillow/issues/630\n        filename = \"Tests/images/junk_jpeg_header.jpg\"\n        with Image.open(filename):\n            pass\n\n    def test_ff00_jpeg_header(self):\n        filename = \"Tests/images/jpeg_ff00_header.jpg\"\n        with Image.open(filename):\n            pass\n\n    def test_truncated_jpeg_should_read_all_the_data(self):\n        filename = \"Tests/images/truncated_jpeg.jpg\"\n        ImageFile.LOAD_TRUNCATED_IMAGES = True\n        with Image.open(filename) as im:\n            im.load()\n            ImageFile.LOAD_TRUNCATED_IMAGES = False\n            assert im.getbbox() is not None\n\n    def test_truncated_jpeg_throws_oserror(self):\n        filename = \"Tests/images/truncated_jpeg.jpg\"\n        with Image.open(filename) as im:\n            with pytest.raises(OSError):\n                im.load()\n\n            # Test that the error is raised if loaded a second time\n            with pytest.raises(OSError):\n                im.load()\n\n    def test_qtables(self, tmp_path):\n        def _n_qtables_helper(n, test_file):\n            with Image.open(test_file) as im:\n                f = str(tmp_path / \"temp.jpg\")\n                im.save(f, qtables=[[n] * 64] * n)\n            with Image.open(f) as im:\n                assert len(im.quantization) == n\n                reloaded = self.roundtrip(im, qtables=\"keep\")\n                assert im.quantization == reloaded.quantization\n\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            qtables = im.quantization\n            reloaded = self.roundtrip(im, qtables=qtables, subsampling=0)\n            assert im.quantization == reloaded.quantization\n            assert_image_similar(im, self.roundtrip(im, qtables=\"web_low\"), 30)\n            assert_image_similar(im, self.roundtrip(im, qtables=\"web_high\"), 30)\n            assert_image_similar(im, self.roundtrip(im, qtables=\"keep\"), 30)\n\n            # valid bounds for baseline qtable\n            bounds_qtable = [int(s) for s in (\"255 1 \" * 32).split(None)]\n            self.roundtrip(im, qtables=[bounds_qtable])\n\n            # values from wizard.txt in jpeg9-a src package.\n            standard_l_qtable = [\n                int(s)\n                for s in \"\"\"\n                16  11  10  16  24  40  51  61\n                12  12  14  19  26  58  60  55\n                14  13  16  24  40  57  69  56\n                14  17  22  29  51  87  80  62\n                18  22  37  56  68 109 103  77\n                24  35  55  64  81 104 113  92\n                49  64  78  87 103 121 120 101\n                72  92  95  98 112 100 103  99\n                \"\"\".split(\n                    None\n                )\n            ]\n\n            standard_chrominance_qtable = [\n                int(s)\n                for s in \"\"\"\n                17  18  24  47  99  99  99  99\n                18  21  26  66  99  99  99  99\n                24  26  56  99  99  99  99  99\n                47  66  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                \"\"\".split(\n                    None\n                )\n            ]\n            # list of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables=[standard_l_qtable, standard_chrominance_qtable]\n                ),\n                30,\n            )\n\n            # tuple of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables=(standard_l_qtable, standard_chrominance_qtable)\n                ),\n                30,\n            )\n\n            # dict of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables={0: standard_l_qtable, 1: standard_chrominance_qtable}\n                ),\n                30,\n            )\n\n            _n_qtables_helper(1, \"Tests/images/hopper_gray.jpg\")\n            _n_qtables_helper(1, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(2, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(3, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(1, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(2, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(3, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(4, \"Tests/images/pil_sample_cmyk.jpg\")\n\n            # not a sequence\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=\"a\")\n            # sequence wrong length\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[])\n            # sequence wrong length\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[1, 2, 3, 4, 5])\n\n            # qtable entry not a sequence\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[1])\n            # qtable entry has wrong number of items\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[[1, 2, 3, 4]])\n\n    @pytest.mark.skipif(not djpeg_available(), reason=\"djpeg not available\")\n    def test_load_djpeg(self):\n        with Image.open(TEST_FILE) as img:\n            img.load_djpeg()\n            assert_image_similar(img, Image.open(TEST_FILE), 5)\n\n    @pytest.mark.skipif(not cjpeg_available(), reason=\"cjpeg not available\")\n    def test_save_cjpeg(self, tmp_path):\n        with Image.open(TEST_FILE) as img:\n            tempfile = str(tmp_path / \"temp.jpg\")\n            JpegImagePlugin._save_cjpeg(img, 0, tempfile)\n            # Default save quality is 75%, so a tiny bit of difference is alright\n            assert_image_similar(img, Image.open(tempfile), 17)\n\n    def test_no_duplicate_0x1001_tag(self):\n        # Arrange\n        tag_ids = {v: k for k, v in ExifTags.TAGS.items()}\n\n        # Assert\n        assert tag_ids[\"RelatedImageWidth\"] == 0x1001\n        assert tag_ids[\"RelatedImageLength\"] == 0x1002\n\n    def test_MAXBLOCK_scaling(self, tmp_path):\n        im = self.gen_random_image((512, 512))\n        f = str(tmp_path / \"temp.jpeg\")\n        im.save(f, quality=100, optimize=True)\n\n        with Image.open(f) as reloaded:\n            # none of these should crash\n            reloaded.save(f, quality=\"keep\")\n            reloaded.save(f, quality=\"keep\", progressive=True)\n            reloaded.save(f, quality=\"keep\", optimize=True)\n\n    def test_bad_mpo_header(self):\n        \"\"\" Treat unknown MPO as JPEG \"\"\"\n        # Arrange\n\n        # Act\n        # Shouldn't raise error\n        fn = \"Tests/images/sugarshack_bad_mpo_header.jpg\"\n        with pytest.warns(UserWarning, Image.open, fn) as im:\n\n            # Assert\n            assert im.format == \"JPEG\"\n\n    def test_save_correct_modes(self):\n        out = BytesIO()\n        for mode in [\"1\", \"L\", \"RGB\", \"RGBX\", \"CMYK\", \"YCbCr\"]:\n            img = Image.new(mode, (20, 20))\n            img.save(out, \"JPEG\")\n\n    def test_save_wrong_modes(self):\n        # ref https://github.com/python-pillow/Pillow/issues/2005\n        out = BytesIO()\n        for mode in [\"LA\", \"La\", \"RGBA\", \"RGBa\", \"P\"]:\n            img = Image.new(mode, (20, 20))\n            with pytest.raises(OSError):\n                img.save(out, \"JPEG\")\n\n    def test_save_tiff_with_dpi(self, tmp_path):\n        # Arrange\n        outfile = str(tmp_path / \"temp.tif\")\n        with Image.open(\"Tests/images/hopper.tif\") as im:\n\n            # Act\n            im.save(outfile, \"JPEG\", dpi=im.info[\"dpi\"])\n\n            # Assert\n            with Image.open(outfile) as reloaded:\n                reloaded.load()\n                assert im.info[\"dpi\"] == reloaded.info[\"dpi\"]\n\n    def test_load_dpi_rounding(self):\n        # Round up\n        with Image.open(\"Tests/images/iptc_roundUp.jpg\") as im:\n            assert im.info[\"dpi\"] == (44, 44)\n\n        # Round down\n        with Image.open(\"Tests/images/iptc_roundDown.jpg\") as im:\n            assert im.info[\"dpi\"] == (2, 2)\n\n    def test_save_dpi_rounding(self, tmp_path):\n        outfile = str(tmp_path / \"temp.jpg\")\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            im.save(outfile, dpi=(72.2, 72.2))\n\n            with Image.open(outfile) as reloaded:\n                assert reloaded.info[\"dpi\"] == (72, 72)\n\n            im.save(outfile, dpi=(72.8, 72.8))\n\n        with Image.open(outfile) as reloaded:\n            assert reloaded.info[\"dpi\"] == (73, 73)\n\n    def test_dpi_tuple_from_exif(self):\n        # Arrange\n        # This Photoshop CC 2017 image has DPI in EXIF not metadata\n        # EXIF XResolution is (2000000, 10000)\n        with Image.open(\"Tests/images/photoshop-200dpi.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (200, 200)\n\n    def test_dpi_int_from_exif(self):\n        # Arrange\n        # This image has DPI in EXIF not metadata\n        # EXIF XResolution is 72\n        with Image.open(\"Tests/images/exif-72dpi-int.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_dpi_from_dpcm_exif(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with EXIF resolution unit set to cm:\n        # exiftool -exif:ResolutionUnit=cm photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/exif-200dpcm.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (508, 508)\n\n    def test_dpi_exif_zero_division(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with EXIF resolution set to 0/0:\n        # exiftool -XResolution=0/0 -YResolution=0/0 photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/exif-dpi-zerodivision.jpg\") as im:\n\n            # Act / Assert\n            # This should return the default, and not raise a ZeroDivisionError\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_no_dpi_in_exif(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with resolution removed from EXIF:\n        # exiftool \"-*resolution*\"= photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/no-dpi-in-exif.jpg\") as im:\n\n            # Act / Assert\n            # \"When the image resolution is unknown, 72 [dpi] is designated.\"\n            # http://www.exiv2.org/tags.html\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_invalid_exif(self):\n        # This is no-dpi-in-exif with the tiff header of the exif block\n        # hexedited from MM * to FF FF FF FF\n        with Image.open(\"Tests/images/invalid-exif.jpg\") as im:\n\n            # This should return the default, and not a SyntaxError or\n            # OSError for unidentified image.\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_invalid_exif_x_resolution(self):\n        # When no x or y resolution is defined in EXIF\n        with Image.open(\"Tests/images/invalid-exif-without-x-resolution.jpg\") as im:\n\n            # This should return the default, and not a ValueError or\n            # OSError for an unidentified image.\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_ifd_offset_exif(self):\n        # Arrange\n        # This image has been manually hexedited to have an IFD offset of 10,\n        # in contrast to normal 8\n        with Image.open(\"Tests/images/exif-ifd-offset.jpg\") as im:\n\n            # Act / Assert\n            assert im._getexif()[306] == \"2017:03:13 23:03:09\"\n\n    def test_photoshop(self):\n        with Image.open(\"Tests/images/photoshop-200dpi.jpg\") as im:\n            assert im.info[\"photoshop\"][0x03ED] == {\n                \"XResolution\": 200.0,\n                \"DisplayedUnitsX\": 1,\n                \"YResolution\": 200.0,\n                \"DisplayedUnitsY\": 1,\n            }\n\n            # Test that the image can still load, even with broken Photoshop data\n            # This image had the APP13 length hexedited to be smaller\n            with Image.open(\"Tests/images/photoshop-200dpi-broken.jpg\") as im_broken:\n                assert_image_equal(im_broken, im)\n\n        # This image does not contain a Photoshop header string\n        with Image.open(\"Tests/images/app13.jpg\") as im:\n            assert \"photoshop\" not in im.info\n\n    def test_photoshop_malformed_and_multiple(self):\n        with Image.open(\"Tests/images/app13-multiple.jpg\") as im:\n            assert \"photoshop\" in im.info\n            assert 24 == len(im.info[\"photoshop\"])\n            apps_13_lengths = [len(v) for k, v in im.applist if k == \"APP13\"]\n            assert [65504, 24] == apps_13_lengths\n\n    def test_icc_after_SOF(self):\n        with Image.open(\"Tests/images/icc-after-SOF.jpg\") as im:\n            assert im.info[\"icc_profile\"] == b\"profile\"",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 234,
                            "end_lineno": 267,
                            "parent": {
                                "file_name": "Tests/test_file_jpeg.py",
                                "type": "class",
                                "name": "TestFileJpeg",
                                "content": "class TestFileJpeg:\n    def roundtrip(self, im, **options):\n        out = BytesIO()\n        im.save(out, \"JPEG\", **options)\n        test_bytes = out.tell()\n        out.seek(0)\n        im = Image.open(out)\n        im.bytes = test_bytes  # for testing only\n        return im\n\n    def gen_random_image(self, size, mode=\"RGB\"):\n        \"\"\" Generates a very hard to compress file\n        :param size: tuple\n        :param mode: optional image mode\n\n        \"\"\"\n        return Image.frombytes(mode, size, os.urandom(size[0] * size[1] * len(mode)))\n\n    def test_sanity(self):\n\n        # internal version number\n        assert re.search(r\"\\d+\\.\\d+$\", Image.core.jpeglib_version)\n\n        with Image.open(TEST_FILE) as im:\n            im.load()\n            assert im.mode == \"RGB\"\n            assert im.size == (128, 128)\n            assert im.format == \"JPEG\"\n            assert im.get_format_mimetype() == \"image/jpeg\"\n\n    def test_app(self):\n        # Test APP/COM reader (@PIL135)\n        with Image.open(TEST_FILE) as im:\n            assert im.applist[0] == (\"APP0\", b\"JFIF\\x00\\x01\\x01\\x01\\x00`\\x00`\\x00\\x00\")\n            assert im.applist[1] == (\n                \"COM\",\n                b\"File written by Adobe Photoshop\\xa8 4.0\\x00\",\n            )\n            assert len(im.applist) == 2\n\n            assert im.info[\"comment\"] == b\"File written by Adobe Photoshop\\xa8 4.0\\x00\"\n\n    def test_cmyk(self):\n        # Test CMYK handling.  Thanks to Tim and Charlie for test data,\n        # Michael for getting me to look one more time.\n        f = \"Tests/images/pil_sample_cmyk.jpg\"\n        with Image.open(f) as im:\n            # the source image has red pixels in the upper left corner.\n            c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))]\n            assert c == 0.0\n            assert m > 0.8\n            assert y > 0.8\n            assert k == 0.0\n            # the opposite corner is black\n            c, m, y, k = [\n                x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1))\n            ]\n            assert k > 0.9\n            # roundtrip, and check again\n            im = self.roundtrip(im)\n            c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))]\n            assert c == 0.0\n            assert m > 0.8\n            assert y > 0.8\n            assert k == 0.0\n            c, m, y, k = [\n                x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1))\n            ]\n            assert k > 0.9\n\n    def test_dpi(self):\n        def test(xdpi, ydpi=None):\n            with Image.open(TEST_FILE) as im:\n                im = self.roundtrip(im, dpi=(xdpi, ydpi or xdpi))\n            return im.info.get(\"dpi\")\n\n        assert test(72) == (72, 72)\n        assert test(300) == (300, 300)\n        assert test(100, 200) == (100, 200)\n        assert test(0) is None  # square pixels\n\n    def test_icc(self, tmp_path):\n        # Test ICC support\n        with Image.open(\"Tests/images/rgb.jpg\") as im1:\n            icc_profile = im1.info[\"icc_profile\"]\n            assert len(icc_profile) == 3144\n            # Roundtrip via physical file.\n            f = str(tmp_path / \"temp.jpg\")\n            im1.save(f, icc_profile=icc_profile)\n        with Image.open(f) as im2:\n            assert im2.info.get(\"icc_profile\") == icc_profile\n            # Roundtrip via memory buffer.\n            im1 = self.roundtrip(hopper())\n            im2 = self.roundtrip(hopper(), icc_profile=icc_profile)\n            assert_image_equal(im1, im2)\n            assert not im1.info.get(\"icc_profile\")\n            assert im2.info.get(\"icc_profile\")\n\n    def test_icc_big(self):\n        # Make sure that the \"extra\" support handles large blocks\n        def test(n):\n            # The ICC APP marker can store 65519 bytes per marker, so\n            # using a 4-byte test code should allow us to detect out of\n            # order issues.\n            icc_profile = (b\"Test\" * int(n / 4 + 1))[:n]\n            assert len(icc_profile) == n  # sanity\n            im1 = self.roundtrip(hopper(), icc_profile=icc_profile)\n            assert im1.info.get(\"icc_profile\") == (icc_profile or None)\n\n        test(0)\n        test(1)\n        test(3)\n        test(4)\n        test(5)\n        test(65533 - 14)  # full JPEG marker block\n        test(65533 - 14 + 1)  # full block plus one byte\n        test(ImageFile.MAXBLOCK)  # full buffer block\n        test(ImageFile.MAXBLOCK + 1)  # full buffer block plus one byte\n        test(ImageFile.MAXBLOCK * 4 + 3)  # large block\n\n    def test_large_icc_meta(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        # Sometimes the meta data on the icc_profile block is bigger than\n        # Image.MAXBLOCK or the image size.\n        with Image.open(\"Tests/images/icc_profile_big.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            icc_profile = im.info[\"icc_profile\"]\n            # Should not raise OSError for image with icc larger than image size.\n            im.save(\n                f,\n                format=\"JPEG\",\n                progressive=True,\n                quality=95,\n                icc_profile=icc_profile,\n                optimize=True,\n            )\n\n    def test_optimize(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), optimize=0)\n        im3 = self.roundtrip(hopper(), optimize=1)\n        assert_image_equal(im1, im2)\n        assert_image_equal(im1, im3)\n        assert im1.bytes >= im2.bytes\n        assert im1.bytes >= im3.bytes\n\n    def test_optimize_large_buffer(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        f = str(tmp_path / \"temp.jpg\")\n        # this requires ~ 1.5x Image.MAXBLOCK\n        im = Image.new(\"RGB\", (4096, 4096), 0xFF3333)\n        im.save(f, format=\"JPEG\", optimize=True)\n\n    def test_progressive(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), progressive=False)\n        im3 = self.roundtrip(hopper(), progressive=True)\n        assert not im1.info.get(\"progressive\")\n        assert not im2.info.get(\"progressive\")\n        assert im3.info.get(\"progressive\")\n\n        assert_image_equal(im1, im3)\n        assert im1.bytes >= im3.bytes\n\n    def test_progressive_large_buffer(self, tmp_path):\n        f = str(tmp_path / \"temp.jpg\")\n        # this requires ~ 1.5x Image.MAXBLOCK\n        im = Image.new(\"RGB\", (4096, 4096), 0xFF3333)\n        im.save(f, format=\"JPEG\", progressive=True)\n\n    def test_progressive_large_buffer_highest_quality(self, tmp_path):\n        f = str(tmp_path / \"temp.jpg\")\n        im = self.gen_random_image((255, 255))\n        # this requires more bytes than pixels in the image\n        im.save(f, format=\"JPEG\", progressive=True, quality=100)\n\n    def test_progressive_cmyk_buffer(self):\n        # Issue 2272, quality 90 cmyk image is tripping the large buffer bug.\n        f = BytesIO()\n        im = self.gen_random_image((256, 256), \"CMYK\")\n        im.save(f, format=\"JPEG\", progressive=True, quality=94)\n\n    def test_large_exif(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        f = str(tmp_path / \"temp.jpg\")\n        im = hopper()\n        im.save(f, \"JPEG\", quality=90, exif=b\"1\" * 65532)\n\n    def test_exif_typeerror(self):\n        with Image.open(\"Tests/images/exif_typeerror.jpg\") as im:\n            # Should not raise a TypeError\n            im._getexif()\n\n    def test_exif_gps(self):\n        # Arrange\n        with Image.open(\"Tests/images/exif_gps.jpg\") as im:\n            gps_index = 34853\n            expected_exif_gps = {\n                0: b\"\\x00\\x00\\x00\\x01\",\n                2: (4294967295, 1),\n                5: b\"\\x01\",\n                30: 65535,\n                29: \"1999:99:99 99:99:99\",\n            }\n\n            # Act\n            exif = im._getexif()\n\n        # Assert\n        assert exif[gps_index] == expected_exif_gps\n\n    def test_exif_rollback(self):\n        # rolling back exif support in 3.1 to pre-3.0 formatting.\n        # expected from 2.9, with b/u qualifiers switched for 3.2 compatibility\n        # this test passes on 2.9 and 3.1, but not 3.0\n        expected_exif = {\n            34867: 4294967295,\n            258: (24, 24, 24),\n            36867: \"2099:09:29 10:10:10\",\n            34853: {\n                0: b\"\\x00\\x00\\x00\\x01\",\n                2: (4294967295, 1),\n                5: b\"\\x01\",\n                30: 65535,\n                29: \"1999:99:99 99:99:99\",\n            },\n            296: 65535,\n            34665: 185,\n            41994: 65535,\n            514: 4294967295,\n            271: \"Make\",\n            272: \"XXX-XXX\",\n            305: \"PIL\",\n            42034: ((1, 1), (1, 1), (1, 1), (1, 1)),\n            42035: \"LensMake\",\n            34856: b\"\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa\",\n            282: (4294967295, 1),\n            33434: (4294967295, 1),\n        }\n\n        with Image.open(\"Tests/images/exif_gps.jpg\") as im:\n            exif = im._getexif()\n\n        for tag, value in expected_exif.items():\n            assert value == exif[tag]\n\n    def test_exif_gps_typeerror(self):\n        with Image.open(\"Tests/images/exif_gps_typeerror.jpg\") as im:\n\n            # Should not raise a TypeError\n            im._getexif()\n\n    def test_progressive_compat(self):\n        im1 = self.roundtrip(hopper())\n        assert not im1.info.get(\"progressive\")\n        assert not im1.info.get(\"progression\")\n\n        im2 = self.roundtrip(hopper(), progressive=0)\n        im3 = self.roundtrip(hopper(), progression=0)  # compatibility\n        assert not im2.info.get(\"progressive\")\n        assert not im2.info.get(\"progression\")\n        assert not im3.info.get(\"progressive\")\n        assert not im3.info.get(\"progression\")\n\n        im2 = self.roundtrip(hopper(), progressive=1)\n        im3 = self.roundtrip(hopper(), progression=1)  # compatibility\n        assert_image_equal(im1, im2)\n        assert_image_equal(im1, im3)\n        assert im2.info.get(\"progressive\")\n        assert im2.info.get(\"progression\")\n        assert im3.info.get(\"progressive\")\n        assert im3.info.get(\"progression\")\n\n    def test_quality(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), quality=50)\n        assert_image(im1, im2.mode, im2.size)\n        assert im1.bytes >= im2.bytes\n\n        im3 = self.roundtrip(hopper(), quality=0)\n        assert_image(im1, im3.mode, im3.size)\n        assert im2.bytes > im3.bytes\n\n    def test_smooth(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), smooth=100)\n        assert_image(im1, im2.mode, im2.size)\n\n    def test_subsampling(self):\n        def getsampling(im):\n            layer = im.layer\n            return layer[0][1:3] + layer[1][1:3] + layer[2][1:3]\n\n        # experimental API\n        im = self.roundtrip(hopper(), subsampling=-1)  # default\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=0)  # 4:4:4\n        assert getsampling(im) == (1, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=1)  # 4:2:2\n        assert getsampling(im) == (2, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=2)  # 4:2:0\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=3)  # default (undefined)\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n\n        im = self.roundtrip(hopper(), subsampling=\"4:4:4\")\n        assert getsampling(im) == (1, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:2:2\")\n        assert getsampling(im) == (2, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:2:0\")\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:1:1\")\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n\n        with pytest.raises(TypeError):\n            self.roundtrip(hopper(), subsampling=\"1:1:1\")\n\n    def test_exif(self):\n        with Image.open(\"Tests/images/pil_sample_rgb.jpg\") as im:\n            info = im._getexif()\n            assert info[305] == \"Adobe Photoshop CS Macintosh\"\n\n    def test_mp(self):\n        with Image.open(\"Tests/images/pil_sample_rgb.jpg\") as im:\n            assert im._getmp() is None\n\n    def test_quality_keep(self, tmp_path):\n        # RGB\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n        # Grayscale\n        with Image.open(\"Tests/images/hopper_gray.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n        # CMYK\n        with Image.open(\"Tests/images/pil_sample_cmyk.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n\n    def test_junk_jpeg_header(self):\n        # https://github.com/python-pillow/Pillow/issues/630\n        filename = \"Tests/images/junk_jpeg_header.jpg\"\n        with Image.open(filename):\n            pass\n\n    def test_ff00_jpeg_header(self):\n        filename = \"Tests/images/jpeg_ff00_header.jpg\"\n        with Image.open(filename):\n            pass\n\n    def test_truncated_jpeg_should_read_all_the_data(self):\n        filename = \"Tests/images/truncated_jpeg.jpg\"\n        ImageFile.LOAD_TRUNCATED_IMAGES = True\n        with Image.open(filename) as im:\n            im.load()\n            ImageFile.LOAD_TRUNCATED_IMAGES = False\n            assert im.getbbox() is not None\n\n    def test_truncated_jpeg_throws_oserror(self):\n        filename = \"Tests/images/truncated_jpeg.jpg\"\n        with Image.open(filename) as im:\n            with pytest.raises(OSError):\n                im.load()\n\n            # Test that the error is raised if loaded a second time\n            with pytest.raises(OSError):\n                im.load()\n\n    def test_qtables(self, tmp_path):\n        def _n_qtables_helper(n, test_file):\n            with Image.open(test_file) as im:\n                f = str(tmp_path / \"temp.jpg\")\n                im.save(f, qtables=[[n] * 64] * n)\n            with Image.open(f) as im:\n                assert len(im.quantization) == n\n                reloaded = self.roundtrip(im, qtables=\"keep\")\n                assert im.quantization == reloaded.quantization\n\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            qtables = im.quantization\n            reloaded = self.roundtrip(im, qtables=qtables, subsampling=0)\n            assert im.quantization == reloaded.quantization\n            assert_image_similar(im, self.roundtrip(im, qtables=\"web_low\"), 30)\n            assert_image_similar(im, self.roundtrip(im, qtables=\"web_high\"), 30)\n            assert_image_similar(im, self.roundtrip(im, qtables=\"keep\"), 30)\n\n            # valid bounds for baseline qtable\n            bounds_qtable = [int(s) for s in (\"255 1 \" * 32).split(None)]\n            self.roundtrip(im, qtables=[bounds_qtable])\n\n            # values from wizard.txt in jpeg9-a src package.\n            standard_l_qtable = [\n                int(s)\n                for s in \"\"\"\n                16  11  10  16  24  40  51  61\n                12  12  14  19  26  58  60  55\n                14  13  16  24  40  57  69  56\n                14  17  22  29  51  87  80  62\n                18  22  37  56  68 109 103  77\n                24  35  55  64  81 104 113  92\n                49  64  78  87 103 121 120 101\n                72  92  95  98 112 100 103  99\n                \"\"\".split(\n                    None\n                )\n            ]\n\n            standard_chrominance_qtable = [\n                int(s)\n                for s in \"\"\"\n                17  18  24  47  99  99  99  99\n                18  21  26  66  99  99  99  99\n                24  26  56  99  99  99  99  99\n                47  66  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                \"\"\".split(\n                    None\n                )\n            ]\n            # list of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables=[standard_l_qtable, standard_chrominance_qtable]\n                ),\n                30,\n            )\n\n            # tuple of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables=(standard_l_qtable, standard_chrominance_qtable)\n                ),\n                30,\n            )\n\n            # dict of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables={0: standard_l_qtable, 1: standard_chrominance_qtable}\n                ),\n                30,\n            )\n\n            _n_qtables_helper(1, \"Tests/images/hopper_gray.jpg\")\n            _n_qtables_helper(1, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(2, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(3, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(1, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(2, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(3, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(4, \"Tests/images/pil_sample_cmyk.jpg\")\n\n            # not a sequence\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=\"a\")\n            # sequence wrong length\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[])\n            # sequence wrong length\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[1, 2, 3, 4, 5])\n\n            # qtable entry not a sequence\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[1])\n            # qtable entry has wrong number of items\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[[1, 2, 3, 4]])\n\n    @pytest.mark.skipif(not djpeg_available(), reason=\"djpeg not available\")\n    def test_load_djpeg(self):\n        with Image.open(TEST_FILE) as img:\n            img.load_djpeg()\n            assert_image_similar(img, Image.open(TEST_FILE), 5)\n\n    @pytest.mark.skipif(not cjpeg_available(), reason=\"cjpeg not available\")\n    def test_save_cjpeg(self, tmp_path):\n        with Image.open(TEST_FILE) as img:\n            tempfile = str(tmp_path / \"temp.jpg\")\n            JpegImagePlugin._save_cjpeg(img, 0, tempfile)\n            # Default save quality is 75%, so a tiny bit of difference is alright\n            assert_image_similar(img, Image.open(tempfile), 17)\n\n    def test_no_duplicate_0x1001_tag(self):\n        # Arrange\n        tag_ids = {v: k for k, v in ExifTags.TAGS.items()}\n\n        # Assert\n        assert tag_ids[\"RelatedImageWidth\"] == 0x1001\n        assert tag_ids[\"RelatedImageLength\"] == 0x1002\n\n    def test_MAXBLOCK_scaling(self, tmp_path):\n        im = self.gen_random_image((512, 512))\n        f = str(tmp_path / \"temp.jpeg\")\n        im.save(f, quality=100, optimize=True)\n\n        with Image.open(f) as reloaded:\n            # none of these should crash\n            reloaded.save(f, quality=\"keep\")\n            reloaded.save(f, quality=\"keep\", progressive=True)\n            reloaded.save(f, quality=\"keep\", optimize=True)\n\n    def test_bad_mpo_header(self):\n        \"\"\" Treat unknown MPO as JPEG \"\"\"\n        # Arrange\n\n        # Act\n        # Shouldn't raise error\n        fn = \"Tests/images/sugarshack_bad_mpo_header.jpg\"\n        with pytest.warns(UserWarning, Image.open, fn) as im:\n\n            # Assert\n            assert im.format == \"JPEG\"\n\n    def test_save_correct_modes(self):\n        out = BytesIO()\n        for mode in [\"1\", \"L\", \"RGB\", \"RGBX\", \"CMYK\", \"YCbCr\"]:\n            img = Image.new(mode, (20, 20))\n            img.save(out, \"JPEG\")\n\n    def test_save_wrong_modes(self):\n        # ref https://github.com/python-pillow/Pillow/issues/2005\n        out = BytesIO()\n        for mode in [\"LA\", \"La\", \"RGBA\", \"RGBa\", \"P\"]:\n            img = Image.new(mode, (20, 20))\n            with pytest.raises(OSError):\n                img.save(out, \"JPEG\")\n\n    def test_save_tiff_with_dpi(self, tmp_path):\n        # Arrange\n        outfile = str(tmp_path / \"temp.tif\")\n        with Image.open(\"Tests/images/hopper.tif\") as im:\n\n            # Act\n            im.save(outfile, \"JPEG\", dpi=im.info[\"dpi\"])\n\n            # Assert\n            with Image.open(outfile) as reloaded:\n                reloaded.load()\n                assert im.info[\"dpi\"] == reloaded.info[\"dpi\"]\n\n    def test_load_dpi_rounding(self):\n        # Round up\n        with Image.open(\"Tests/images/iptc_roundUp.jpg\") as im:\n            assert im.info[\"dpi\"] == (44, 44)\n\n        # Round down\n        with Image.open(\"Tests/images/iptc_roundDown.jpg\") as im:\n            assert im.info[\"dpi\"] == (2, 2)\n\n    def test_save_dpi_rounding(self, tmp_path):\n        outfile = str(tmp_path / \"temp.jpg\")\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            im.save(outfile, dpi=(72.2, 72.2))\n\n            with Image.open(outfile) as reloaded:\n                assert reloaded.info[\"dpi\"] == (72, 72)\n\n            im.save(outfile, dpi=(72.8, 72.8))\n\n        with Image.open(outfile) as reloaded:\n            assert reloaded.info[\"dpi\"] == (73, 73)\n\n    def test_dpi_tuple_from_exif(self):\n        # Arrange\n        # This Photoshop CC 2017 image has DPI in EXIF not metadata\n        # EXIF XResolution is (2000000, 10000)\n        with Image.open(\"Tests/images/photoshop-200dpi.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (200, 200)\n\n    def test_dpi_int_from_exif(self):\n        # Arrange\n        # This image has DPI in EXIF not metadata\n        # EXIF XResolution is 72\n        with Image.open(\"Tests/images/exif-72dpi-int.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_dpi_from_dpcm_exif(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with EXIF resolution unit set to cm:\n        # exiftool -exif:ResolutionUnit=cm photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/exif-200dpcm.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (508, 508)\n\n    def test_dpi_exif_zero_division(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with EXIF resolution set to 0/0:\n        # exiftool -XResolution=0/0 -YResolution=0/0 photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/exif-dpi-zerodivision.jpg\") as im:\n\n            # Act / Assert\n            # This should return the default, and not raise a ZeroDivisionError\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_no_dpi_in_exif(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with resolution removed from EXIF:\n        # exiftool \"-*resolution*\"= photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/no-dpi-in-exif.jpg\") as im:\n\n            # Act / Assert\n            # \"When the image resolution is unknown, 72 [dpi] is designated.\"\n            # http://www.exiv2.org/tags.html\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_invalid_exif(self):\n        # This is no-dpi-in-exif with the tiff header of the exif block\n        # hexedited from MM * to FF FF FF FF\n        with Image.open(\"Tests/images/invalid-exif.jpg\") as im:\n\n            # This should return the default, and not a SyntaxError or\n            # OSError for unidentified image.\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_invalid_exif_x_resolution(self):\n        # When no x or y resolution is defined in EXIF\n        with Image.open(\"Tests/images/invalid-exif-without-x-resolution.jpg\") as im:\n\n            # This should return the default, and not a ValueError or\n            # OSError for an unidentified image.\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_ifd_offset_exif(self):\n        # Arrange\n        # This image has been manually hexedited to have an IFD offset of 10,\n        # in contrast to normal 8\n        with Image.open(\"Tests/images/exif-ifd-offset.jpg\") as im:\n\n            # Act / Assert\n            assert im._getexif()[306] == \"2017:03:13 23:03:09\"\n\n    def test_photoshop(self):\n        with Image.open(\"Tests/images/photoshop-200dpi.jpg\") as im:\n            assert im.info[\"photoshop\"][0x03ED] == {\n                \"XResolution\": 200.0,\n                \"DisplayedUnitsX\": 1,\n                \"YResolution\": 200.0,\n                \"DisplayedUnitsY\": 1,\n            }\n\n            # Test that the image can still load, even with broken Photoshop data\n            # This image had the APP13 length hexedited to be smaller\n            with Image.open(\"Tests/images/photoshop-200dpi-broken.jpg\") as im_broken:\n                assert_image_equal(im_broken, im)\n\n        # This image does not contain a Photoshop header string\n        with Image.open(\"Tests/images/app13.jpg\") as im:\n            assert \"photoshop\" not in im.info\n\n    def test_photoshop_malformed_and_multiple(self):\n        with Image.open(\"Tests/images/app13-multiple.jpg\") as im:\n            assert \"photoshop\" in im.info\n            assert 24 == len(im.info[\"photoshop\"])\n            apps_13_lengths = [len(v) for k, v in im.applist if k == \"APP13\"]\n            assert [65504, 24] == apps_13_lengths\n\n    def test_icc_after_SOF(self):\n        with Image.open(\"Tests/images/icc-after-SOF.jpg\") as im:\n            assert im.info[\"icc_profile\"] == b\"profile\"",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 23,
                                "end_lineno": 694,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "Tests/test_file_jpeg.py",
                            "type": "class",
                            "name": "TestFileJpeg",
                            "content": "class TestFileJpeg:\n    def roundtrip(self, im, **options):\n        out = BytesIO()\n        im.save(out, \"JPEG\", **options)\n        test_bytes = out.tell()\n        out.seek(0)\n        im = Image.open(out)\n        im.bytes = test_bytes  # for testing only\n        return im\n\n    def gen_random_image(self, size, mode=\"RGB\"):\n        \"\"\" Generates a very hard to compress file\n        :param size: tuple\n        :param mode: optional image mode\n\n        \"\"\"\n        return Image.frombytes(mode, size, os.urandom(size[0] * size[1] * len(mode)))\n\n    def test_sanity(self):\n\n        # internal version number\n        assert re.search(r\"\\d+\\.\\d+$\", Image.core.jpeglib_version)\n\n        with Image.open(TEST_FILE) as im:\n            im.load()\n            assert im.mode == \"RGB\"\n            assert im.size == (128, 128)\n            assert im.format == \"JPEG\"\n            assert im.get_format_mimetype() == \"image/jpeg\"\n\n    def test_app(self):\n        # Test APP/COM reader (@PIL135)\n        with Image.open(TEST_FILE) as im:\n            assert im.applist[0] == (\"APP0\", b\"JFIF\\x00\\x01\\x01\\x01\\x00`\\x00`\\x00\\x00\")\n            assert im.applist[1] == (\n                \"COM\",\n                b\"File written by Adobe Photoshop\\xa8 4.0\\x00\",\n            )\n            assert len(im.applist) == 2\n\n            assert im.info[\"comment\"] == b\"File written by Adobe Photoshop\\xa8 4.0\\x00\"\n\n    def test_cmyk(self):\n        # Test CMYK handling.  Thanks to Tim and Charlie for test data,\n        # Michael for getting me to look one more time.\n        f = \"Tests/images/pil_sample_cmyk.jpg\"\n        with Image.open(f) as im:\n            # the source image has red pixels in the upper left corner.\n            c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))]\n            assert c == 0.0\n            assert m > 0.8\n            assert y > 0.8\n            assert k == 0.0\n            # the opposite corner is black\n            c, m, y, k = [\n                x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1))\n            ]\n            assert k > 0.9\n            # roundtrip, and check again\n            im = self.roundtrip(im)\n            c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))]\n            assert c == 0.0\n            assert m > 0.8\n            assert y > 0.8\n            assert k == 0.0\n            c, m, y, k = [\n                x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1))\n            ]\n            assert k > 0.9\n\n    def test_dpi(self):\n        def test(xdpi, ydpi=None):\n            with Image.open(TEST_FILE) as im:\n                im = self.roundtrip(im, dpi=(xdpi, ydpi or xdpi))\n            return im.info.get(\"dpi\")\n\n        assert test(72) == (72, 72)\n        assert test(300) == (300, 300)\n        assert test(100, 200) == (100, 200)\n        assert test(0) is None  # square pixels\n\n    def test_icc(self, tmp_path):\n        # Test ICC support\n        with Image.open(\"Tests/images/rgb.jpg\") as im1:\n            icc_profile = im1.info[\"icc_profile\"]\n            assert len(icc_profile) == 3144\n            # Roundtrip via physical file.\n            f = str(tmp_path / \"temp.jpg\")\n            im1.save(f, icc_profile=icc_profile)\n        with Image.open(f) as im2:\n            assert im2.info.get(\"icc_profile\") == icc_profile\n            # Roundtrip via memory buffer.\n            im1 = self.roundtrip(hopper())\n            im2 = self.roundtrip(hopper(), icc_profile=icc_profile)\n            assert_image_equal(im1, im2)\n            assert not im1.info.get(\"icc_profile\")\n            assert im2.info.get(\"icc_profile\")\n\n    def test_icc_big(self):\n        # Make sure that the \"extra\" support handles large blocks\n        def test(n):\n            # The ICC APP marker can store 65519 bytes per marker, so\n            # using a 4-byte test code should allow us to detect out of\n            # order issues.\n            icc_profile = (b\"Test\" * int(n / 4 + 1))[:n]\n            assert len(icc_profile) == n  # sanity\n            im1 = self.roundtrip(hopper(), icc_profile=icc_profile)\n            assert im1.info.get(\"icc_profile\") == (icc_profile or None)\n\n        test(0)\n        test(1)\n        test(3)\n        test(4)\n        test(5)\n        test(65533 - 14)  # full JPEG marker block\n        test(65533 - 14 + 1)  # full block plus one byte\n        test(ImageFile.MAXBLOCK)  # full buffer block\n        test(ImageFile.MAXBLOCK + 1)  # full buffer block plus one byte\n        test(ImageFile.MAXBLOCK * 4 + 3)  # large block\n\n    def test_large_icc_meta(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        # Sometimes the meta data on the icc_profile block is bigger than\n        # Image.MAXBLOCK or the image size.\n        with Image.open(\"Tests/images/icc_profile_big.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            icc_profile = im.info[\"icc_profile\"]\n            # Should not raise OSError for image with icc larger than image size.\n            im.save(\n                f,\n                format=\"JPEG\",\n                progressive=True,\n                quality=95,\n                icc_profile=icc_profile,\n                optimize=True,\n            )\n\n    def test_optimize(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), optimize=0)\n        im3 = self.roundtrip(hopper(), optimize=1)\n        assert_image_equal(im1, im2)\n        assert_image_equal(im1, im3)\n        assert im1.bytes >= im2.bytes\n        assert im1.bytes >= im3.bytes\n\n    def test_optimize_large_buffer(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        f = str(tmp_path / \"temp.jpg\")\n        # this requires ~ 1.5x Image.MAXBLOCK\n        im = Image.new(\"RGB\", (4096, 4096), 0xFF3333)\n        im.save(f, format=\"JPEG\", optimize=True)\n\n    def test_progressive(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), progressive=False)\n        im3 = self.roundtrip(hopper(), progressive=True)\n        assert not im1.info.get(\"progressive\")\n        assert not im2.info.get(\"progressive\")\n        assert im3.info.get(\"progressive\")\n\n        assert_image_equal(im1, im3)\n        assert im1.bytes >= im3.bytes\n\n    def test_progressive_large_buffer(self, tmp_path):\n        f = str(tmp_path / \"temp.jpg\")\n        # this requires ~ 1.5x Image.MAXBLOCK\n        im = Image.new(\"RGB\", (4096, 4096), 0xFF3333)\n        im.save(f, format=\"JPEG\", progressive=True)\n\n    def test_progressive_large_buffer_highest_quality(self, tmp_path):\n        f = str(tmp_path / \"temp.jpg\")\n        im = self.gen_random_image((255, 255))\n        # this requires more bytes than pixels in the image\n        im.save(f, format=\"JPEG\", progressive=True, quality=100)\n\n    def test_progressive_cmyk_buffer(self):\n        # Issue 2272, quality 90 cmyk image is tripping the large buffer bug.\n        f = BytesIO()\n        im = self.gen_random_image((256, 256), \"CMYK\")\n        im.save(f, format=\"JPEG\", progressive=True, quality=94)\n\n    def test_large_exif(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        f = str(tmp_path / \"temp.jpg\")\n        im = hopper()\n        im.save(f, \"JPEG\", quality=90, exif=b\"1\" * 65532)\n\n    def test_exif_typeerror(self):\n        with Image.open(\"Tests/images/exif_typeerror.jpg\") as im:\n            # Should not raise a TypeError\n            im._getexif()\n\n    def test_exif_gps(self):\n        # Arrange\n        with Image.open(\"Tests/images/exif_gps.jpg\") as im:\n            gps_index = 34853\n            expected_exif_gps = {\n                0: b\"\\x00\\x00\\x00\\x01\",\n                2: (4294967295, 1),\n                5: b\"\\x01\",\n                30: 65535,\n                29: \"1999:99:99 99:99:99\",\n            }\n\n            # Act\n            exif = im._getexif()\n\n        # Assert\n        assert exif[gps_index] == expected_exif_gps\n\n    def test_exif_rollback(self):\n        # rolling back exif support in 3.1 to pre-3.0 formatting.\n        # expected from 2.9, with b/u qualifiers switched for 3.2 compatibility\n        # this test passes on 2.9 and 3.1, but not 3.0\n        expected_exif = {\n            34867: 4294967295,\n            258: (24, 24, 24),\n            36867: \"2099:09:29 10:10:10\",\n            34853: {\n                0: b\"\\x00\\x00\\x00\\x01\",\n                2: (4294967295, 1),\n                5: b\"\\x01\",\n                30: 65535,\n                29: \"1999:99:99 99:99:99\",\n            },\n            296: 65535,\n            34665: 185,\n            41994: 65535,\n            514: 4294967295,\n            271: \"Make\",\n            272: \"XXX-XXX\",\n            305: \"PIL\",\n            42034: ((1, 1), (1, 1), (1, 1), (1, 1)),\n            42035: \"LensMake\",\n            34856: b\"\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa\",\n            282: (4294967295, 1),\n            33434: (4294967295, 1),\n        }\n\n        with Image.open(\"Tests/images/exif_gps.jpg\") as im:\n            exif = im._getexif()\n\n        for tag, value in expected_exif.items():\n            assert value == exif[tag]\n\n    def test_exif_gps_typeerror(self):\n        with Image.open(\"Tests/images/exif_gps_typeerror.jpg\") as im:\n\n            # Should not raise a TypeError\n            im._getexif()\n\n    def test_progressive_compat(self):\n        im1 = self.roundtrip(hopper())\n        assert not im1.info.get(\"progressive\")\n        assert not im1.info.get(\"progression\")\n\n        im2 = self.roundtrip(hopper(), progressive=0)\n        im3 = self.roundtrip(hopper(), progression=0)  # compatibility\n        assert not im2.info.get(\"progressive\")\n        assert not im2.info.get(\"progression\")\n        assert not im3.info.get(\"progressive\")\n        assert not im3.info.get(\"progression\")\n\n        im2 = self.roundtrip(hopper(), progressive=1)\n        im3 = self.roundtrip(hopper(), progression=1)  # compatibility\n        assert_image_equal(im1, im2)\n        assert_image_equal(im1, im3)\n        assert im2.info.get(\"progressive\")\n        assert im2.info.get(\"progression\")\n        assert im3.info.get(\"progressive\")\n        assert im3.info.get(\"progression\")\n\n    def test_quality(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), quality=50)\n        assert_image(im1, im2.mode, im2.size)\n        assert im1.bytes >= im2.bytes\n\n        im3 = self.roundtrip(hopper(), quality=0)\n        assert_image(im1, im3.mode, im3.size)\n        assert im2.bytes > im3.bytes\n\n    def test_smooth(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), smooth=100)\n        assert_image(im1, im2.mode, im2.size)\n\n    def test_subsampling(self):\n        def getsampling(im):\n            layer = im.layer\n            return layer[0][1:3] + layer[1][1:3] + layer[2][1:3]\n\n        # experimental API\n        im = self.roundtrip(hopper(), subsampling=-1)  # default\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=0)  # 4:4:4\n        assert getsampling(im) == (1, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=1)  # 4:2:2\n        assert getsampling(im) == (2, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=2)  # 4:2:0\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=3)  # default (undefined)\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n\n        im = self.roundtrip(hopper(), subsampling=\"4:4:4\")\n        assert getsampling(im) == (1, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:2:2\")\n        assert getsampling(im) == (2, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:2:0\")\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:1:1\")\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n\n        with pytest.raises(TypeError):\n            self.roundtrip(hopper(), subsampling=\"1:1:1\")\n\n    def test_exif(self):\n        with Image.open(\"Tests/images/pil_sample_rgb.jpg\") as im:\n            info = im._getexif()\n            assert info[305] == \"Adobe Photoshop CS Macintosh\"\n\n    def test_mp(self):\n        with Image.open(\"Tests/images/pil_sample_rgb.jpg\") as im:\n            assert im._getmp() is None\n\n    def test_quality_keep(self, tmp_path):\n        # RGB\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n        # Grayscale\n        with Image.open(\"Tests/images/hopper_gray.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n        # CMYK\n        with Image.open(\"Tests/images/pil_sample_cmyk.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n\n    def test_junk_jpeg_header(self):\n        # https://github.com/python-pillow/Pillow/issues/630\n        filename = \"Tests/images/junk_jpeg_header.jpg\"\n        with Image.open(filename):\n            pass\n\n    def test_ff00_jpeg_header(self):\n        filename = \"Tests/images/jpeg_ff00_header.jpg\"\n        with Image.open(filename):\n            pass\n\n    def test_truncated_jpeg_should_read_all_the_data(self):\n        filename = \"Tests/images/truncated_jpeg.jpg\"\n        ImageFile.LOAD_TRUNCATED_IMAGES = True\n        with Image.open(filename) as im:\n            im.load()\n            ImageFile.LOAD_TRUNCATED_IMAGES = False\n            assert im.getbbox() is not None\n\n    def test_truncated_jpeg_throws_oserror(self):\n        filename = \"Tests/images/truncated_jpeg.jpg\"\n        with Image.open(filename) as im:\n            with pytest.raises(OSError):\n                im.load()\n\n            # Test that the error is raised if loaded a second time\n            with pytest.raises(OSError):\n                im.load()\n\n    def test_qtables(self, tmp_path):\n        def _n_qtables_helper(n, test_file):\n            with Image.open(test_file) as im:\n                f = str(tmp_path / \"temp.jpg\")\n                im.save(f, qtables=[[n] * 64] * n)\n            with Image.open(f) as im:\n                assert len(im.quantization) == n\n                reloaded = self.roundtrip(im, qtables=\"keep\")\n                assert im.quantization == reloaded.quantization\n\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            qtables = im.quantization\n            reloaded = self.roundtrip(im, qtables=qtables, subsampling=0)\n            assert im.quantization == reloaded.quantization\n            assert_image_similar(im, self.roundtrip(im, qtables=\"web_low\"), 30)\n            assert_image_similar(im, self.roundtrip(im, qtables=\"web_high\"), 30)\n            assert_image_similar(im, self.roundtrip(im, qtables=\"keep\"), 30)\n\n            # valid bounds for baseline qtable\n            bounds_qtable = [int(s) for s in (\"255 1 \" * 32).split(None)]\n            self.roundtrip(im, qtables=[bounds_qtable])\n\n            # values from wizard.txt in jpeg9-a src package.\n            standard_l_qtable = [\n                int(s)\n                for s in \"\"\"\n                16  11  10  16  24  40  51  61\n                12  12  14  19  26  58  60  55\n                14  13  16  24  40  57  69  56\n                14  17  22  29  51  87  80  62\n                18  22  37  56  68 109 103  77\n                24  35  55  64  81 104 113  92\n                49  64  78  87 103 121 120 101\n                72  92  95  98 112 100 103  99\n                \"\"\".split(\n                    None\n                )\n            ]\n\n            standard_chrominance_qtable = [\n                int(s)\n                for s in \"\"\"\n                17  18  24  47  99  99  99  99\n                18  21  26  66  99  99  99  99\n                24  26  56  99  99  99  99  99\n                47  66  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                \"\"\".split(\n                    None\n                )\n            ]\n            # list of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables=[standard_l_qtable, standard_chrominance_qtable]\n                ),\n                30,\n            )\n\n            # tuple of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables=(standard_l_qtable, standard_chrominance_qtable)\n                ),\n                30,\n            )\n\n            # dict of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables={0: standard_l_qtable, 1: standard_chrominance_qtable}\n                ),\n                30,\n            )\n\n            _n_qtables_helper(1, \"Tests/images/hopper_gray.jpg\")\n            _n_qtables_helper(1, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(2, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(3, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(1, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(2, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(3, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(4, \"Tests/images/pil_sample_cmyk.jpg\")\n\n            # not a sequence\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=\"a\")\n            # sequence wrong length\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[])\n            # sequence wrong length\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[1, 2, 3, 4, 5])\n\n            # qtable entry not a sequence\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[1])\n            # qtable entry has wrong number of items\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[[1, 2, 3, 4]])\n\n    @pytest.mark.skipif(not djpeg_available(), reason=\"djpeg not available\")\n    def test_load_djpeg(self):\n        with Image.open(TEST_FILE) as img:\n            img.load_djpeg()\n            assert_image_similar(img, Image.open(TEST_FILE), 5)\n\n    @pytest.mark.skipif(not cjpeg_available(), reason=\"cjpeg not available\")\n    def test_save_cjpeg(self, tmp_path):\n        with Image.open(TEST_FILE) as img:\n            tempfile = str(tmp_path / \"temp.jpg\")\n            JpegImagePlugin._save_cjpeg(img, 0, tempfile)\n            # Default save quality is 75%, so a tiny bit of difference is alright\n            assert_image_similar(img, Image.open(tempfile), 17)\n\n    def test_no_duplicate_0x1001_tag(self):\n        # Arrange\n        tag_ids = {v: k for k, v in ExifTags.TAGS.items()}\n\n        # Assert\n        assert tag_ids[\"RelatedImageWidth\"] == 0x1001\n        assert tag_ids[\"RelatedImageLength\"] == 0x1002\n\n    def test_MAXBLOCK_scaling(self, tmp_path):\n        im = self.gen_random_image((512, 512))\n        f = str(tmp_path / \"temp.jpeg\")\n        im.save(f, quality=100, optimize=True)\n\n        with Image.open(f) as reloaded:\n            # none of these should crash\n            reloaded.save(f, quality=\"keep\")\n            reloaded.save(f, quality=\"keep\", progressive=True)\n            reloaded.save(f, quality=\"keep\", optimize=True)\n\n    def test_bad_mpo_header(self):\n        \"\"\" Treat unknown MPO as JPEG \"\"\"\n        # Arrange\n\n        # Act\n        # Shouldn't raise error\n        fn = \"Tests/images/sugarshack_bad_mpo_header.jpg\"\n        with pytest.warns(UserWarning, Image.open, fn) as im:\n\n            # Assert\n            assert im.format == \"JPEG\"\n\n    def test_save_correct_modes(self):\n        out = BytesIO()\n        for mode in [\"1\", \"L\", \"RGB\", \"RGBX\", \"CMYK\", \"YCbCr\"]:\n            img = Image.new(mode, (20, 20))\n            img.save(out, \"JPEG\")\n\n    def test_save_wrong_modes(self):\n        # ref https://github.com/python-pillow/Pillow/issues/2005\n        out = BytesIO()\n        for mode in [\"LA\", \"La\", \"RGBA\", \"RGBa\", \"P\"]:\n            img = Image.new(mode, (20, 20))\n            with pytest.raises(OSError):\n                img.save(out, \"JPEG\")\n\n    def test_save_tiff_with_dpi(self, tmp_path):\n        # Arrange\n        outfile = str(tmp_path / \"temp.tif\")\n        with Image.open(\"Tests/images/hopper.tif\") as im:\n\n            # Act\n            im.save(outfile, \"JPEG\", dpi=im.info[\"dpi\"])\n\n            # Assert\n            with Image.open(outfile) as reloaded:\n                reloaded.load()\n                assert im.info[\"dpi\"] == reloaded.info[\"dpi\"]\n\n    def test_load_dpi_rounding(self):\n        # Round up\n        with Image.open(\"Tests/images/iptc_roundUp.jpg\") as im:\n            assert im.info[\"dpi\"] == (44, 44)\n\n        # Round down\n        with Image.open(\"Tests/images/iptc_roundDown.jpg\") as im:\n            assert im.info[\"dpi\"] == (2, 2)\n\n    def test_save_dpi_rounding(self, tmp_path):\n        outfile = str(tmp_path / \"temp.jpg\")\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            im.save(outfile, dpi=(72.2, 72.2))\n\n            with Image.open(outfile) as reloaded:\n                assert reloaded.info[\"dpi\"] == (72, 72)\n\n            im.save(outfile, dpi=(72.8, 72.8))\n\n        with Image.open(outfile) as reloaded:\n            assert reloaded.info[\"dpi\"] == (73, 73)\n\n    def test_dpi_tuple_from_exif(self):\n        # Arrange\n        # This Photoshop CC 2017 image has DPI in EXIF not metadata\n        # EXIF XResolution is (2000000, 10000)\n        with Image.open(\"Tests/images/photoshop-200dpi.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (200, 200)\n\n    def test_dpi_int_from_exif(self):\n        # Arrange\n        # This image has DPI in EXIF not metadata\n        # EXIF XResolution is 72\n        with Image.open(\"Tests/images/exif-72dpi-int.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_dpi_from_dpcm_exif(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with EXIF resolution unit set to cm:\n        # exiftool -exif:ResolutionUnit=cm photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/exif-200dpcm.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (508, 508)\n\n    def test_dpi_exif_zero_division(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with EXIF resolution set to 0/0:\n        # exiftool -XResolution=0/0 -YResolution=0/0 photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/exif-dpi-zerodivision.jpg\") as im:\n\n            # Act / Assert\n            # This should return the default, and not raise a ZeroDivisionError\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_no_dpi_in_exif(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with resolution removed from EXIF:\n        # exiftool \"-*resolution*\"= photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/no-dpi-in-exif.jpg\") as im:\n\n            # Act / Assert\n            # \"When the image resolution is unknown, 72 [dpi] is designated.\"\n            # http://www.exiv2.org/tags.html\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_invalid_exif(self):\n        # This is no-dpi-in-exif with the tiff header of the exif block\n        # hexedited from MM * to FF FF FF FF\n        with Image.open(\"Tests/images/invalid-exif.jpg\") as im:\n\n            # This should return the default, and not a SyntaxError or\n            # OSError for unidentified image.\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_invalid_exif_x_resolution(self):\n        # When no x or y resolution is defined in EXIF\n        with Image.open(\"Tests/images/invalid-exif-without-x-resolution.jpg\") as im:\n\n            # This should return the default, and not a ValueError or\n            # OSError for an unidentified image.\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_ifd_offset_exif(self):\n        # Arrange\n        # This image has been manually hexedited to have an IFD offset of 10,\n        # in contrast to normal 8\n        with Image.open(\"Tests/images/exif-ifd-offset.jpg\") as im:\n\n            # Act / Assert\n            assert im._getexif()[306] == \"2017:03:13 23:03:09\"\n\n    def test_photoshop(self):\n        with Image.open(\"Tests/images/photoshop-200dpi.jpg\") as im:\n            assert im.info[\"photoshop\"][0x03ED] == {\n                \"XResolution\": 200.0,\n                \"DisplayedUnitsX\": 1,\n                \"YResolution\": 200.0,\n                \"DisplayedUnitsY\": 1,\n            }\n\n            # Test that the image can still load, even with broken Photoshop data\n            # This image had the APP13 length hexedited to be smaller\n            with Image.open(\"Tests/images/photoshop-200dpi-broken.jpg\") as im_broken:\n                assert_image_equal(im_broken, im)\n\n        # This image does not contain a Photoshop header string\n        with Image.open(\"Tests/images/app13.jpg\") as im:\n            assert \"photoshop\" not in im.info\n\n    def test_photoshop_malformed_and_multiple(self):\n        with Image.open(\"Tests/images/app13-multiple.jpg\") as im:\n            assert \"photoshop\" in im.info\n            assert 24 == len(im.info[\"photoshop\"])\n            apps_13_lengths = [len(v) for k, v in im.applist if k == \"APP13\"]\n            assert [65504, 24] == apps_13_lengths\n\n    def test_icc_after_SOF(self):\n        with Image.open(\"Tests/images/icc-after-SOF.jpg\") as im:\n            assert im.info[\"icc_profile\"] == b\"profile\"",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 23,
                            "end_lineno": 694,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 253,
                            "length": 11
                        },
                        "new_range": {
                            "start": 253,
                            "length": 11
                        },
                        "section": "class TestFileJpeg:"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "            271: \"Make\",",
                                "type": "context"
                            },
                            {
                                "content": "            272: \"XXX-XXX\",",
                                "type": "context"
                            },
                            {
                                "content": "            305: \"PIL\",",
                                "type": "context"
                            },
                            {
                                "content": "            42034: ((1, 1), (1, 1), (1, 1), (1, 1)),",
                                "type": "deleted"
                            },
                            {
                                "content": "            42034: (1, 1, 1, 1),",
                                "type": "added"
                            },
                            {
                                "content": "            42035: \"LensMake\",",
                                "type": "context"
                            },
                            {
                                "content": "            34856: b\"\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa\",",
                                "type": "context"
                            },
                            {
                                "content": "            282: (4294967295, 1),",
                                "type": "deleted"
                            },
                            {
                                "content": "            33434: (4294967295, 1),",
                                "type": "deleted"
                            },
                            {
                                "content": "            282: 4294967295,",
                                "type": "added"
                            },
                            {
                                "content": "            33434: 4294967295,",
                                "type": "added"
                            },
                            {
                                "content": "        }",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        with Image.open(\"Tests/images/exif_gps.jpg\") as im:",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Tests/test_file_jpeg.py",
                            "type": "method",
                            "name": "TestFileJpeg.test_exif_rollback",
                            "content": "class TestFileJpeg:\n    def roundtrip(self, im, **options):\n        out = BytesIO()\n        im.save(out, \"JPEG\", **options)\n        test_bytes = out.tell()\n        out.seek(0)\n        im = Image.open(out)\n        im.bytes = test_bytes  # for testing only\n        return im\n\n    def gen_random_image(self, size, mode=\"RGB\"):\n        \"\"\" Generates a very hard to compress file\n        :param size: tuple\n        :param mode: optional image mode\n\n        \"\"\"\n        return Image.frombytes(mode, size, os.urandom(size[0] * size[1] * len(mode)))\n\n    def test_sanity(self):\n\n        # internal version number\n        assert re.search(r\"\\d+\\.\\d+$\", Image.core.jpeglib_version)\n\n        with Image.open(TEST_FILE) as im:\n            im.load()\n            assert im.mode == \"RGB\"\n            assert im.size == (128, 128)\n            assert im.format == \"JPEG\"\n            assert im.get_format_mimetype() == \"image/jpeg\"\n\n    def test_app(self):\n        # Test APP/COM reader (@PIL135)\n        with Image.open(TEST_FILE) as im:\n            assert im.applist[0] == (\"APP0\", b\"JFIF\\x00\\x01\\x01\\x01\\x00`\\x00`\\x00\\x00\")\n            assert im.applist[1] == (\n                \"COM\",\n                b\"File written by Adobe Photoshop\\xa8 4.0\\x00\",\n            )\n            assert len(im.applist) == 2\n\n            assert im.info[\"comment\"] == b\"File written by Adobe Photoshop\\xa8 4.0\\x00\"\n\n    def test_cmyk(self):\n        # Test CMYK handling.  Thanks to Tim and Charlie for test data,\n        # Michael for getting me to look one more time.\n        f = \"Tests/images/pil_sample_cmyk.jpg\"\n        with Image.open(f) as im:\n            # the source image has red pixels in the upper left corner.\n            c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))]\n            assert c == 0.0\n            assert m > 0.8\n            assert y > 0.8\n            assert k == 0.0\n            # the opposite corner is black\n            c, m, y, k = [\n                x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1))\n            ]\n            assert k > 0.9\n            # roundtrip, and check again\n            im = self.roundtrip(im)\n            c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))]\n            assert c == 0.0\n            assert m > 0.8\n            assert y > 0.8\n            assert k == 0.0\n            c, m, y, k = [\n                x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1))\n            ]\n            assert k > 0.9\n\n    def test_dpi(self):\n        def test(xdpi, ydpi=None):\n            with Image.open(TEST_FILE) as im:\n                im = self.roundtrip(im, dpi=(xdpi, ydpi or xdpi))\n            return im.info.get(\"dpi\")\n\n        assert test(72) == (72, 72)\n        assert test(300) == (300, 300)\n        assert test(100, 200) == (100, 200)\n        assert test(0) is None  # square pixels\n\n    def test_icc(self, tmp_path):\n        # Test ICC support\n        with Image.open(\"Tests/images/rgb.jpg\") as im1:\n            icc_profile = im1.info[\"icc_profile\"]\n            assert len(icc_profile) == 3144\n            # Roundtrip via physical file.\n            f = str(tmp_path / \"temp.jpg\")\n            im1.save(f, icc_profile=icc_profile)\n        with Image.open(f) as im2:\n            assert im2.info.get(\"icc_profile\") == icc_profile\n            # Roundtrip via memory buffer.\n            im1 = self.roundtrip(hopper())\n            im2 = self.roundtrip(hopper(), icc_profile=icc_profile)\n            assert_image_equal(im1, im2)\n            assert not im1.info.get(\"icc_profile\")\n            assert im2.info.get(\"icc_profile\")\n\n    def test_icc_big(self):\n        # Make sure that the \"extra\" support handles large blocks\n        def test(n):\n            # The ICC APP marker can store 65519 bytes per marker, so\n            # using a 4-byte test code should allow us to detect out of\n            # order issues.\n            icc_profile = (b\"Test\" * int(n / 4 + 1))[:n]\n            assert len(icc_profile) == n  # sanity\n            im1 = self.roundtrip(hopper(), icc_profile=icc_profile)\n            assert im1.info.get(\"icc_profile\") == (icc_profile or None)\n\n        test(0)\n        test(1)\n        test(3)\n        test(4)\n        test(5)\n        test(65533 - 14)  # full JPEG marker block\n        test(65533 - 14 + 1)  # full block plus one byte\n        test(ImageFile.MAXBLOCK)  # full buffer block\n        test(ImageFile.MAXBLOCK + 1)  # full buffer block plus one byte\n        test(ImageFile.MAXBLOCK * 4 + 3)  # large block\n\n    def test_large_icc_meta(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        # Sometimes the meta data on the icc_profile block is bigger than\n        # Image.MAXBLOCK or the image size.\n        with Image.open(\"Tests/images/icc_profile_big.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            icc_profile = im.info[\"icc_profile\"]\n            # Should not raise OSError for image with icc larger than image size.\n            im.save(\n                f,\n                format=\"JPEG\",\n                progressive=True,\n                quality=95,\n                icc_profile=icc_profile,\n                optimize=True,\n            )\n\n    def test_optimize(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), optimize=0)\n        im3 = self.roundtrip(hopper(), optimize=1)\n        assert_image_equal(im1, im2)\n        assert_image_equal(im1, im3)\n        assert im1.bytes >= im2.bytes\n        assert im1.bytes >= im3.bytes\n\n    def test_optimize_large_buffer(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        f = str(tmp_path / \"temp.jpg\")\n        # this requires ~ 1.5x Image.MAXBLOCK\n        im = Image.new(\"RGB\", (4096, 4096), 0xFF3333)\n        im.save(f, format=\"JPEG\", optimize=True)\n\n    def test_progressive(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), progressive=False)\n        im3 = self.roundtrip(hopper(), progressive=True)\n        assert not im1.info.get(\"progressive\")\n        assert not im2.info.get(\"progressive\")\n        assert im3.info.get(\"progressive\")\n\n        assert_image_equal(im1, im3)\n        assert im1.bytes >= im3.bytes\n\n    def test_progressive_large_buffer(self, tmp_path):\n        f = str(tmp_path / \"temp.jpg\")\n        # this requires ~ 1.5x Image.MAXBLOCK\n        im = Image.new(\"RGB\", (4096, 4096), 0xFF3333)\n        im.save(f, format=\"JPEG\", progressive=True)\n\n    def test_progressive_large_buffer_highest_quality(self, tmp_path):\n        f = str(tmp_path / \"temp.jpg\")\n        im = self.gen_random_image((255, 255))\n        # this requires more bytes than pixels in the image\n        im.save(f, format=\"JPEG\", progressive=True, quality=100)\n\n    def test_progressive_cmyk_buffer(self):\n        # Issue 2272, quality 90 cmyk image is tripping the large buffer bug.\n        f = BytesIO()\n        im = self.gen_random_image((256, 256), \"CMYK\")\n        im.save(f, format=\"JPEG\", progressive=True, quality=94)\n\n    def test_large_exif(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        f = str(tmp_path / \"temp.jpg\")\n        im = hopper()\n        im.save(f, \"JPEG\", quality=90, exif=b\"1\" * 65532)\n\n    def test_exif_typeerror(self):\n        with Image.open(\"Tests/images/exif_typeerror.jpg\") as im:\n            # Should not raise a TypeError\n            im._getexif()\n\n    def test_exif_gps(self):\n        # Arrange\n        with Image.open(\"Tests/images/exif_gps.jpg\") as im:\n            gps_index = 34853\n            expected_exif_gps = {\n                0: b\"\\x00\\x00\\x00\\x01\",\n                2: (4294967295, 1),\n                5: b\"\\x01\",\n                30: 65535,\n                29: \"1999:99:99 99:99:99\",\n            }\n\n            # Act\n            exif = im._getexif()\n\n        # Assert\n        assert exif[gps_index] == expected_exif_gps\n\n    def test_exif_rollback(self):\n        # rolling back exif support in 3.1 to pre-3.0 formatting.\n        # expected from 2.9, with b/u qualifiers switched for 3.2 compatibility\n        # this test passes on 2.9 and 3.1, but not 3.0\n        expected_exif = {\n            34867: 4294967295,\n            258: (24, 24, 24),\n            36867: \"2099:09:29 10:10:10\",\n            34853: {\n                0: b\"\\x00\\x00\\x00\\x01\",\n                2: (4294967295, 1),\n                5: b\"\\x01\",\n                30: 65535,\n                29: \"1999:99:99 99:99:99\",\n            },\n            296: 65535,\n            34665: 185,\n            41994: 65535,\n            514: 4294967295,\n            271: \"Make\",\n            272: \"XXX-XXX\",\n            305: \"PIL\",\n            42034: ((1, 1), (1, 1), (1, 1), (1, 1)),\n            42035: \"LensMake\",\n            34856: b\"\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa\",\n            282: (4294967295, 1),\n            33434: (4294967295, 1),\n        }\n\n        with Image.open(\"Tests/images/exif_gps.jpg\") as im:\n            exif = im._getexif()\n\n        for tag, value in expected_exif.items():\n            assert value == exif[tag]\n\n    def test_exif_gps_typeerror(self):\n        with Image.open(\"Tests/images/exif_gps_typeerror.jpg\") as im:\n\n            # Should not raise a TypeError\n            im._getexif()\n\n    def test_progressive_compat(self):\n        im1 = self.roundtrip(hopper())\n        assert not im1.info.get(\"progressive\")\n        assert not im1.info.get(\"progression\")\n\n        im2 = self.roundtrip(hopper(), progressive=0)\n        im3 = self.roundtrip(hopper(), progression=0)  # compatibility\n        assert not im2.info.get(\"progressive\")\n        assert not im2.info.get(\"progression\")\n        assert not im3.info.get(\"progressive\")\n        assert not im3.info.get(\"progression\")\n\n        im2 = self.roundtrip(hopper(), progressive=1)\n        im3 = self.roundtrip(hopper(), progression=1)  # compatibility\n        assert_image_equal(im1, im2)\n        assert_image_equal(im1, im3)\n        assert im2.info.get(\"progressive\")\n        assert im2.info.get(\"progression\")\n        assert im3.info.get(\"progressive\")\n        assert im3.info.get(\"progression\")\n\n    def test_quality(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), quality=50)\n        assert_image(im1, im2.mode, im2.size)\n        assert im1.bytes >= im2.bytes\n\n        im3 = self.roundtrip(hopper(), quality=0)\n        assert_image(im1, im3.mode, im3.size)\n        assert im2.bytes > im3.bytes\n\n    def test_smooth(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), smooth=100)\n        assert_image(im1, im2.mode, im2.size)\n\n    def test_subsampling(self):\n        def getsampling(im):\n            layer = im.layer\n            return layer[0][1:3] + layer[1][1:3] + layer[2][1:3]\n\n        # experimental API\n        im = self.roundtrip(hopper(), subsampling=-1)  # default\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=0)  # 4:4:4\n        assert getsampling(im) == (1, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=1)  # 4:2:2\n        assert getsampling(im) == (2, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=2)  # 4:2:0\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=3)  # default (undefined)\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n\n        im = self.roundtrip(hopper(), subsampling=\"4:4:4\")\n        assert getsampling(im) == (1, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:2:2\")\n        assert getsampling(im) == (2, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:2:0\")\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:1:1\")\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n\n        with pytest.raises(TypeError):\n            self.roundtrip(hopper(), subsampling=\"1:1:1\")\n\n    def test_exif(self):\n        with Image.open(\"Tests/images/pil_sample_rgb.jpg\") as im:\n            info = im._getexif()\n            assert info[305] == \"Adobe Photoshop CS Macintosh\"\n\n    def test_mp(self):\n        with Image.open(\"Tests/images/pil_sample_rgb.jpg\") as im:\n            assert im._getmp() is None\n\n    def test_quality_keep(self, tmp_path):\n        # RGB\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n        # Grayscale\n        with Image.open(\"Tests/images/hopper_gray.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n        # CMYK\n        with Image.open(\"Tests/images/pil_sample_cmyk.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n\n    def test_junk_jpeg_header(self):\n        # https://github.com/python-pillow/Pillow/issues/630\n        filename = \"Tests/images/junk_jpeg_header.jpg\"\n        with Image.open(filename):\n            pass\n\n    def test_ff00_jpeg_header(self):\n        filename = \"Tests/images/jpeg_ff00_header.jpg\"\n        with Image.open(filename):\n            pass\n\n    def test_truncated_jpeg_should_read_all_the_data(self):\n        filename = \"Tests/images/truncated_jpeg.jpg\"\n        ImageFile.LOAD_TRUNCATED_IMAGES = True\n        with Image.open(filename) as im:\n            im.load()\n            ImageFile.LOAD_TRUNCATED_IMAGES = False\n            assert im.getbbox() is not None\n\n    def test_truncated_jpeg_throws_oserror(self):\n        filename = \"Tests/images/truncated_jpeg.jpg\"\n        with Image.open(filename) as im:\n            with pytest.raises(OSError):\n                im.load()\n\n            # Test that the error is raised if loaded a second time\n            with pytest.raises(OSError):\n                im.load()\n\n    def test_qtables(self, tmp_path):\n        def _n_qtables_helper(n, test_file):\n            with Image.open(test_file) as im:\n                f = str(tmp_path / \"temp.jpg\")\n                im.save(f, qtables=[[n] * 64] * n)\n            with Image.open(f) as im:\n                assert len(im.quantization) == n\n                reloaded = self.roundtrip(im, qtables=\"keep\")\n                assert im.quantization == reloaded.quantization\n\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            qtables = im.quantization\n            reloaded = self.roundtrip(im, qtables=qtables, subsampling=0)\n            assert im.quantization == reloaded.quantization\n            assert_image_similar(im, self.roundtrip(im, qtables=\"web_low\"), 30)\n            assert_image_similar(im, self.roundtrip(im, qtables=\"web_high\"), 30)\n            assert_image_similar(im, self.roundtrip(im, qtables=\"keep\"), 30)\n\n            # valid bounds for baseline qtable\n            bounds_qtable = [int(s) for s in (\"255 1 \" * 32).split(None)]\n            self.roundtrip(im, qtables=[bounds_qtable])\n\n            # values from wizard.txt in jpeg9-a src package.\n            standard_l_qtable = [\n                int(s)\n                for s in \"\"\"\n                16  11  10  16  24  40  51  61\n                12  12  14  19  26  58  60  55\n                14  13  16  24  40  57  69  56\n                14  17  22  29  51  87  80  62\n                18  22  37  56  68 109 103  77\n                24  35  55  64  81 104 113  92\n                49  64  78  87 103 121 120 101\n                72  92  95  98 112 100 103  99\n                \"\"\".split(\n                    None\n                )\n            ]\n\n            standard_chrominance_qtable = [\n                int(s)\n                for s in \"\"\"\n                17  18  24  47  99  99  99  99\n                18  21  26  66  99  99  99  99\n                24  26  56  99  99  99  99  99\n                47  66  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                \"\"\".split(\n                    None\n                )\n            ]\n            # list of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables=[standard_l_qtable, standard_chrominance_qtable]\n                ),\n                30,\n            )\n\n            # tuple of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables=(standard_l_qtable, standard_chrominance_qtable)\n                ),\n                30,\n            )\n\n            # dict of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables={0: standard_l_qtable, 1: standard_chrominance_qtable}\n                ),\n                30,\n            )\n\n            _n_qtables_helper(1, \"Tests/images/hopper_gray.jpg\")\n            _n_qtables_helper(1, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(2, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(3, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(1, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(2, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(3, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(4, \"Tests/images/pil_sample_cmyk.jpg\")\n\n            # not a sequence\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=\"a\")\n            # sequence wrong length\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[])\n            # sequence wrong length\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[1, 2, 3, 4, 5])\n\n            # qtable entry not a sequence\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[1])\n            # qtable entry has wrong number of items\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[[1, 2, 3, 4]])\n\n    @pytest.mark.skipif(not djpeg_available(), reason=\"djpeg not available\")\n    def test_load_djpeg(self):\n        with Image.open(TEST_FILE) as img:\n            img.load_djpeg()\n            assert_image_similar(img, Image.open(TEST_FILE), 5)\n\n    @pytest.mark.skipif(not cjpeg_available(), reason=\"cjpeg not available\")\n    def test_save_cjpeg(self, tmp_path):\n        with Image.open(TEST_FILE) as img:\n            tempfile = str(tmp_path / \"temp.jpg\")\n            JpegImagePlugin._save_cjpeg(img, 0, tempfile)\n            # Default save quality is 75%, so a tiny bit of difference is alright\n            assert_image_similar(img, Image.open(tempfile), 17)\n\n    def test_no_duplicate_0x1001_tag(self):\n        # Arrange\n        tag_ids = {v: k for k, v in ExifTags.TAGS.items()}\n\n        # Assert\n        assert tag_ids[\"RelatedImageWidth\"] == 0x1001\n        assert tag_ids[\"RelatedImageLength\"] == 0x1002\n\n    def test_MAXBLOCK_scaling(self, tmp_path):\n        im = self.gen_random_image((512, 512))\n        f = str(tmp_path / \"temp.jpeg\")\n        im.save(f, quality=100, optimize=True)\n\n        with Image.open(f) as reloaded:\n            # none of these should crash\n            reloaded.save(f, quality=\"keep\")\n            reloaded.save(f, quality=\"keep\", progressive=True)\n            reloaded.save(f, quality=\"keep\", optimize=True)\n\n    def test_bad_mpo_header(self):\n        \"\"\" Treat unknown MPO as JPEG \"\"\"\n        # Arrange\n\n        # Act\n        # Shouldn't raise error\n        fn = \"Tests/images/sugarshack_bad_mpo_header.jpg\"\n        with pytest.warns(UserWarning, Image.open, fn) as im:\n\n            # Assert\n            assert im.format == \"JPEG\"\n\n    def test_save_correct_modes(self):\n        out = BytesIO()\n        for mode in [\"1\", \"L\", \"RGB\", \"RGBX\", \"CMYK\", \"YCbCr\"]:\n            img = Image.new(mode, (20, 20))\n            img.save(out, \"JPEG\")\n\n    def test_save_wrong_modes(self):\n        # ref https://github.com/python-pillow/Pillow/issues/2005\n        out = BytesIO()\n        for mode in [\"LA\", \"La\", \"RGBA\", \"RGBa\", \"P\"]:\n            img = Image.new(mode, (20, 20))\n            with pytest.raises(OSError):\n                img.save(out, \"JPEG\")\n\n    def test_save_tiff_with_dpi(self, tmp_path):\n        # Arrange\n        outfile = str(tmp_path / \"temp.tif\")\n        with Image.open(\"Tests/images/hopper.tif\") as im:\n\n            # Act\n            im.save(outfile, \"JPEG\", dpi=im.info[\"dpi\"])\n\n            # Assert\n            with Image.open(outfile) as reloaded:\n                reloaded.load()\n                assert im.info[\"dpi\"] == reloaded.info[\"dpi\"]\n\n    def test_load_dpi_rounding(self):\n        # Round up\n        with Image.open(\"Tests/images/iptc_roundUp.jpg\") as im:\n            assert im.info[\"dpi\"] == (44, 44)\n\n        # Round down\n        with Image.open(\"Tests/images/iptc_roundDown.jpg\") as im:\n            assert im.info[\"dpi\"] == (2, 2)\n\n    def test_save_dpi_rounding(self, tmp_path):\n        outfile = str(tmp_path / \"temp.jpg\")\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            im.save(outfile, dpi=(72.2, 72.2))\n\n            with Image.open(outfile) as reloaded:\n                assert reloaded.info[\"dpi\"] == (72, 72)\n\n            im.save(outfile, dpi=(72.8, 72.8))\n\n        with Image.open(outfile) as reloaded:\n            assert reloaded.info[\"dpi\"] == (73, 73)\n\n    def test_dpi_tuple_from_exif(self):\n        # Arrange\n        # This Photoshop CC 2017 image has DPI in EXIF not metadata\n        # EXIF XResolution is (2000000, 10000)\n        with Image.open(\"Tests/images/photoshop-200dpi.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (200, 200)\n\n    def test_dpi_int_from_exif(self):\n        # Arrange\n        # This image has DPI in EXIF not metadata\n        # EXIF XResolution is 72\n        with Image.open(\"Tests/images/exif-72dpi-int.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_dpi_from_dpcm_exif(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with EXIF resolution unit set to cm:\n        # exiftool -exif:ResolutionUnit=cm photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/exif-200dpcm.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (508, 508)\n\n    def test_dpi_exif_zero_division(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with EXIF resolution set to 0/0:\n        # exiftool -XResolution=0/0 -YResolution=0/0 photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/exif-dpi-zerodivision.jpg\") as im:\n\n            # Act / Assert\n            # This should return the default, and not raise a ZeroDivisionError\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_no_dpi_in_exif(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with resolution removed from EXIF:\n        # exiftool \"-*resolution*\"= photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/no-dpi-in-exif.jpg\") as im:\n\n            # Act / Assert\n            # \"When the image resolution is unknown, 72 [dpi] is designated.\"\n            # http://www.exiv2.org/tags.html\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_invalid_exif(self):\n        # This is no-dpi-in-exif with the tiff header of the exif block\n        # hexedited from MM * to FF FF FF FF\n        with Image.open(\"Tests/images/invalid-exif.jpg\") as im:\n\n            # This should return the default, and not a SyntaxError or\n            # OSError for unidentified image.\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_invalid_exif_x_resolution(self):\n        # When no x or y resolution is defined in EXIF\n        with Image.open(\"Tests/images/invalid-exif-without-x-resolution.jpg\") as im:\n\n            # This should return the default, and not a ValueError or\n            # OSError for an unidentified image.\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_ifd_offset_exif(self):\n        # Arrange\n        # This image has been manually hexedited to have an IFD offset of 10,\n        # in contrast to normal 8\n        with Image.open(\"Tests/images/exif-ifd-offset.jpg\") as im:\n\n            # Act / Assert\n            assert im._getexif()[306] == \"2017:03:13 23:03:09\"\n\n    def test_photoshop(self):\n        with Image.open(\"Tests/images/photoshop-200dpi.jpg\") as im:\n            assert im.info[\"photoshop\"][0x03ED] == {\n                \"XResolution\": 200.0,\n                \"DisplayedUnitsX\": 1,\n                \"YResolution\": 200.0,\n                \"DisplayedUnitsY\": 1,\n            }\n\n            # Test that the image can still load, even with broken Photoshop data\n            # This image had the APP13 length hexedited to be smaller\n            with Image.open(\"Tests/images/photoshop-200dpi-broken.jpg\") as im_broken:\n                assert_image_equal(im_broken, im)\n\n        # This image does not contain a Photoshop header string\n        with Image.open(\"Tests/images/app13.jpg\") as im:\n            assert \"photoshop\" not in im.info\n\n    def test_photoshop_malformed_and_multiple(self):\n        with Image.open(\"Tests/images/app13-multiple.jpg\") as im:\n            assert \"photoshop\" in im.info\n            assert 24 == len(im.info[\"photoshop\"])\n            apps_13_lengths = [len(v) for k, v in im.applist if k == \"APP13\"]\n            assert [65504, 24] == apps_13_lengths\n\n    def test_icc_after_SOF(self):\n        with Image.open(\"Tests/images/icc-after-SOF.jpg\") as im:\n            assert im.info[\"icc_profile\"] == b\"profile\"",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 234,
                            "end_lineno": 267,
                            "parent": {
                                "file_name": "Tests/test_file_jpeg.py",
                                "type": "class",
                                "name": "TestFileJpeg",
                                "content": "class TestFileJpeg:\n    def roundtrip(self, im, **options):\n        out = BytesIO()\n        im.save(out, \"JPEG\", **options)\n        test_bytes = out.tell()\n        out.seek(0)\n        im = Image.open(out)\n        im.bytes = test_bytes  # for testing only\n        return im\n\n    def gen_random_image(self, size, mode=\"RGB\"):\n        \"\"\" Generates a very hard to compress file\n        :param size: tuple\n        :param mode: optional image mode\n\n        \"\"\"\n        return Image.frombytes(mode, size, os.urandom(size[0] * size[1] * len(mode)))\n\n    def test_sanity(self):\n\n        # internal version number\n        assert re.search(r\"\\d+\\.\\d+$\", Image.core.jpeglib_version)\n\n        with Image.open(TEST_FILE) as im:\n            im.load()\n            assert im.mode == \"RGB\"\n            assert im.size == (128, 128)\n            assert im.format == \"JPEG\"\n            assert im.get_format_mimetype() == \"image/jpeg\"\n\n    def test_app(self):\n        # Test APP/COM reader (@PIL135)\n        with Image.open(TEST_FILE) as im:\n            assert im.applist[0] == (\"APP0\", b\"JFIF\\x00\\x01\\x01\\x01\\x00`\\x00`\\x00\\x00\")\n            assert im.applist[1] == (\n                \"COM\",\n                b\"File written by Adobe Photoshop\\xa8 4.0\\x00\",\n            )\n            assert len(im.applist) == 2\n\n            assert im.info[\"comment\"] == b\"File written by Adobe Photoshop\\xa8 4.0\\x00\"\n\n    def test_cmyk(self):\n        # Test CMYK handling.  Thanks to Tim and Charlie for test data,\n        # Michael for getting me to look one more time.\n        f = \"Tests/images/pil_sample_cmyk.jpg\"\n        with Image.open(f) as im:\n            # the source image has red pixels in the upper left corner.\n            c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))]\n            assert c == 0.0\n            assert m > 0.8\n            assert y > 0.8\n            assert k == 0.0\n            # the opposite corner is black\n            c, m, y, k = [\n                x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1))\n            ]\n            assert k > 0.9\n            # roundtrip, and check again\n            im = self.roundtrip(im)\n            c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))]\n            assert c == 0.0\n            assert m > 0.8\n            assert y > 0.8\n            assert k == 0.0\n            c, m, y, k = [\n                x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1))\n            ]\n            assert k > 0.9\n\n    def test_dpi(self):\n        def test(xdpi, ydpi=None):\n            with Image.open(TEST_FILE) as im:\n                im = self.roundtrip(im, dpi=(xdpi, ydpi or xdpi))\n            return im.info.get(\"dpi\")\n\n        assert test(72) == (72, 72)\n        assert test(300) == (300, 300)\n        assert test(100, 200) == (100, 200)\n        assert test(0) is None  # square pixels\n\n    def test_icc(self, tmp_path):\n        # Test ICC support\n        with Image.open(\"Tests/images/rgb.jpg\") as im1:\n            icc_profile = im1.info[\"icc_profile\"]\n            assert len(icc_profile) == 3144\n            # Roundtrip via physical file.\n            f = str(tmp_path / \"temp.jpg\")\n            im1.save(f, icc_profile=icc_profile)\n        with Image.open(f) as im2:\n            assert im2.info.get(\"icc_profile\") == icc_profile\n            # Roundtrip via memory buffer.\n            im1 = self.roundtrip(hopper())\n            im2 = self.roundtrip(hopper(), icc_profile=icc_profile)\n            assert_image_equal(im1, im2)\n            assert not im1.info.get(\"icc_profile\")\n            assert im2.info.get(\"icc_profile\")\n\n    def test_icc_big(self):\n        # Make sure that the \"extra\" support handles large blocks\n        def test(n):\n            # The ICC APP marker can store 65519 bytes per marker, so\n            # using a 4-byte test code should allow us to detect out of\n            # order issues.\n            icc_profile = (b\"Test\" * int(n / 4 + 1))[:n]\n            assert len(icc_profile) == n  # sanity\n            im1 = self.roundtrip(hopper(), icc_profile=icc_profile)\n            assert im1.info.get(\"icc_profile\") == (icc_profile or None)\n\n        test(0)\n        test(1)\n        test(3)\n        test(4)\n        test(5)\n        test(65533 - 14)  # full JPEG marker block\n        test(65533 - 14 + 1)  # full block plus one byte\n        test(ImageFile.MAXBLOCK)  # full buffer block\n        test(ImageFile.MAXBLOCK + 1)  # full buffer block plus one byte\n        test(ImageFile.MAXBLOCK * 4 + 3)  # large block\n\n    def test_large_icc_meta(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        # Sometimes the meta data on the icc_profile block is bigger than\n        # Image.MAXBLOCK or the image size.\n        with Image.open(\"Tests/images/icc_profile_big.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            icc_profile = im.info[\"icc_profile\"]\n            # Should not raise OSError for image with icc larger than image size.\n            im.save(\n                f,\n                format=\"JPEG\",\n                progressive=True,\n                quality=95,\n                icc_profile=icc_profile,\n                optimize=True,\n            )\n\n    def test_optimize(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), optimize=0)\n        im3 = self.roundtrip(hopper(), optimize=1)\n        assert_image_equal(im1, im2)\n        assert_image_equal(im1, im3)\n        assert im1.bytes >= im2.bytes\n        assert im1.bytes >= im3.bytes\n\n    def test_optimize_large_buffer(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        f = str(tmp_path / \"temp.jpg\")\n        # this requires ~ 1.5x Image.MAXBLOCK\n        im = Image.new(\"RGB\", (4096, 4096), 0xFF3333)\n        im.save(f, format=\"JPEG\", optimize=True)\n\n    def test_progressive(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), progressive=False)\n        im3 = self.roundtrip(hopper(), progressive=True)\n        assert not im1.info.get(\"progressive\")\n        assert not im2.info.get(\"progressive\")\n        assert im3.info.get(\"progressive\")\n\n        assert_image_equal(im1, im3)\n        assert im1.bytes >= im3.bytes\n\n    def test_progressive_large_buffer(self, tmp_path):\n        f = str(tmp_path / \"temp.jpg\")\n        # this requires ~ 1.5x Image.MAXBLOCK\n        im = Image.new(\"RGB\", (4096, 4096), 0xFF3333)\n        im.save(f, format=\"JPEG\", progressive=True)\n\n    def test_progressive_large_buffer_highest_quality(self, tmp_path):\n        f = str(tmp_path / \"temp.jpg\")\n        im = self.gen_random_image((255, 255))\n        # this requires more bytes than pixels in the image\n        im.save(f, format=\"JPEG\", progressive=True, quality=100)\n\n    def test_progressive_cmyk_buffer(self):\n        # Issue 2272, quality 90 cmyk image is tripping the large buffer bug.\n        f = BytesIO()\n        im = self.gen_random_image((256, 256), \"CMYK\")\n        im.save(f, format=\"JPEG\", progressive=True, quality=94)\n\n    def test_large_exif(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        f = str(tmp_path / \"temp.jpg\")\n        im = hopper()\n        im.save(f, \"JPEG\", quality=90, exif=b\"1\" * 65532)\n\n    def test_exif_typeerror(self):\n        with Image.open(\"Tests/images/exif_typeerror.jpg\") as im:\n            # Should not raise a TypeError\n            im._getexif()\n\n    def test_exif_gps(self):\n        # Arrange\n        with Image.open(\"Tests/images/exif_gps.jpg\") as im:\n            gps_index = 34853\n            expected_exif_gps = {\n                0: b\"\\x00\\x00\\x00\\x01\",\n                2: (4294967295, 1),\n                5: b\"\\x01\",\n                30: 65535,\n                29: \"1999:99:99 99:99:99\",\n            }\n\n            # Act\n            exif = im._getexif()\n\n        # Assert\n        assert exif[gps_index] == expected_exif_gps\n\n    def test_exif_rollback(self):\n        # rolling back exif support in 3.1 to pre-3.0 formatting.\n        # expected from 2.9, with b/u qualifiers switched for 3.2 compatibility\n        # this test passes on 2.9 and 3.1, but not 3.0\n        expected_exif = {\n            34867: 4294967295,\n            258: (24, 24, 24),\n            36867: \"2099:09:29 10:10:10\",\n            34853: {\n                0: b\"\\x00\\x00\\x00\\x01\",\n                2: (4294967295, 1),\n                5: b\"\\x01\",\n                30: 65535,\n                29: \"1999:99:99 99:99:99\",\n            },\n            296: 65535,\n            34665: 185,\n            41994: 65535,\n            514: 4294967295,\n            271: \"Make\",\n            272: \"XXX-XXX\",\n            305: \"PIL\",\n            42034: ((1, 1), (1, 1), (1, 1), (1, 1)),\n            42035: \"LensMake\",\n            34856: b\"\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa\",\n            282: (4294967295, 1),\n            33434: (4294967295, 1),\n        }\n\n        with Image.open(\"Tests/images/exif_gps.jpg\") as im:\n            exif = im._getexif()\n\n        for tag, value in expected_exif.items():\n            assert value == exif[tag]\n\n    def test_exif_gps_typeerror(self):\n        with Image.open(\"Tests/images/exif_gps_typeerror.jpg\") as im:\n\n            # Should not raise a TypeError\n            im._getexif()\n\n    def test_progressive_compat(self):\n        im1 = self.roundtrip(hopper())\n        assert not im1.info.get(\"progressive\")\n        assert not im1.info.get(\"progression\")\n\n        im2 = self.roundtrip(hopper(), progressive=0)\n        im3 = self.roundtrip(hopper(), progression=0)  # compatibility\n        assert not im2.info.get(\"progressive\")\n        assert not im2.info.get(\"progression\")\n        assert not im3.info.get(\"progressive\")\n        assert not im3.info.get(\"progression\")\n\n        im2 = self.roundtrip(hopper(), progressive=1)\n        im3 = self.roundtrip(hopper(), progression=1)  # compatibility\n        assert_image_equal(im1, im2)\n        assert_image_equal(im1, im3)\n        assert im2.info.get(\"progressive\")\n        assert im2.info.get(\"progression\")\n        assert im3.info.get(\"progressive\")\n        assert im3.info.get(\"progression\")\n\n    def test_quality(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), quality=50)\n        assert_image(im1, im2.mode, im2.size)\n        assert im1.bytes >= im2.bytes\n\n        im3 = self.roundtrip(hopper(), quality=0)\n        assert_image(im1, im3.mode, im3.size)\n        assert im2.bytes > im3.bytes\n\n    def test_smooth(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), smooth=100)\n        assert_image(im1, im2.mode, im2.size)\n\n    def test_subsampling(self):\n        def getsampling(im):\n            layer = im.layer\n            return layer[0][1:3] + layer[1][1:3] + layer[2][1:3]\n\n        # experimental API\n        im = self.roundtrip(hopper(), subsampling=-1)  # default\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=0)  # 4:4:4\n        assert getsampling(im) == (1, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=1)  # 4:2:2\n        assert getsampling(im) == (2, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=2)  # 4:2:0\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=3)  # default (undefined)\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n\n        im = self.roundtrip(hopper(), subsampling=\"4:4:4\")\n        assert getsampling(im) == (1, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:2:2\")\n        assert getsampling(im) == (2, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:2:0\")\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:1:1\")\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n\n        with pytest.raises(TypeError):\n            self.roundtrip(hopper(), subsampling=\"1:1:1\")\n\n    def test_exif(self):\n        with Image.open(\"Tests/images/pil_sample_rgb.jpg\") as im:\n            info = im._getexif()\n            assert info[305] == \"Adobe Photoshop CS Macintosh\"\n\n    def test_mp(self):\n        with Image.open(\"Tests/images/pil_sample_rgb.jpg\") as im:\n            assert im._getmp() is None\n\n    def test_quality_keep(self, tmp_path):\n        # RGB\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n        # Grayscale\n        with Image.open(\"Tests/images/hopper_gray.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n        # CMYK\n        with Image.open(\"Tests/images/pil_sample_cmyk.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n\n    def test_junk_jpeg_header(self):\n        # https://github.com/python-pillow/Pillow/issues/630\n        filename = \"Tests/images/junk_jpeg_header.jpg\"\n        with Image.open(filename):\n            pass\n\n    def test_ff00_jpeg_header(self):\n        filename = \"Tests/images/jpeg_ff00_header.jpg\"\n        with Image.open(filename):\n            pass\n\n    def test_truncated_jpeg_should_read_all_the_data(self):\n        filename = \"Tests/images/truncated_jpeg.jpg\"\n        ImageFile.LOAD_TRUNCATED_IMAGES = True\n        with Image.open(filename) as im:\n            im.load()\n            ImageFile.LOAD_TRUNCATED_IMAGES = False\n            assert im.getbbox() is not None\n\n    def test_truncated_jpeg_throws_oserror(self):\n        filename = \"Tests/images/truncated_jpeg.jpg\"\n        with Image.open(filename) as im:\n            with pytest.raises(OSError):\n                im.load()\n\n            # Test that the error is raised if loaded a second time\n            with pytest.raises(OSError):\n                im.load()\n\n    def test_qtables(self, tmp_path):\n        def _n_qtables_helper(n, test_file):\n            with Image.open(test_file) as im:\n                f = str(tmp_path / \"temp.jpg\")\n                im.save(f, qtables=[[n] * 64] * n)\n            with Image.open(f) as im:\n                assert len(im.quantization) == n\n                reloaded = self.roundtrip(im, qtables=\"keep\")\n                assert im.quantization == reloaded.quantization\n\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            qtables = im.quantization\n            reloaded = self.roundtrip(im, qtables=qtables, subsampling=0)\n            assert im.quantization == reloaded.quantization\n            assert_image_similar(im, self.roundtrip(im, qtables=\"web_low\"), 30)\n            assert_image_similar(im, self.roundtrip(im, qtables=\"web_high\"), 30)\n            assert_image_similar(im, self.roundtrip(im, qtables=\"keep\"), 30)\n\n            # valid bounds for baseline qtable\n            bounds_qtable = [int(s) for s in (\"255 1 \" * 32).split(None)]\n            self.roundtrip(im, qtables=[bounds_qtable])\n\n            # values from wizard.txt in jpeg9-a src package.\n            standard_l_qtable = [\n                int(s)\n                for s in \"\"\"\n                16  11  10  16  24  40  51  61\n                12  12  14  19  26  58  60  55\n                14  13  16  24  40  57  69  56\n                14  17  22  29  51  87  80  62\n                18  22  37  56  68 109 103  77\n                24  35  55  64  81 104 113  92\n                49  64  78  87 103 121 120 101\n                72  92  95  98 112 100 103  99\n                \"\"\".split(\n                    None\n                )\n            ]\n\n            standard_chrominance_qtable = [\n                int(s)\n                for s in \"\"\"\n                17  18  24  47  99  99  99  99\n                18  21  26  66  99  99  99  99\n                24  26  56  99  99  99  99  99\n                47  66  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                \"\"\".split(\n                    None\n                )\n            ]\n            # list of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables=[standard_l_qtable, standard_chrominance_qtable]\n                ),\n                30,\n            )\n\n            # tuple of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables=(standard_l_qtable, standard_chrominance_qtable)\n                ),\n                30,\n            )\n\n            # dict of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables={0: standard_l_qtable, 1: standard_chrominance_qtable}\n                ),\n                30,\n            )\n\n            _n_qtables_helper(1, \"Tests/images/hopper_gray.jpg\")\n            _n_qtables_helper(1, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(2, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(3, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(1, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(2, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(3, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(4, \"Tests/images/pil_sample_cmyk.jpg\")\n\n            # not a sequence\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=\"a\")\n            # sequence wrong length\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[])\n            # sequence wrong length\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[1, 2, 3, 4, 5])\n\n            # qtable entry not a sequence\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[1])\n            # qtable entry has wrong number of items\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[[1, 2, 3, 4]])\n\n    @pytest.mark.skipif(not djpeg_available(), reason=\"djpeg not available\")\n    def test_load_djpeg(self):\n        with Image.open(TEST_FILE) as img:\n            img.load_djpeg()\n            assert_image_similar(img, Image.open(TEST_FILE), 5)\n\n    @pytest.mark.skipif(not cjpeg_available(), reason=\"cjpeg not available\")\n    def test_save_cjpeg(self, tmp_path):\n        with Image.open(TEST_FILE) as img:\n            tempfile = str(tmp_path / \"temp.jpg\")\n            JpegImagePlugin._save_cjpeg(img, 0, tempfile)\n            # Default save quality is 75%, so a tiny bit of difference is alright\n            assert_image_similar(img, Image.open(tempfile), 17)\n\n    def test_no_duplicate_0x1001_tag(self):\n        # Arrange\n        tag_ids = {v: k for k, v in ExifTags.TAGS.items()}\n\n        # Assert\n        assert tag_ids[\"RelatedImageWidth\"] == 0x1001\n        assert tag_ids[\"RelatedImageLength\"] == 0x1002\n\n    def test_MAXBLOCK_scaling(self, tmp_path):\n        im = self.gen_random_image((512, 512))\n        f = str(tmp_path / \"temp.jpeg\")\n        im.save(f, quality=100, optimize=True)\n\n        with Image.open(f) as reloaded:\n            # none of these should crash\n            reloaded.save(f, quality=\"keep\")\n            reloaded.save(f, quality=\"keep\", progressive=True)\n            reloaded.save(f, quality=\"keep\", optimize=True)\n\n    def test_bad_mpo_header(self):\n        \"\"\" Treat unknown MPO as JPEG \"\"\"\n        # Arrange\n\n        # Act\n        # Shouldn't raise error\n        fn = \"Tests/images/sugarshack_bad_mpo_header.jpg\"\n        with pytest.warns(UserWarning, Image.open, fn) as im:\n\n            # Assert\n            assert im.format == \"JPEG\"\n\n    def test_save_correct_modes(self):\n        out = BytesIO()\n        for mode in [\"1\", \"L\", \"RGB\", \"RGBX\", \"CMYK\", \"YCbCr\"]:\n            img = Image.new(mode, (20, 20))\n            img.save(out, \"JPEG\")\n\n    def test_save_wrong_modes(self):\n        # ref https://github.com/python-pillow/Pillow/issues/2005\n        out = BytesIO()\n        for mode in [\"LA\", \"La\", \"RGBA\", \"RGBa\", \"P\"]:\n            img = Image.new(mode, (20, 20))\n            with pytest.raises(OSError):\n                img.save(out, \"JPEG\")\n\n    def test_save_tiff_with_dpi(self, tmp_path):\n        # Arrange\n        outfile = str(tmp_path / \"temp.tif\")\n        with Image.open(\"Tests/images/hopper.tif\") as im:\n\n            # Act\n            im.save(outfile, \"JPEG\", dpi=im.info[\"dpi\"])\n\n            # Assert\n            with Image.open(outfile) as reloaded:\n                reloaded.load()\n                assert im.info[\"dpi\"] == reloaded.info[\"dpi\"]\n\n    def test_load_dpi_rounding(self):\n        # Round up\n        with Image.open(\"Tests/images/iptc_roundUp.jpg\") as im:\n            assert im.info[\"dpi\"] == (44, 44)\n\n        # Round down\n        with Image.open(\"Tests/images/iptc_roundDown.jpg\") as im:\n            assert im.info[\"dpi\"] == (2, 2)\n\n    def test_save_dpi_rounding(self, tmp_path):\n        outfile = str(tmp_path / \"temp.jpg\")\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            im.save(outfile, dpi=(72.2, 72.2))\n\n            with Image.open(outfile) as reloaded:\n                assert reloaded.info[\"dpi\"] == (72, 72)\n\n            im.save(outfile, dpi=(72.8, 72.8))\n\n        with Image.open(outfile) as reloaded:\n            assert reloaded.info[\"dpi\"] == (73, 73)\n\n    def test_dpi_tuple_from_exif(self):\n        # Arrange\n        # This Photoshop CC 2017 image has DPI in EXIF not metadata\n        # EXIF XResolution is (2000000, 10000)\n        with Image.open(\"Tests/images/photoshop-200dpi.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (200, 200)\n\n    def test_dpi_int_from_exif(self):\n        # Arrange\n        # This image has DPI in EXIF not metadata\n        # EXIF XResolution is 72\n        with Image.open(\"Tests/images/exif-72dpi-int.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_dpi_from_dpcm_exif(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with EXIF resolution unit set to cm:\n        # exiftool -exif:ResolutionUnit=cm photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/exif-200dpcm.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (508, 508)\n\n    def test_dpi_exif_zero_division(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with EXIF resolution set to 0/0:\n        # exiftool -XResolution=0/0 -YResolution=0/0 photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/exif-dpi-zerodivision.jpg\") as im:\n\n            # Act / Assert\n            # This should return the default, and not raise a ZeroDivisionError\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_no_dpi_in_exif(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with resolution removed from EXIF:\n        # exiftool \"-*resolution*\"= photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/no-dpi-in-exif.jpg\") as im:\n\n            # Act / Assert\n            # \"When the image resolution is unknown, 72 [dpi] is designated.\"\n            # http://www.exiv2.org/tags.html\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_invalid_exif(self):\n        # This is no-dpi-in-exif with the tiff header of the exif block\n        # hexedited from MM * to FF FF FF FF\n        with Image.open(\"Tests/images/invalid-exif.jpg\") as im:\n\n            # This should return the default, and not a SyntaxError or\n            # OSError for unidentified image.\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_invalid_exif_x_resolution(self):\n        # When no x or y resolution is defined in EXIF\n        with Image.open(\"Tests/images/invalid-exif-without-x-resolution.jpg\") as im:\n\n            # This should return the default, and not a ValueError or\n            # OSError for an unidentified image.\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_ifd_offset_exif(self):\n        # Arrange\n        # This image has been manually hexedited to have an IFD offset of 10,\n        # in contrast to normal 8\n        with Image.open(\"Tests/images/exif-ifd-offset.jpg\") as im:\n\n            # Act / Assert\n            assert im._getexif()[306] == \"2017:03:13 23:03:09\"\n\n    def test_photoshop(self):\n        with Image.open(\"Tests/images/photoshop-200dpi.jpg\") as im:\n            assert im.info[\"photoshop\"][0x03ED] == {\n                \"XResolution\": 200.0,\n                \"DisplayedUnitsX\": 1,\n                \"YResolution\": 200.0,\n                \"DisplayedUnitsY\": 1,\n            }\n\n            # Test that the image can still load, even with broken Photoshop data\n            # This image had the APP13 length hexedited to be smaller\n            with Image.open(\"Tests/images/photoshop-200dpi-broken.jpg\") as im_broken:\n                assert_image_equal(im_broken, im)\n\n        # This image does not contain a Photoshop header string\n        with Image.open(\"Tests/images/app13.jpg\") as im:\n            assert \"photoshop\" not in im.info\n\n    def test_photoshop_malformed_and_multiple(self):\n        with Image.open(\"Tests/images/app13-multiple.jpg\") as im:\n            assert \"photoshop\" in im.info\n            assert 24 == len(im.info[\"photoshop\"])\n            apps_13_lengths = [len(v) for k, v in im.applist if k == \"APP13\"]\n            assert [65504, 24] == apps_13_lengths\n\n    def test_icc_after_SOF(self):\n        with Image.open(\"Tests/images/icc-after-SOF.jpg\") as im:\n            assert im.info[\"icc_profile\"] == b\"profile\"",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 23,
                                "end_lineno": 694,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "Tests/test_file_jpeg.py",
                            "type": "class",
                            "name": "TestFileJpeg",
                            "content": "class TestFileJpeg:\n    def roundtrip(self, im, **options):\n        out = BytesIO()\n        im.save(out, \"JPEG\", **options)\n        test_bytes = out.tell()\n        out.seek(0)\n        im = Image.open(out)\n        im.bytes = test_bytes  # for testing only\n        return im\n\n    def gen_random_image(self, size, mode=\"RGB\"):\n        \"\"\" Generates a very hard to compress file\n        :param size: tuple\n        :param mode: optional image mode\n\n        \"\"\"\n        return Image.frombytes(mode, size, os.urandom(size[0] * size[1] * len(mode)))\n\n    def test_sanity(self):\n\n        # internal version number\n        assert re.search(r\"\\d+\\.\\d+$\", Image.core.jpeglib_version)\n\n        with Image.open(TEST_FILE) as im:\n            im.load()\n            assert im.mode == \"RGB\"\n            assert im.size == (128, 128)\n            assert im.format == \"JPEG\"\n            assert im.get_format_mimetype() == \"image/jpeg\"\n\n    def test_app(self):\n        # Test APP/COM reader (@PIL135)\n        with Image.open(TEST_FILE) as im:\n            assert im.applist[0] == (\"APP0\", b\"JFIF\\x00\\x01\\x01\\x01\\x00`\\x00`\\x00\\x00\")\n            assert im.applist[1] == (\n                \"COM\",\n                b\"File written by Adobe Photoshop\\xa8 4.0\\x00\",\n            )\n            assert len(im.applist) == 2\n\n            assert im.info[\"comment\"] == b\"File written by Adobe Photoshop\\xa8 4.0\\x00\"\n\n    def test_cmyk(self):\n        # Test CMYK handling.  Thanks to Tim and Charlie for test data,\n        # Michael for getting me to look one more time.\n        f = \"Tests/images/pil_sample_cmyk.jpg\"\n        with Image.open(f) as im:\n            # the source image has red pixels in the upper left corner.\n            c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))]\n            assert c == 0.0\n            assert m > 0.8\n            assert y > 0.8\n            assert k == 0.0\n            # the opposite corner is black\n            c, m, y, k = [\n                x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1))\n            ]\n            assert k > 0.9\n            # roundtrip, and check again\n            im = self.roundtrip(im)\n            c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))]\n            assert c == 0.0\n            assert m > 0.8\n            assert y > 0.8\n            assert k == 0.0\n            c, m, y, k = [\n                x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1))\n            ]\n            assert k > 0.9\n\n    def test_dpi(self):\n        def test(xdpi, ydpi=None):\n            with Image.open(TEST_FILE) as im:\n                im = self.roundtrip(im, dpi=(xdpi, ydpi or xdpi))\n            return im.info.get(\"dpi\")\n\n        assert test(72) == (72, 72)\n        assert test(300) == (300, 300)\n        assert test(100, 200) == (100, 200)\n        assert test(0) is None  # square pixels\n\n    def test_icc(self, tmp_path):\n        # Test ICC support\n        with Image.open(\"Tests/images/rgb.jpg\") as im1:\n            icc_profile = im1.info[\"icc_profile\"]\n            assert len(icc_profile) == 3144\n            # Roundtrip via physical file.\n            f = str(tmp_path / \"temp.jpg\")\n            im1.save(f, icc_profile=icc_profile)\n        with Image.open(f) as im2:\n            assert im2.info.get(\"icc_profile\") == icc_profile\n            # Roundtrip via memory buffer.\n            im1 = self.roundtrip(hopper())\n            im2 = self.roundtrip(hopper(), icc_profile=icc_profile)\n            assert_image_equal(im1, im2)\n            assert not im1.info.get(\"icc_profile\")\n            assert im2.info.get(\"icc_profile\")\n\n    def test_icc_big(self):\n        # Make sure that the \"extra\" support handles large blocks\n        def test(n):\n            # The ICC APP marker can store 65519 bytes per marker, so\n            # using a 4-byte test code should allow us to detect out of\n            # order issues.\n            icc_profile = (b\"Test\" * int(n / 4 + 1))[:n]\n            assert len(icc_profile) == n  # sanity\n            im1 = self.roundtrip(hopper(), icc_profile=icc_profile)\n            assert im1.info.get(\"icc_profile\") == (icc_profile or None)\n\n        test(0)\n        test(1)\n        test(3)\n        test(4)\n        test(5)\n        test(65533 - 14)  # full JPEG marker block\n        test(65533 - 14 + 1)  # full block plus one byte\n        test(ImageFile.MAXBLOCK)  # full buffer block\n        test(ImageFile.MAXBLOCK + 1)  # full buffer block plus one byte\n        test(ImageFile.MAXBLOCK * 4 + 3)  # large block\n\n    def test_large_icc_meta(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        # Sometimes the meta data on the icc_profile block is bigger than\n        # Image.MAXBLOCK or the image size.\n        with Image.open(\"Tests/images/icc_profile_big.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            icc_profile = im.info[\"icc_profile\"]\n            # Should not raise OSError for image with icc larger than image size.\n            im.save(\n                f,\n                format=\"JPEG\",\n                progressive=True,\n                quality=95,\n                icc_profile=icc_profile,\n                optimize=True,\n            )\n\n    def test_optimize(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), optimize=0)\n        im3 = self.roundtrip(hopper(), optimize=1)\n        assert_image_equal(im1, im2)\n        assert_image_equal(im1, im3)\n        assert im1.bytes >= im2.bytes\n        assert im1.bytes >= im3.bytes\n\n    def test_optimize_large_buffer(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        f = str(tmp_path / \"temp.jpg\")\n        # this requires ~ 1.5x Image.MAXBLOCK\n        im = Image.new(\"RGB\", (4096, 4096), 0xFF3333)\n        im.save(f, format=\"JPEG\", optimize=True)\n\n    def test_progressive(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), progressive=False)\n        im3 = self.roundtrip(hopper(), progressive=True)\n        assert not im1.info.get(\"progressive\")\n        assert not im2.info.get(\"progressive\")\n        assert im3.info.get(\"progressive\")\n\n        assert_image_equal(im1, im3)\n        assert im1.bytes >= im3.bytes\n\n    def test_progressive_large_buffer(self, tmp_path):\n        f = str(tmp_path / \"temp.jpg\")\n        # this requires ~ 1.5x Image.MAXBLOCK\n        im = Image.new(\"RGB\", (4096, 4096), 0xFF3333)\n        im.save(f, format=\"JPEG\", progressive=True)\n\n    def test_progressive_large_buffer_highest_quality(self, tmp_path):\n        f = str(tmp_path / \"temp.jpg\")\n        im = self.gen_random_image((255, 255))\n        # this requires more bytes than pixels in the image\n        im.save(f, format=\"JPEG\", progressive=True, quality=100)\n\n    def test_progressive_cmyk_buffer(self):\n        # Issue 2272, quality 90 cmyk image is tripping the large buffer bug.\n        f = BytesIO()\n        im = self.gen_random_image((256, 256), \"CMYK\")\n        im.save(f, format=\"JPEG\", progressive=True, quality=94)\n\n    def test_large_exif(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        f = str(tmp_path / \"temp.jpg\")\n        im = hopper()\n        im.save(f, \"JPEG\", quality=90, exif=b\"1\" * 65532)\n\n    def test_exif_typeerror(self):\n        with Image.open(\"Tests/images/exif_typeerror.jpg\") as im:\n            # Should not raise a TypeError\n            im._getexif()\n\n    def test_exif_gps(self):\n        # Arrange\n        with Image.open(\"Tests/images/exif_gps.jpg\") as im:\n            gps_index = 34853\n            expected_exif_gps = {\n                0: b\"\\x00\\x00\\x00\\x01\",\n                2: (4294967295, 1),\n                5: b\"\\x01\",\n                30: 65535,\n                29: \"1999:99:99 99:99:99\",\n            }\n\n            # Act\n            exif = im._getexif()\n\n        # Assert\n        assert exif[gps_index] == expected_exif_gps\n\n    def test_exif_rollback(self):\n        # rolling back exif support in 3.1 to pre-3.0 formatting.\n        # expected from 2.9, with b/u qualifiers switched for 3.2 compatibility\n        # this test passes on 2.9 and 3.1, but not 3.0\n        expected_exif = {\n            34867: 4294967295,\n            258: (24, 24, 24),\n            36867: \"2099:09:29 10:10:10\",\n            34853: {\n                0: b\"\\x00\\x00\\x00\\x01\",\n                2: (4294967295, 1),\n                5: b\"\\x01\",\n                30: 65535,\n                29: \"1999:99:99 99:99:99\",\n            },\n            296: 65535,\n            34665: 185,\n            41994: 65535,\n            514: 4294967295,\n            271: \"Make\",\n            272: \"XXX-XXX\",\n            305: \"PIL\",\n            42034: ((1, 1), (1, 1), (1, 1), (1, 1)),\n            42035: \"LensMake\",\n            34856: b\"\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa\",\n            282: (4294967295, 1),\n            33434: (4294967295, 1),\n        }\n\n        with Image.open(\"Tests/images/exif_gps.jpg\") as im:\n            exif = im._getexif()\n\n        for tag, value in expected_exif.items():\n            assert value == exif[tag]\n\n    def test_exif_gps_typeerror(self):\n        with Image.open(\"Tests/images/exif_gps_typeerror.jpg\") as im:\n\n            # Should not raise a TypeError\n            im._getexif()\n\n    def test_progressive_compat(self):\n        im1 = self.roundtrip(hopper())\n        assert not im1.info.get(\"progressive\")\n        assert not im1.info.get(\"progression\")\n\n        im2 = self.roundtrip(hopper(), progressive=0)\n        im3 = self.roundtrip(hopper(), progression=0)  # compatibility\n        assert not im2.info.get(\"progressive\")\n        assert not im2.info.get(\"progression\")\n        assert not im3.info.get(\"progressive\")\n        assert not im3.info.get(\"progression\")\n\n        im2 = self.roundtrip(hopper(), progressive=1)\n        im3 = self.roundtrip(hopper(), progression=1)  # compatibility\n        assert_image_equal(im1, im2)\n        assert_image_equal(im1, im3)\n        assert im2.info.get(\"progressive\")\n        assert im2.info.get(\"progression\")\n        assert im3.info.get(\"progressive\")\n        assert im3.info.get(\"progression\")\n\n    def test_quality(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), quality=50)\n        assert_image(im1, im2.mode, im2.size)\n        assert im1.bytes >= im2.bytes\n\n        im3 = self.roundtrip(hopper(), quality=0)\n        assert_image(im1, im3.mode, im3.size)\n        assert im2.bytes > im3.bytes\n\n    def test_smooth(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), smooth=100)\n        assert_image(im1, im2.mode, im2.size)\n\n    def test_subsampling(self):\n        def getsampling(im):\n            layer = im.layer\n            return layer[0][1:3] + layer[1][1:3] + layer[2][1:3]\n\n        # experimental API\n        im = self.roundtrip(hopper(), subsampling=-1)  # default\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=0)  # 4:4:4\n        assert getsampling(im) == (1, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=1)  # 4:2:2\n        assert getsampling(im) == (2, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=2)  # 4:2:0\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=3)  # default (undefined)\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n\n        im = self.roundtrip(hopper(), subsampling=\"4:4:4\")\n        assert getsampling(im) == (1, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:2:2\")\n        assert getsampling(im) == (2, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:2:0\")\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:1:1\")\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n\n        with pytest.raises(TypeError):\n            self.roundtrip(hopper(), subsampling=\"1:1:1\")\n\n    def test_exif(self):\n        with Image.open(\"Tests/images/pil_sample_rgb.jpg\") as im:\n            info = im._getexif()\n            assert info[305] == \"Adobe Photoshop CS Macintosh\"\n\n    def test_mp(self):\n        with Image.open(\"Tests/images/pil_sample_rgb.jpg\") as im:\n            assert im._getmp() is None\n\n    def test_quality_keep(self, tmp_path):\n        # RGB\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n        # Grayscale\n        with Image.open(\"Tests/images/hopper_gray.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n        # CMYK\n        with Image.open(\"Tests/images/pil_sample_cmyk.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n\n    def test_junk_jpeg_header(self):\n        # https://github.com/python-pillow/Pillow/issues/630\n        filename = \"Tests/images/junk_jpeg_header.jpg\"\n        with Image.open(filename):\n            pass\n\n    def test_ff00_jpeg_header(self):\n        filename = \"Tests/images/jpeg_ff00_header.jpg\"\n        with Image.open(filename):\n            pass\n\n    def test_truncated_jpeg_should_read_all_the_data(self):\n        filename = \"Tests/images/truncated_jpeg.jpg\"\n        ImageFile.LOAD_TRUNCATED_IMAGES = True\n        with Image.open(filename) as im:\n            im.load()\n            ImageFile.LOAD_TRUNCATED_IMAGES = False\n            assert im.getbbox() is not None\n\n    def test_truncated_jpeg_throws_oserror(self):\n        filename = \"Tests/images/truncated_jpeg.jpg\"\n        with Image.open(filename) as im:\n            with pytest.raises(OSError):\n                im.load()\n\n            # Test that the error is raised if loaded a second time\n            with pytest.raises(OSError):\n                im.load()\n\n    def test_qtables(self, tmp_path):\n        def _n_qtables_helper(n, test_file):\n            with Image.open(test_file) as im:\n                f = str(tmp_path / \"temp.jpg\")\n                im.save(f, qtables=[[n] * 64] * n)\n            with Image.open(f) as im:\n                assert len(im.quantization) == n\n                reloaded = self.roundtrip(im, qtables=\"keep\")\n                assert im.quantization == reloaded.quantization\n\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            qtables = im.quantization\n            reloaded = self.roundtrip(im, qtables=qtables, subsampling=0)\n            assert im.quantization == reloaded.quantization\n            assert_image_similar(im, self.roundtrip(im, qtables=\"web_low\"), 30)\n            assert_image_similar(im, self.roundtrip(im, qtables=\"web_high\"), 30)\n            assert_image_similar(im, self.roundtrip(im, qtables=\"keep\"), 30)\n\n            # valid bounds for baseline qtable\n            bounds_qtable = [int(s) for s in (\"255 1 \" * 32).split(None)]\n            self.roundtrip(im, qtables=[bounds_qtable])\n\n            # values from wizard.txt in jpeg9-a src package.\n            standard_l_qtable = [\n                int(s)\n                for s in \"\"\"\n                16  11  10  16  24  40  51  61\n                12  12  14  19  26  58  60  55\n                14  13  16  24  40  57  69  56\n                14  17  22  29  51  87  80  62\n                18  22  37  56  68 109 103  77\n                24  35  55  64  81 104 113  92\n                49  64  78  87 103 121 120 101\n                72  92  95  98 112 100 103  99\n                \"\"\".split(\n                    None\n                )\n            ]\n\n            standard_chrominance_qtable = [\n                int(s)\n                for s in \"\"\"\n                17  18  24  47  99  99  99  99\n                18  21  26  66  99  99  99  99\n                24  26  56  99  99  99  99  99\n                47  66  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                \"\"\".split(\n                    None\n                )\n            ]\n            # list of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables=[standard_l_qtable, standard_chrominance_qtable]\n                ),\n                30,\n            )\n\n            # tuple of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables=(standard_l_qtable, standard_chrominance_qtable)\n                ),\n                30,\n            )\n\n            # dict of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables={0: standard_l_qtable, 1: standard_chrominance_qtable}\n                ),\n                30,\n            )\n\n            _n_qtables_helper(1, \"Tests/images/hopper_gray.jpg\")\n            _n_qtables_helper(1, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(2, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(3, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(1, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(2, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(3, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(4, \"Tests/images/pil_sample_cmyk.jpg\")\n\n            # not a sequence\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=\"a\")\n            # sequence wrong length\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[])\n            # sequence wrong length\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[1, 2, 3, 4, 5])\n\n            # qtable entry not a sequence\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[1])\n            # qtable entry has wrong number of items\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[[1, 2, 3, 4]])\n\n    @pytest.mark.skipif(not djpeg_available(), reason=\"djpeg not available\")\n    def test_load_djpeg(self):\n        with Image.open(TEST_FILE) as img:\n            img.load_djpeg()\n            assert_image_similar(img, Image.open(TEST_FILE), 5)\n\n    @pytest.mark.skipif(not cjpeg_available(), reason=\"cjpeg not available\")\n    def test_save_cjpeg(self, tmp_path):\n        with Image.open(TEST_FILE) as img:\n            tempfile = str(tmp_path / \"temp.jpg\")\n            JpegImagePlugin._save_cjpeg(img, 0, tempfile)\n            # Default save quality is 75%, so a tiny bit of difference is alright\n            assert_image_similar(img, Image.open(tempfile), 17)\n\n    def test_no_duplicate_0x1001_tag(self):\n        # Arrange\n        tag_ids = {v: k for k, v in ExifTags.TAGS.items()}\n\n        # Assert\n        assert tag_ids[\"RelatedImageWidth\"] == 0x1001\n        assert tag_ids[\"RelatedImageLength\"] == 0x1002\n\n    def test_MAXBLOCK_scaling(self, tmp_path):\n        im = self.gen_random_image((512, 512))\n        f = str(tmp_path / \"temp.jpeg\")\n        im.save(f, quality=100, optimize=True)\n\n        with Image.open(f) as reloaded:\n            # none of these should crash\n            reloaded.save(f, quality=\"keep\")\n            reloaded.save(f, quality=\"keep\", progressive=True)\n            reloaded.save(f, quality=\"keep\", optimize=True)\n\n    def test_bad_mpo_header(self):\n        \"\"\" Treat unknown MPO as JPEG \"\"\"\n        # Arrange\n\n        # Act\n        # Shouldn't raise error\n        fn = \"Tests/images/sugarshack_bad_mpo_header.jpg\"\n        with pytest.warns(UserWarning, Image.open, fn) as im:\n\n            # Assert\n            assert im.format == \"JPEG\"\n\n    def test_save_correct_modes(self):\n        out = BytesIO()\n        for mode in [\"1\", \"L\", \"RGB\", \"RGBX\", \"CMYK\", \"YCbCr\"]:\n            img = Image.new(mode, (20, 20))\n            img.save(out, \"JPEG\")\n\n    def test_save_wrong_modes(self):\n        # ref https://github.com/python-pillow/Pillow/issues/2005\n        out = BytesIO()\n        for mode in [\"LA\", \"La\", \"RGBA\", \"RGBa\", \"P\"]:\n            img = Image.new(mode, (20, 20))\n            with pytest.raises(OSError):\n                img.save(out, \"JPEG\")\n\n    def test_save_tiff_with_dpi(self, tmp_path):\n        # Arrange\n        outfile = str(tmp_path / \"temp.tif\")\n        with Image.open(\"Tests/images/hopper.tif\") as im:\n\n            # Act\n            im.save(outfile, \"JPEG\", dpi=im.info[\"dpi\"])\n\n            # Assert\n            with Image.open(outfile) as reloaded:\n                reloaded.load()\n                assert im.info[\"dpi\"] == reloaded.info[\"dpi\"]\n\n    def test_load_dpi_rounding(self):\n        # Round up\n        with Image.open(\"Tests/images/iptc_roundUp.jpg\") as im:\n            assert im.info[\"dpi\"] == (44, 44)\n\n        # Round down\n        with Image.open(\"Tests/images/iptc_roundDown.jpg\") as im:\n            assert im.info[\"dpi\"] == (2, 2)\n\n    def test_save_dpi_rounding(self, tmp_path):\n        outfile = str(tmp_path / \"temp.jpg\")\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            im.save(outfile, dpi=(72.2, 72.2))\n\n            with Image.open(outfile) as reloaded:\n                assert reloaded.info[\"dpi\"] == (72, 72)\n\n            im.save(outfile, dpi=(72.8, 72.8))\n\n        with Image.open(outfile) as reloaded:\n            assert reloaded.info[\"dpi\"] == (73, 73)\n\n    def test_dpi_tuple_from_exif(self):\n        # Arrange\n        # This Photoshop CC 2017 image has DPI in EXIF not metadata\n        # EXIF XResolution is (2000000, 10000)\n        with Image.open(\"Tests/images/photoshop-200dpi.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (200, 200)\n\n    def test_dpi_int_from_exif(self):\n        # Arrange\n        # This image has DPI in EXIF not metadata\n        # EXIF XResolution is 72\n        with Image.open(\"Tests/images/exif-72dpi-int.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_dpi_from_dpcm_exif(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with EXIF resolution unit set to cm:\n        # exiftool -exif:ResolutionUnit=cm photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/exif-200dpcm.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (508, 508)\n\n    def test_dpi_exif_zero_division(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with EXIF resolution set to 0/0:\n        # exiftool -XResolution=0/0 -YResolution=0/0 photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/exif-dpi-zerodivision.jpg\") as im:\n\n            # Act / Assert\n            # This should return the default, and not raise a ZeroDivisionError\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_no_dpi_in_exif(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with resolution removed from EXIF:\n        # exiftool \"-*resolution*\"= photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/no-dpi-in-exif.jpg\") as im:\n\n            # Act / Assert\n            # \"When the image resolution is unknown, 72 [dpi] is designated.\"\n            # http://www.exiv2.org/tags.html\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_invalid_exif(self):\n        # This is no-dpi-in-exif with the tiff header of the exif block\n        # hexedited from MM * to FF FF FF FF\n        with Image.open(\"Tests/images/invalid-exif.jpg\") as im:\n\n            # This should return the default, and not a SyntaxError or\n            # OSError for unidentified image.\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_invalid_exif_x_resolution(self):\n        # When no x or y resolution is defined in EXIF\n        with Image.open(\"Tests/images/invalid-exif-without-x-resolution.jpg\") as im:\n\n            # This should return the default, and not a ValueError or\n            # OSError for an unidentified image.\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_ifd_offset_exif(self):\n        # Arrange\n        # This image has been manually hexedited to have an IFD offset of 10,\n        # in contrast to normal 8\n        with Image.open(\"Tests/images/exif-ifd-offset.jpg\") as im:\n\n            # Act / Assert\n            assert im._getexif()[306] == \"2017:03:13 23:03:09\"\n\n    def test_photoshop(self):\n        with Image.open(\"Tests/images/photoshop-200dpi.jpg\") as im:\n            assert im.info[\"photoshop\"][0x03ED] == {\n                \"XResolution\": 200.0,\n                \"DisplayedUnitsX\": 1,\n                \"YResolution\": 200.0,\n                \"DisplayedUnitsY\": 1,\n            }\n\n            # Test that the image can still load, even with broken Photoshop data\n            # This image had the APP13 length hexedited to be smaller\n            with Image.open(\"Tests/images/photoshop-200dpi-broken.jpg\") as im_broken:\n                assert_image_equal(im_broken, im)\n\n        # This image does not contain a Photoshop header string\n        with Image.open(\"Tests/images/app13.jpg\") as im:\n            assert \"photoshop\" not in im.info\n\n    def test_photoshop_malformed_and_multiple(self):\n        with Image.open(\"Tests/images/app13-multiple.jpg\") as im:\n            assert \"photoshop\" in im.info\n            assert 24 == len(im.info[\"photoshop\"])\n            apps_13_lengths = [len(v) for k, v in im.applist if k == \"APP13\"]\n            assert [65504, 24] == apps_13_lengths\n\n    def test_icc_after_SOF(self):\n        with Image.open(\"Tests/images/icc-after-SOF.jpg\") as im:\n            assert im.info[\"icc_profile\"] == b\"profile\"",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 23,
                            "end_lineno": 694,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 647,
                            "length": 6
                        },
                        "new_range": {
                            "start": 647,
                            "length": 19
                        },
                        "section": "class TestFileJpeg:"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "            # OSError for unidentified image.",
                                "type": "context"
                            },
                            {
                                "content": "            assert im.info.get(\"dpi\") == (72, 72)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def test_exif_x_resolution(self, tmp_path):",
                                "type": "added"
                            },
                            {
                                "content": "        with Image.open(\"Tests/images/flower.jpg\") as im:",
                                "type": "added"
                            },
                            {
                                "content": "            exif = im.getexif()",
                                "type": "added"
                            },
                            {
                                "content": "            assert exif[282] == 180",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "            out = str(tmp_path / \"out.jpg\")",
                                "type": "added"
                            },
                            {
                                "content": "            with pytest.warns(None) as record:",
                                "type": "added"
                            },
                            {
                                "content": "                im.save(out, exif=exif)",
                                "type": "added"
                            },
                            {
                                "content": "            assert len(record) == 0",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        with Image.open(out) as reloaded:",
                                "type": "added"
                            },
                            {
                                "content": "            assert reloaded.getexif()[282] == 180",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def test_invalid_exif_x_resolution(self):",
                                "type": "context"
                            },
                            {
                                "content": "        # When no x or y resolution is defined in EXIF",
                                "type": "context"
                            },
                            {
                                "content": "        with Image.open(\"Tests/images/invalid-exif-without-x-resolution.jpg\") as im:",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Tests/test_file_jpeg.py",
                            "type": "class",
                            "name": "TestFileJpeg",
                            "content": "class TestFileJpeg:\n    def roundtrip(self, im, **options):\n        out = BytesIO()\n        im.save(out, \"JPEG\", **options)\n        test_bytes = out.tell()\n        out.seek(0)\n        im = Image.open(out)\n        im.bytes = test_bytes  # for testing only\n        return im\n\n    def gen_random_image(self, size, mode=\"RGB\"):\n        \"\"\" Generates a very hard to compress file\n        :param size: tuple\n        :param mode: optional image mode\n\n        \"\"\"\n        return Image.frombytes(mode, size, os.urandom(size[0] * size[1] * len(mode)))\n\n    def test_sanity(self):\n\n        # internal version number\n        assert re.search(r\"\\d+\\.\\d+$\", Image.core.jpeglib_version)\n\n        with Image.open(TEST_FILE) as im:\n            im.load()\n            assert im.mode == \"RGB\"\n            assert im.size == (128, 128)\n            assert im.format == \"JPEG\"\n            assert im.get_format_mimetype() == \"image/jpeg\"\n\n    def test_app(self):\n        # Test APP/COM reader (@PIL135)\n        with Image.open(TEST_FILE) as im:\n            assert im.applist[0] == (\"APP0\", b\"JFIF\\x00\\x01\\x01\\x01\\x00`\\x00`\\x00\\x00\")\n            assert im.applist[1] == (\n                \"COM\",\n                b\"File written by Adobe Photoshop\\xa8 4.0\\x00\",\n            )\n            assert len(im.applist) == 2\n\n            assert im.info[\"comment\"] == b\"File written by Adobe Photoshop\\xa8 4.0\\x00\"\n\n    def test_cmyk(self):\n        # Test CMYK handling.  Thanks to Tim and Charlie for test data,\n        # Michael for getting me to look one more time.\n        f = \"Tests/images/pil_sample_cmyk.jpg\"\n        with Image.open(f) as im:\n            # the source image has red pixels in the upper left corner.\n            c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))]\n            assert c == 0.0\n            assert m > 0.8\n            assert y > 0.8\n            assert k == 0.0\n            # the opposite corner is black\n            c, m, y, k = [\n                x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1))\n            ]\n            assert k > 0.9\n            # roundtrip, and check again\n            im = self.roundtrip(im)\n            c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))]\n            assert c == 0.0\n            assert m > 0.8\n            assert y > 0.8\n            assert k == 0.0\n            c, m, y, k = [\n                x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1))\n            ]\n            assert k > 0.9\n\n    def test_dpi(self):\n        def test(xdpi, ydpi=None):\n            with Image.open(TEST_FILE) as im:\n                im = self.roundtrip(im, dpi=(xdpi, ydpi or xdpi))\n            return im.info.get(\"dpi\")\n\n        assert test(72) == (72, 72)\n        assert test(300) == (300, 300)\n        assert test(100, 200) == (100, 200)\n        assert test(0) is None  # square pixels\n\n    def test_icc(self, tmp_path):\n        # Test ICC support\n        with Image.open(\"Tests/images/rgb.jpg\") as im1:\n            icc_profile = im1.info[\"icc_profile\"]\n            assert len(icc_profile) == 3144\n            # Roundtrip via physical file.\n            f = str(tmp_path / \"temp.jpg\")\n            im1.save(f, icc_profile=icc_profile)\n        with Image.open(f) as im2:\n            assert im2.info.get(\"icc_profile\") == icc_profile\n            # Roundtrip via memory buffer.\n            im1 = self.roundtrip(hopper())\n            im2 = self.roundtrip(hopper(), icc_profile=icc_profile)\n            assert_image_equal(im1, im2)\n            assert not im1.info.get(\"icc_profile\")\n            assert im2.info.get(\"icc_profile\")\n\n    def test_icc_big(self):\n        # Make sure that the \"extra\" support handles large blocks\n        def test(n):\n            # The ICC APP marker can store 65519 bytes per marker, so\n            # using a 4-byte test code should allow us to detect out of\n            # order issues.\n            icc_profile = (b\"Test\" * int(n / 4 + 1))[:n]\n            assert len(icc_profile) == n  # sanity\n            im1 = self.roundtrip(hopper(), icc_profile=icc_profile)\n            assert im1.info.get(\"icc_profile\") == (icc_profile or None)\n\n        test(0)\n        test(1)\n        test(3)\n        test(4)\n        test(5)\n        test(65533 - 14)  # full JPEG marker block\n        test(65533 - 14 + 1)  # full block plus one byte\n        test(ImageFile.MAXBLOCK)  # full buffer block\n        test(ImageFile.MAXBLOCK + 1)  # full buffer block plus one byte\n        test(ImageFile.MAXBLOCK * 4 + 3)  # large block\n\n    def test_large_icc_meta(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        # Sometimes the meta data on the icc_profile block is bigger than\n        # Image.MAXBLOCK or the image size.\n        with Image.open(\"Tests/images/icc_profile_big.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            icc_profile = im.info[\"icc_profile\"]\n            # Should not raise OSError for image with icc larger than image size.\n            im.save(\n                f,\n                format=\"JPEG\",\n                progressive=True,\n                quality=95,\n                icc_profile=icc_profile,\n                optimize=True,\n            )\n\n    def test_optimize(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), optimize=0)\n        im3 = self.roundtrip(hopper(), optimize=1)\n        assert_image_equal(im1, im2)\n        assert_image_equal(im1, im3)\n        assert im1.bytes >= im2.bytes\n        assert im1.bytes >= im3.bytes\n\n    def test_optimize_large_buffer(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        f = str(tmp_path / \"temp.jpg\")\n        # this requires ~ 1.5x Image.MAXBLOCK\n        im = Image.new(\"RGB\", (4096, 4096), 0xFF3333)\n        im.save(f, format=\"JPEG\", optimize=True)\n\n    def test_progressive(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), progressive=False)\n        im3 = self.roundtrip(hopper(), progressive=True)\n        assert not im1.info.get(\"progressive\")\n        assert not im2.info.get(\"progressive\")\n        assert im3.info.get(\"progressive\")\n\n        assert_image_equal(im1, im3)\n        assert im1.bytes >= im3.bytes\n\n    def test_progressive_large_buffer(self, tmp_path):\n        f = str(tmp_path / \"temp.jpg\")\n        # this requires ~ 1.5x Image.MAXBLOCK\n        im = Image.new(\"RGB\", (4096, 4096), 0xFF3333)\n        im.save(f, format=\"JPEG\", progressive=True)\n\n    def test_progressive_large_buffer_highest_quality(self, tmp_path):\n        f = str(tmp_path / \"temp.jpg\")\n        im = self.gen_random_image((255, 255))\n        # this requires more bytes than pixels in the image\n        im.save(f, format=\"JPEG\", progressive=True, quality=100)\n\n    def test_progressive_cmyk_buffer(self):\n        # Issue 2272, quality 90 cmyk image is tripping the large buffer bug.\n        f = BytesIO()\n        im = self.gen_random_image((256, 256), \"CMYK\")\n        im.save(f, format=\"JPEG\", progressive=True, quality=94)\n\n    def test_large_exif(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        f = str(tmp_path / \"temp.jpg\")\n        im = hopper()\n        im.save(f, \"JPEG\", quality=90, exif=b\"1\" * 65532)\n\n    def test_exif_typeerror(self):\n        with Image.open(\"Tests/images/exif_typeerror.jpg\") as im:\n            # Should not raise a TypeError\n            im._getexif()\n\n    def test_exif_gps(self):\n        # Arrange\n        with Image.open(\"Tests/images/exif_gps.jpg\") as im:\n            gps_index = 34853\n            expected_exif_gps = {\n                0: b\"\\x00\\x00\\x00\\x01\",\n                2: 4294967295,\n                5: b\"\\x01\",\n                30: 65535,\n                29: \"1999:99:99 99:99:99\",\n            }\n\n            # Act\n            exif = im._getexif()\n\n        # Assert\n        assert exif[gps_index] == expected_exif_gps\n\n    def test_exif_rollback(self):\n        # rolling back exif support in 3.1 to pre-3.0 formatting.\n        # expected from 2.9, with b/u qualifiers switched for 3.2 compatibility\n        # this test passes on 2.9 and 3.1, but not 3.0\n        expected_exif = {\n            34867: 4294967295,\n            258: (24, 24, 24),\n            36867: \"2099:09:29 10:10:10\",\n            34853: {\n                0: b\"\\x00\\x00\\x00\\x01\",\n                2: 4294967295,\n                5: b\"\\x01\",\n                30: 65535,\n                29: \"1999:99:99 99:99:99\",\n            },\n            296: 65535,\n            34665: 185,\n            41994: 65535,\n            514: 4294967295,\n            271: \"Make\",\n            272: \"XXX-XXX\",\n            305: \"PIL\",\n            42034: (1, 1, 1, 1),\n            42035: \"LensMake\",\n            34856: b\"\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa\",\n            282: 4294967295,\n            33434: 4294967295,\n        }\n\n        with Image.open(\"Tests/images/exif_gps.jpg\") as im:\n            exif = im._getexif()\n\n        for tag, value in expected_exif.items():\n            assert value == exif[tag]\n\n    def test_exif_gps_typeerror(self):\n        with Image.open(\"Tests/images/exif_gps_typeerror.jpg\") as im:\n\n            # Should not raise a TypeError\n            im._getexif()\n\n    def test_progressive_compat(self):\n        im1 = self.roundtrip(hopper())\n        assert not im1.info.get(\"progressive\")\n        assert not im1.info.get(\"progression\")\n\n        im2 = self.roundtrip(hopper(), progressive=0)\n        im3 = self.roundtrip(hopper(), progression=0)  # compatibility\n        assert not im2.info.get(\"progressive\")\n        assert not im2.info.get(\"progression\")\n        assert not im3.info.get(\"progressive\")\n        assert not im3.info.get(\"progression\")\n\n        im2 = self.roundtrip(hopper(), progressive=1)\n        im3 = self.roundtrip(hopper(), progression=1)  # compatibility\n        assert_image_equal(im1, im2)\n        assert_image_equal(im1, im3)\n        assert im2.info.get(\"progressive\")\n        assert im2.info.get(\"progression\")\n        assert im3.info.get(\"progressive\")\n        assert im3.info.get(\"progression\")\n\n    def test_quality(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), quality=50)\n        assert_image(im1, im2.mode, im2.size)\n        assert im1.bytes >= im2.bytes\n\n        im3 = self.roundtrip(hopper(), quality=0)\n        assert_image(im1, im3.mode, im3.size)\n        assert im2.bytes > im3.bytes\n\n    def test_smooth(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), smooth=100)\n        assert_image(im1, im2.mode, im2.size)\n\n    def test_subsampling(self):\n        def getsampling(im):\n            layer = im.layer\n            return layer[0][1:3] + layer[1][1:3] + layer[2][1:3]\n\n        # experimental API\n        im = self.roundtrip(hopper(), subsampling=-1)  # default\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=0)  # 4:4:4\n        assert getsampling(im) == (1, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=1)  # 4:2:2\n        assert getsampling(im) == (2, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=2)  # 4:2:0\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=3)  # default (undefined)\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n\n        im = self.roundtrip(hopper(), subsampling=\"4:4:4\")\n        assert getsampling(im) == (1, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:2:2\")\n        assert getsampling(im) == (2, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:2:0\")\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:1:1\")\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n\n        with pytest.raises(TypeError):\n            self.roundtrip(hopper(), subsampling=\"1:1:1\")\n\n    def test_exif(self):\n        with Image.open(\"Tests/images/pil_sample_rgb.jpg\") as im:\n            info = im._getexif()\n            assert info[305] == \"Adobe Photoshop CS Macintosh\"\n\n    def test_mp(self):\n        with Image.open(\"Tests/images/pil_sample_rgb.jpg\") as im:\n            assert im._getmp() is None\n\n    def test_quality_keep(self, tmp_path):\n        # RGB\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n        # Grayscale\n        with Image.open(\"Tests/images/hopper_gray.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n        # CMYK\n        with Image.open(\"Tests/images/pil_sample_cmyk.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n\n    def test_junk_jpeg_header(self):\n        # https://github.com/python-pillow/Pillow/issues/630\n        filename = \"Tests/images/junk_jpeg_header.jpg\"\n        with Image.open(filename):\n            pass\n\n    def test_ff00_jpeg_header(self):\n        filename = \"Tests/images/jpeg_ff00_header.jpg\"\n        with Image.open(filename):\n            pass\n\n    def test_truncated_jpeg_should_read_all_the_data(self):\n        filename = \"Tests/images/truncated_jpeg.jpg\"\n        ImageFile.LOAD_TRUNCATED_IMAGES = True\n        with Image.open(filename) as im:\n            im.load()\n            ImageFile.LOAD_TRUNCATED_IMAGES = False\n            assert im.getbbox() is not None\n\n    def test_truncated_jpeg_throws_oserror(self):\n        filename = \"Tests/images/truncated_jpeg.jpg\"\n        with Image.open(filename) as im:\n            with pytest.raises(OSError):\n                im.load()\n\n            # Test that the error is raised if loaded a second time\n            with pytest.raises(OSError):\n                im.load()\n\n    def test_qtables(self, tmp_path):\n        def _n_qtables_helper(n, test_file):\n            with Image.open(test_file) as im:\n                f = str(tmp_path / \"temp.jpg\")\n                im.save(f, qtables=[[n] * 64] * n)\n            with Image.open(f) as im:\n                assert len(im.quantization) == n\n                reloaded = self.roundtrip(im, qtables=\"keep\")\n                assert im.quantization == reloaded.quantization\n\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            qtables = im.quantization\n            reloaded = self.roundtrip(im, qtables=qtables, subsampling=0)\n            assert im.quantization == reloaded.quantization\n            assert_image_similar(im, self.roundtrip(im, qtables=\"web_low\"), 30)\n            assert_image_similar(im, self.roundtrip(im, qtables=\"web_high\"), 30)\n            assert_image_similar(im, self.roundtrip(im, qtables=\"keep\"), 30)\n\n            # valid bounds for baseline qtable\n            bounds_qtable = [int(s) for s in (\"255 1 \" * 32).split(None)]\n            self.roundtrip(im, qtables=[bounds_qtable])\n\n            # values from wizard.txt in jpeg9-a src package.\n            standard_l_qtable = [\n                int(s)\n                for s in \"\"\"\n                16  11  10  16  24  40  51  61\n                12  12  14  19  26  58  60  55\n                14  13  16  24  40  57  69  56\n                14  17  22  29  51  87  80  62\n                18  22  37  56  68 109 103  77\n                24  35  55  64  81 104 113  92\n                49  64  78  87 103 121 120 101\n                72  92  95  98 112 100 103  99\n                \"\"\".split(\n                    None\n                )\n            ]\n\n            standard_chrominance_qtable = [\n                int(s)\n                for s in \"\"\"\n                17  18  24  47  99  99  99  99\n                18  21  26  66  99  99  99  99\n                24  26  56  99  99  99  99  99\n                47  66  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                \"\"\".split(\n                    None\n                )\n            ]\n            # list of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables=[standard_l_qtable, standard_chrominance_qtable]\n                ),\n                30,\n            )\n\n            # tuple of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables=(standard_l_qtable, standard_chrominance_qtable)\n                ),\n                30,\n            )\n\n            # dict of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables={0: standard_l_qtable, 1: standard_chrominance_qtable}\n                ),\n                30,\n            )\n\n            _n_qtables_helper(1, \"Tests/images/hopper_gray.jpg\")\n            _n_qtables_helper(1, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(2, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(3, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(1, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(2, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(3, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(4, \"Tests/images/pil_sample_cmyk.jpg\")\n\n            # not a sequence\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=\"a\")\n            # sequence wrong length\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[])\n            # sequence wrong length\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[1, 2, 3, 4, 5])\n\n            # qtable entry not a sequence\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[1])\n            # qtable entry has wrong number of items\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[[1, 2, 3, 4]])\n\n    @pytest.mark.skipif(not djpeg_available(), reason=\"djpeg not available\")\n    def test_load_djpeg(self):\n        with Image.open(TEST_FILE) as img:\n            img.load_djpeg()\n            assert_image_similar(img, Image.open(TEST_FILE), 5)\n\n    @pytest.mark.skipif(not cjpeg_available(), reason=\"cjpeg not available\")\n    def test_save_cjpeg(self, tmp_path):\n        with Image.open(TEST_FILE) as img:\n            tempfile = str(tmp_path / \"temp.jpg\")\n            JpegImagePlugin._save_cjpeg(img, 0, tempfile)\n            # Default save quality is 75%, so a tiny bit of difference is alright\n            assert_image_similar(img, Image.open(tempfile), 17)\n\n    def test_no_duplicate_0x1001_tag(self):\n        # Arrange\n        tag_ids = {v: k for k, v in ExifTags.TAGS.items()}\n\n        # Assert\n        assert tag_ids[\"RelatedImageWidth\"] == 0x1001\n        assert tag_ids[\"RelatedImageLength\"] == 0x1002\n\n    def test_MAXBLOCK_scaling(self, tmp_path):\n        im = self.gen_random_image((512, 512))\n        f = str(tmp_path / \"temp.jpeg\")\n        im.save(f, quality=100, optimize=True)\n\n        with Image.open(f) as reloaded:\n            # none of these should crash\n            reloaded.save(f, quality=\"keep\")\n            reloaded.save(f, quality=\"keep\", progressive=True)\n            reloaded.save(f, quality=\"keep\", optimize=True)\n\n    def test_bad_mpo_header(self):\n        \"\"\" Treat unknown MPO as JPEG \"\"\"\n        # Arrange\n\n        # Act\n        # Shouldn't raise error\n        fn = \"Tests/images/sugarshack_bad_mpo_header.jpg\"\n        with pytest.warns(UserWarning, Image.open, fn) as im:\n\n            # Assert\n            assert im.format == \"JPEG\"\n\n    def test_save_correct_modes(self):\n        out = BytesIO()\n        for mode in [\"1\", \"L\", \"RGB\", \"RGBX\", \"CMYK\", \"YCbCr\"]:\n            img = Image.new(mode, (20, 20))\n            img.save(out, \"JPEG\")\n\n    def test_save_wrong_modes(self):\n        # ref https://github.com/python-pillow/Pillow/issues/2005\n        out = BytesIO()\n        for mode in [\"LA\", \"La\", \"RGBA\", \"RGBa\", \"P\"]:\n            img = Image.new(mode, (20, 20))\n            with pytest.raises(OSError):\n                img.save(out, \"JPEG\")\n\n    def test_save_tiff_with_dpi(self, tmp_path):\n        # Arrange\n        outfile = str(tmp_path / \"temp.tif\")\n        with Image.open(\"Tests/images/hopper.tif\") as im:\n\n            # Act\n            im.save(outfile, \"JPEG\", dpi=im.info[\"dpi\"])\n\n            # Assert\n            with Image.open(outfile) as reloaded:\n                reloaded.load()\n                assert im.info[\"dpi\"] == reloaded.info[\"dpi\"]\n\n    def test_load_dpi_rounding(self):\n        # Round up\n        with Image.open(\"Tests/images/iptc_roundUp.jpg\") as im:\n            assert im.info[\"dpi\"] == (44, 44)\n\n        # Round down\n        with Image.open(\"Tests/images/iptc_roundDown.jpg\") as im:\n            assert im.info[\"dpi\"] == (2, 2)\n\n    def test_save_dpi_rounding(self, tmp_path):\n        outfile = str(tmp_path / \"temp.jpg\")\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            im.save(outfile, dpi=(72.2, 72.2))\n\n            with Image.open(outfile) as reloaded:\n                assert reloaded.info[\"dpi\"] == (72, 72)\n\n            im.save(outfile, dpi=(72.8, 72.8))\n\n        with Image.open(outfile) as reloaded:\n            assert reloaded.info[\"dpi\"] == (73, 73)\n\n    def test_dpi_tuple_from_exif(self):\n        # Arrange\n        # This Photoshop CC 2017 image has DPI in EXIF not metadata\n        # EXIF XResolution is (2000000, 10000)\n        with Image.open(\"Tests/images/photoshop-200dpi.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (200, 200)\n\n    def test_dpi_int_from_exif(self):\n        # Arrange\n        # This image has DPI in EXIF not metadata\n        # EXIF XResolution is 72\n        with Image.open(\"Tests/images/exif-72dpi-int.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_dpi_from_dpcm_exif(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with EXIF resolution unit set to cm:\n        # exiftool -exif:ResolutionUnit=cm photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/exif-200dpcm.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (508, 508)\n\n    def test_dpi_exif_zero_division(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with EXIF resolution set to 0/0:\n        # exiftool -XResolution=0/0 -YResolution=0/0 photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/exif-dpi-zerodivision.jpg\") as im:\n\n            # Act / Assert\n            # This should return the default, and not raise a ZeroDivisionError\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_no_dpi_in_exif(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with resolution removed from EXIF:\n        # exiftool \"-*resolution*\"= photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/no-dpi-in-exif.jpg\") as im:\n\n            # Act / Assert\n            # \"When the image resolution is unknown, 72 [dpi] is designated.\"\n            # http://www.exiv2.org/tags.html\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_invalid_exif(self):\n        # This is no-dpi-in-exif with the tiff header of the exif block\n        # hexedited from MM * to FF FF FF FF\n        with Image.open(\"Tests/images/invalid-exif.jpg\") as im:\n\n            # This should return the default, and not a SyntaxError or\n            # OSError for unidentified image.\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_exif_x_resolution(self, tmp_path):\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            exif = im.getexif()\n            assert exif[282] == 180\n\n            out = str(tmp_path / \"out.jpg\")\n            with pytest.warns(None) as record:\n                im.save(out, exif=exif)\n            assert len(record) == 0\n\n        with Image.open(out) as reloaded:\n            assert reloaded.getexif()[282] == 180\n\n    def test_invalid_exif_x_resolution(self):\n        # When no x or y resolution is defined in EXIF\n        with Image.open(\"Tests/images/invalid-exif-without-x-resolution.jpg\") as im:\n\n            # This should return the default, and not a ValueError or\n            # OSError for an unidentified image.\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_ifd_offset_exif(self):\n        # Arrange\n        # This image has been manually hexedited to have an IFD offset of 10,\n        # in contrast to normal 8\n        with Image.open(\"Tests/images/exif-ifd-offset.jpg\") as im:\n\n            # Act / Assert\n            assert im._getexif()[306] == \"2017:03:13 23:03:09\"\n\n    def test_photoshop(self):\n        with Image.open(\"Tests/images/photoshop-200dpi.jpg\") as im:\n            assert im.info[\"photoshop\"][0x03ED] == {\n                \"XResolution\": 200.0,\n                \"DisplayedUnitsX\": 1,\n                \"YResolution\": 200.0,\n                \"DisplayedUnitsY\": 1,\n            }\n\n            # Test that the image can still load, even with broken Photoshop data\n            # This image had the APP13 length hexedited to be smaller\n            with Image.open(\"Tests/images/photoshop-200dpi-broken.jpg\") as im_broken:\n                assert_image_equal(im_broken, im)\n\n        # This image does not contain a Photoshop header string\n        with Image.open(\"Tests/images/app13.jpg\") as im:\n            assert \"photoshop\" not in im.info\n\n    def test_photoshop_malformed_and_multiple(self):\n        with Image.open(\"Tests/images/app13-multiple.jpg\") as im:\n            assert \"photoshop\" in im.info\n            assert 24 == len(im.info[\"photoshop\"])\n            apps_13_lengths = [len(v) for k, v in im.applist if k == \"APP13\"]\n            assert [65504, 24] == apps_13_lengths\n\n    def test_icc_after_SOF(self):\n        with Image.open(\"Tests/images/icc-after-SOF.jpg\") as im:\n            assert im.info[\"icc_profile\"] == b\"profile\"",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 23,
                            "end_lineno": 707,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "Tests/test_file_jpeg.py",
                            "type": "method",
                            "name": "TestFileJpeg.test_exif_x_resolution",
                            "content": "class TestFileJpeg:\n    def roundtrip(self, im, **options):\n        out = BytesIO()\n        im.save(out, \"JPEG\", **options)\n        test_bytes = out.tell()\n        out.seek(0)\n        im = Image.open(out)\n        im.bytes = test_bytes  # for testing only\n        return im\n\n    def gen_random_image(self, size, mode=\"RGB\"):\n        \"\"\" Generates a very hard to compress file\n        :param size: tuple\n        :param mode: optional image mode\n\n        \"\"\"\n        return Image.frombytes(mode, size, os.urandom(size[0] * size[1] * len(mode)))\n\n    def test_sanity(self):\n\n        # internal version number\n        assert re.search(r\"\\d+\\.\\d+$\", Image.core.jpeglib_version)\n\n        with Image.open(TEST_FILE) as im:\n            im.load()\n            assert im.mode == \"RGB\"\n            assert im.size == (128, 128)\n            assert im.format == \"JPEG\"\n            assert im.get_format_mimetype() == \"image/jpeg\"\n\n    def test_app(self):\n        # Test APP/COM reader (@PIL135)\n        with Image.open(TEST_FILE) as im:\n            assert im.applist[0] == (\"APP0\", b\"JFIF\\x00\\x01\\x01\\x01\\x00`\\x00`\\x00\\x00\")\n            assert im.applist[1] == (\n                \"COM\",\n                b\"File written by Adobe Photoshop\\xa8 4.0\\x00\",\n            )\n            assert len(im.applist) == 2\n\n            assert im.info[\"comment\"] == b\"File written by Adobe Photoshop\\xa8 4.0\\x00\"\n\n    def test_cmyk(self):\n        # Test CMYK handling.  Thanks to Tim and Charlie for test data,\n        # Michael for getting me to look one more time.\n        f = \"Tests/images/pil_sample_cmyk.jpg\"\n        with Image.open(f) as im:\n            # the source image has red pixels in the upper left corner.\n            c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))]\n            assert c == 0.0\n            assert m > 0.8\n            assert y > 0.8\n            assert k == 0.0\n            # the opposite corner is black\n            c, m, y, k = [\n                x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1))\n            ]\n            assert k > 0.9\n            # roundtrip, and check again\n            im = self.roundtrip(im)\n            c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))]\n            assert c == 0.0\n            assert m > 0.8\n            assert y > 0.8\n            assert k == 0.0\n            c, m, y, k = [\n                x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1))\n            ]\n            assert k > 0.9\n\n    def test_dpi(self):\n        def test(xdpi, ydpi=None):\n            with Image.open(TEST_FILE) as im:\n                im = self.roundtrip(im, dpi=(xdpi, ydpi or xdpi))\n            return im.info.get(\"dpi\")\n\n        assert test(72) == (72, 72)\n        assert test(300) == (300, 300)\n        assert test(100, 200) == (100, 200)\n        assert test(0) is None  # square pixels\n\n    def test_icc(self, tmp_path):\n        # Test ICC support\n        with Image.open(\"Tests/images/rgb.jpg\") as im1:\n            icc_profile = im1.info[\"icc_profile\"]\n            assert len(icc_profile) == 3144\n            # Roundtrip via physical file.\n            f = str(tmp_path / \"temp.jpg\")\n            im1.save(f, icc_profile=icc_profile)\n        with Image.open(f) as im2:\n            assert im2.info.get(\"icc_profile\") == icc_profile\n            # Roundtrip via memory buffer.\n            im1 = self.roundtrip(hopper())\n            im2 = self.roundtrip(hopper(), icc_profile=icc_profile)\n            assert_image_equal(im1, im2)\n            assert not im1.info.get(\"icc_profile\")\n            assert im2.info.get(\"icc_profile\")\n\n    def test_icc_big(self):\n        # Make sure that the \"extra\" support handles large blocks\n        def test(n):\n            # The ICC APP marker can store 65519 bytes per marker, so\n            # using a 4-byte test code should allow us to detect out of\n            # order issues.\n            icc_profile = (b\"Test\" * int(n / 4 + 1))[:n]\n            assert len(icc_profile) == n  # sanity\n            im1 = self.roundtrip(hopper(), icc_profile=icc_profile)\n            assert im1.info.get(\"icc_profile\") == (icc_profile or None)\n\n        test(0)\n        test(1)\n        test(3)\n        test(4)\n        test(5)\n        test(65533 - 14)  # full JPEG marker block\n        test(65533 - 14 + 1)  # full block plus one byte\n        test(ImageFile.MAXBLOCK)  # full buffer block\n        test(ImageFile.MAXBLOCK + 1)  # full buffer block plus one byte\n        test(ImageFile.MAXBLOCK * 4 + 3)  # large block\n\n    def test_large_icc_meta(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        # Sometimes the meta data on the icc_profile block is bigger than\n        # Image.MAXBLOCK or the image size.\n        with Image.open(\"Tests/images/icc_profile_big.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            icc_profile = im.info[\"icc_profile\"]\n            # Should not raise OSError for image with icc larger than image size.\n            im.save(\n                f,\n                format=\"JPEG\",\n                progressive=True,\n                quality=95,\n                icc_profile=icc_profile,\n                optimize=True,\n            )\n\n    def test_optimize(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), optimize=0)\n        im3 = self.roundtrip(hopper(), optimize=1)\n        assert_image_equal(im1, im2)\n        assert_image_equal(im1, im3)\n        assert im1.bytes >= im2.bytes\n        assert im1.bytes >= im3.bytes\n\n    def test_optimize_large_buffer(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        f = str(tmp_path / \"temp.jpg\")\n        # this requires ~ 1.5x Image.MAXBLOCK\n        im = Image.new(\"RGB\", (4096, 4096), 0xFF3333)\n        im.save(f, format=\"JPEG\", optimize=True)\n\n    def test_progressive(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), progressive=False)\n        im3 = self.roundtrip(hopper(), progressive=True)\n        assert not im1.info.get(\"progressive\")\n        assert not im2.info.get(\"progressive\")\n        assert im3.info.get(\"progressive\")\n\n        assert_image_equal(im1, im3)\n        assert im1.bytes >= im3.bytes\n\n    def test_progressive_large_buffer(self, tmp_path):\n        f = str(tmp_path / \"temp.jpg\")\n        # this requires ~ 1.5x Image.MAXBLOCK\n        im = Image.new(\"RGB\", (4096, 4096), 0xFF3333)\n        im.save(f, format=\"JPEG\", progressive=True)\n\n    def test_progressive_large_buffer_highest_quality(self, tmp_path):\n        f = str(tmp_path / \"temp.jpg\")\n        im = self.gen_random_image((255, 255))\n        # this requires more bytes than pixels in the image\n        im.save(f, format=\"JPEG\", progressive=True, quality=100)\n\n    def test_progressive_cmyk_buffer(self):\n        # Issue 2272, quality 90 cmyk image is tripping the large buffer bug.\n        f = BytesIO()\n        im = self.gen_random_image((256, 256), \"CMYK\")\n        im.save(f, format=\"JPEG\", progressive=True, quality=94)\n\n    def test_large_exif(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        f = str(tmp_path / \"temp.jpg\")\n        im = hopper()\n        im.save(f, \"JPEG\", quality=90, exif=b\"1\" * 65532)\n\n    def test_exif_typeerror(self):\n        with Image.open(\"Tests/images/exif_typeerror.jpg\") as im:\n            # Should not raise a TypeError\n            im._getexif()\n\n    def test_exif_gps(self):\n        # Arrange\n        with Image.open(\"Tests/images/exif_gps.jpg\") as im:\n            gps_index = 34853\n            expected_exif_gps = {\n                0: b\"\\x00\\x00\\x00\\x01\",\n                2: 4294967295,\n                5: b\"\\x01\",\n                30: 65535,\n                29: \"1999:99:99 99:99:99\",\n            }\n\n            # Act\n            exif = im._getexif()\n\n        # Assert\n        assert exif[gps_index] == expected_exif_gps\n\n    def test_exif_rollback(self):\n        # rolling back exif support in 3.1 to pre-3.0 formatting.\n        # expected from 2.9, with b/u qualifiers switched for 3.2 compatibility\n        # this test passes on 2.9 and 3.1, but not 3.0\n        expected_exif = {\n            34867: 4294967295,\n            258: (24, 24, 24),\n            36867: \"2099:09:29 10:10:10\",\n            34853: {\n                0: b\"\\x00\\x00\\x00\\x01\",\n                2: 4294967295,\n                5: b\"\\x01\",\n                30: 65535,\n                29: \"1999:99:99 99:99:99\",\n            },\n            296: 65535,\n            34665: 185,\n            41994: 65535,\n            514: 4294967295,\n            271: \"Make\",\n            272: \"XXX-XXX\",\n            305: \"PIL\",\n            42034: (1, 1, 1, 1),\n            42035: \"LensMake\",\n            34856: b\"\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa\",\n            282: 4294967295,\n            33434: 4294967295,\n        }\n\n        with Image.open(\"Tests/images/exif_gps.jpg\") as im:\n            exif = im._getexif()\n\n        for tag, value in expected_exif.items():\n            assert value == exif[tag]\n\n    def test_exif_gps_typeerror(self):\n        with Image.open(\"Tests/images/exif_gps_typeerror.jpg\") as im:\n\n            # Should not raise a TypeError\n            im._getexif()\n\n    def test_progressive_compat(self):\n        im1 = self.roundtrip(hopper())\n        assert not im1.info.get(\"progressive\")\n        assert not im1.info.get(\"progression\")\n\n        im2 = self.roundtrip(hopper(), progressive=0)\n        im3 = self.roundtrip(hopper(), progression=0)  # compatibility\n        assert not im2.info.get(\"progressive\")\n        assert not im2.info.get(\"progression\")\n        assert not im3.info.get(\"progressive\")\n        assert not im3.info.get(\"progression\")\n\n        im2 = self.roundtrip(hopper(), progressive=1)\n        im3 = self.roundtrip(hopper(), progression=1)  # compatibility\n        assert_image_equal(im1, im2)\n        assert_image_equal(im1, im3)\n        assert im2.info.get(\"progressive\")\n        assert im2.info.get(\"progression\")\n        assert im3.info.get(\"progressive\")\n        assert im3.info.get(\"progression\")\n\n    def test_quality(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), quality=50)\n        assert_image(im1, im2.mode, im2.size)\n        assert im1.bytes >= im2.bytes\n\n        im3 = self.roundtrip(hopper(), quality=0)\n        assert_image(im1, im3.mode, im3.size)\n        assert im2.bytes > im3.bytes\n\n    def test_smooth(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), smooth=100)\n        assert_image(im1, im2.mode, im2.size)\n\n    def test_subsampling(self):\n        def getsampling(im):\n            layer = im.layer\n            return layer[0][1:3] + layer[1][1:3] + layer[2][1:3]\n\n        # experimental API\n        im = self.roundtrip(hopper(), subsampling=-1)  # default\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=0)  # 4:4:4\n        assert getsampling(im) == (1, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=1)  # 4:2:2\n        assert getsampling(im) == (2, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=2)  # 4:2:0\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=3)  # default (undefined)\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n\n        im = self.roundtrip(hopper(), subsampling=\"4:4:4\")\n        assert getsampling(im) == (1, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:2:2\")\n        assert getsampling(im) == (2, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:2:0\")\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:1:1\")\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n\n        with pytest.raises(TypeError):\n            self.roundtrip(hopper(), subsampling=\"1:1:1\")\n\n    def test_exif(self):\n        with Image.open(\"Tests/images/pil_sample_rgb.jpg\") as im:\n            info = im._getexif()\n            assert info[305] == \"Adobe Photoshop CS Macintosh\"\n\n    def test_mp(self):\n        with Image.open(\"Tests/images/pil_sample_rgb.jpg\") as im:\n            assert im._getmp() is None\n\n    def test_quality_keep(self, tmp_path):\n        # RGB\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n        # Grayscale\n        with Image.open(\"Tests/images/hopper_gray.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n        # CMYK\n        with Image.open(\"Tests/images/pil_sample_cmyk.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n\n    def test_junk_jpeg_header(self):\n        # https://github.com/python-pillow/Pillow/issues/630\n        filename = \"Tests/images/junk_jpeg_header.jpg\"\n        with Image.open(filename):\n            pass\n\n    def test_ff00_jpeg_header(self):\n        filename = \"Tests/images/jpeg_ff00_header.jpg\"\n        with Image.open(filename):\n            pass\n\n    def test_truncated_jpeg_should_read_all_the_data(self):\n        filename = \"Tests/images/truncated_jpeg.jpg\"\n        ImageFile.LOAD_TRUNCATED_IMAGES = True\n        with Image.open(filename) as im:\n            im.load()\n            ImageFile.LOAD_TRUNCATED_IMAGES = False\n            assert im.getbbox() is not None\n\n    def test_truncated_jpeg_throws_oserror(self):\n        filename = \"Tests/images/truncated_jpeg.jpg\"\n        with Image.open(filename) as im:\n            with pytest.raises(OSError):\n                im.load()\n\n            # Test that the error is raised if loaded a second time\n            with pytest.raises(OSError):\n                im.load()\n\n    def test_qtables(self, tmp_path):\n        def _n_qtables_helper(n, test_file):\n            with Image.open(test_file) as im:\n                f = str(tmp_path / \"temp.jpg\")\n                im.save(f, qtables=[[n] * 64] * n)\n            with Image.open(f) as im:\n                assert len(im.quantization) == n\n                reloaded = self.roundtrip(im, qtables=\"keep\")\n                assert im.quantization == reloaded.quantization\n\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            qtables = im.quantization\n            reloaded = self.roundtrip(im, qtables=qtables, subsampling=0)\n            assert im.quantization == reloaded.quantization\n            assert_image_similar(im, self.roundtrip(im, qtables=\"web_low\"), 30)\n            assert_image_similar(im, self.roundtrip(im, qtables=\"web_high\"), 30)\n            assert_image_similar(im, self.roundtrip(im, qtables=\"keep\"), 30)\n\n            # valid bounds for baseline qtable\n            bounds_qtable = [int(s) for s in (\"255 1 \" * 32).split(None)]\n            self.roundtrip(im, qtables=[bounds_qtable])\n\n            # values from wizard.txt in jpeg9-a src package.\n            standard_l_qtable = [\n                int(s)\n                for s in \"\"\"\n                16  11  10  16  24  40  51  61\n                12  12  14  19  26  58  60  55\n                14  13  16  24  40  57  69  56\n                14  17  22  29  51  87  80  62\n                18  22  37  56  68 109 103  77\n                24  35  55  64  81 104 113  92\n                49  64  78  87 103 121 120 101\n                72  92  95  98 112 100 103  99\n                \"\"\".split(\n                    None\n                )\n            ]\n\n            standard_chrominance_qtable = [\n                int(s)\n                for s in \"\"\"\n                17  18  24  47  99  99  99  99\n                18  21  26  66  99  99  99  99\n                24  26  56  99  99  99  99  99\n                47  66  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                \"\"\".split(\n                    None\n                )\n            ]\n            # list of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables=[standard_l_qtable, standard_chrominance_qtable]\n                ),\n                30,\n            )\n\n            # tuple of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables=(standard_l_qtable, standard_chrominance_qtable)\n                ),\n                30,\n            )\n\n            # dict of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables={0: standard_l_qtable, 1: standard_chrominance_qtable}\n                ),\n                30,\n            )\n\n            _n_qtables_helper(1, \"Tests/images/hopper_gray.jpg\")\n            _n_qtables_helper(1, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(2, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(3, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(1, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(2, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(3, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(4, \"Tests/images/pil_sample_cmyk.jpg\")\n\n            # not a sequence\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=\"a\")\n            # sequence wrong length\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[])\n            # sequence wrong length\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[1, 2, 3, 4, 5])\n\n            # qtable entry not a sequence\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[1])\n            # qtable entry has wrong number of items\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[[1, 2, 3, 4]])\n\n    @pytest.mark.skipif(not djpeg_available(), reason=\"djpeg not available\")\n    def test_load_djpeg(self):\n        with Image.open(TEST_FILE) as img:\n            img.load_djpeg()\n            assert_image_similar(img, Image.open(TEST_FILE), 5)\n\n    @pytest.mark.skipif(not cjpeg_available(), reason=\"cjpeg not available\")\n    def test_save_cjpeg(self, tmp_path):\n        with Image.open(TEST_FILE) as img:\n            tempfile = str(tmp_path / \"temp.jpg\")\n            JpegImagePlugin._save_cjpeg(img, 0, tempfile)\n            # Default save quality is 75%, so a tiny bit of difference is alright\n            assert_image_similar(img, Image.open(tempfile), 17)\n\n    def test_no_duplicate_0x1001_tag(self):\n        # Arrange\n        tag_ids = {v: k for k, v in ExifTags.TAGS.items()}\n\n        # Assert\n        assert tag_ids[\"RelatedImageWidth\"] == 0x1001\n        assert tag_ids[\"RelatedImageLength\"] == 0x1002\n\n    def test_MAXBLOCK_scaling(self, tmp_path):\n        im = self.gen_random_image((512, 512))\n        f = str(tmp_path / \"temp.jpeg\")\n        im.save(f, quality=100, optimize=True)\n\n        with Image.open(f) as reloaded:\n            # none of these should crash\n            reloaded.save(f, quality=\"keep\")\n            reloaded.save(f, quality=\"keep\", progressive=True)\n            reloaded.save(f, quality=\"keep\", optimize=True)\n\n    def test_bad_mpo_header(self):\n        \"\"\" Treat unknown MPO as JPEG \"\"\"\n        # Arrange\n\n        # Act\n        # Shouldn't raise error\n        fn = \"Tests/images/sugarshack_bad_mpo_header.jpg\"\n        with pytest.warns(UserWarning, Image.open, fn) as im:\n\n            # Assert\n            assert im.format == \"JPEG\"\n\n    def test_save_correct_modes(self):\n        out = BytesIO()\n        for mode in [\"1\", \"L\", \"RGB\", \"RGBX\", \"CMYK\", \"YCbCr\"]:\n            img = Image.new(mode, (20, 20))\n            img.save(out, \"JPEG\")\n\n    def test_save_wrong_modes(self):\n        # ref https://github.com/python-pillow/Pillow/issues/2005\n        out = BytesIO()\n        for mode in [\"LA\", \"La\", \"RGBA\", \"RGBa\", \"P\"]:\n            img = Image.new(mode, (20, 20))\n            with pytest.raises(OSError):\n                img.save(out, \"JPEG\")\n\n    def test_save_tiff_with_dpi(self, tmp_path):\n        # Arrange\n        outfile = str(tmp_path / \"temp.tif\")\n        with Image.open(\"Tests/images/hopper.tif\") as im:\n\n            # Act\n            im.save(outfile, \"JPEG\", dpi=im.info[\"dpi\"])\n\n            # Assert\n            with Image.open(outfile) as reloaded:\n                reloaded.load()\n                assert im.info[\"dpi\"] == reloaded.info[\"dpi\"]\n\n    def test_load_dpi_rounding(self):\n        # Round up\n        with Image.open(\"Tests/images/iptc_roundUp.jpg\") as im:\n            assert im.info[\"dpi\"] == (44, 44)\n\n        # Round down\n        with Image.open(\"Tests/images/iptc_roundDown.jpg\") as im:\n            assert im.info[\"dpi\"] == (2, 2)\n\n    def test_save_dpi_rounding(self, tmp_path):\n        outfile = str(tmp_path / \"temp.jpg\")\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            im.save(outfile, dpi=(72.2, 72.2))\n\n            with Image.open(outfile) as reloaded:\n                assert reloaded.info[\"dpi\"] == (72, 72)\n\n            im.save(outfile, dpi=(72.8, 72.8))\n\n        with Image.open(outfile) as reloaded:\n            assert reloaded.info[\"dpi\"] == (73, 73)\n\n    def test_dpi_tuple_from_exif(self):\n        # Arrange\n        # This Photoshop CC 2017 image has DPI in EXIF not metadata\n        # EXIF XResolution is (2000000, 10000)\n        with Image.open(\"Tests/images/photoshop-200dpi.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (200, 200)\n\n    def test_dpi_int_from_exif(self):\n        # Arrange\n        # This image has DPI in EXIF not metadata\n        # EXIF XResolution is 72\n        with Image.open(\"Tests/images/exif-72dpi-int.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_dpi_from_dpcm_exif(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with EXIF resolution unit set to cm:\n        # exiftool -exif:ResolutionUnit=cm photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/exif-200dpcm.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (508, 508)\n\n    def test_dpi_exif_zero_division(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with EXIF resolution set to 0/0:\n        # exiftool -XResolution=0/0 -YResolution=0/0 photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/exif-dpi-zerodivision.jpg\") as im:\n\n            # Act / Assert\n            # This should return the default, and not raise a ZeroDivisionError\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_no_dpi_in_exif(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with resolution removed from EXIF:\n        # exiftool \"-*resolution*\"= photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/no-dpi-in-exif.jpg\") as im:\n\n            # Act / Assert\n            # \"When the image resolution is unknown, 72 [dpi] is designated.\"\n            # http://www.exiv2.org/tags.html\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_invalid_exif(self):\n        # This is no-dpi-in-exif with the tiff header of the exif block\n        # hexedited from MM * to FF FF FF FF\n        with Image.open(\"Tests/images/invalid-exif.jpg\") as im:\n\n            # This should return the default, and not a SyntaxError or\n            # OSError for unidentified image.\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_exif_x_resolution(self, tmp_path):\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            exif = im.getexif()\n            assert exif[282] == 180\n\n            out = str(tmp_path / \"out.jpg\")\n            with pytest.warns(None) as record:\n                im.save(out, exif=exif)\n            assert len(record) == 0\n\n        with Image.open(out) as reloaded:\n            assert reloaded.getexif()[282] == 180\n\n    def test_invalid_exif_x_resolution(self):\n        # When no x or y resolution is defined in EXIF\n        with Image.open(\"Tests/images/invalid-exif-without-x-resolution.jpg\") as im:\n\n            # This should return the default, and not a ValueError or\n            # OSError for an unidentified image.\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_ifd_offset_exif(self):\n        # Arrange\n        # This image has been manually hexedited to have an IFD offset of 10,\n        # in contrast to normal 8\n        with Image.open(\"Tests/images/exif-ifd-offset.jpg\") as im:\n\n            # Act / Assert\n            assert im._getexif()[306] == \"2017:03:13 23:03:09\"\n\n    def test_photoshop(self):\n        with Image.open(\"Tests/images/photoshop-200dpi.jpg\") as im:\n            assert im.info[\"photoshop\"][0x03ED] == {\n                \"XResolution\": 200.0,\n                \"DisplayedUnitsX\": 1,\n                \"YResolution\": 200.0,\n                \"DisplayedUnitsY\": 1,\n            }\n\n            # Test that the image can still load, even with broken Photoshop data\n            # This image had the APP13 length hexedited to be smaller\n            with Image.open(\"Tests/images/photoshop-200dpi-broken.jpg\") as im_broken:\n                assert_image_equal(im_broken, im)\n\n        # This image does not contain a Photoshop header string\n        with Image.open(\"Tests/images/app13.jpg\") as im:\n            assert \"photoshop\" not in im.info\n\n    def test_photoshop_malformed_and_multiple(self):\n        with Image.open(\"Tests/images/app13-multiple.jpg\") as im:\n            assert \"photoshop\" in im.info\n            assert 24 == len(im.info[\"photoshop\"])\n            apps_13_lengths = [len(v) for k, v in im.applist if k == \"APP13\"]\n            assert [65504, 24] == apps_13_lengths\n\n    def test_icc_after_SOF(self):\n        with Image.open(\"Tests/images/icc-after-SOF.jpg\") as im:\n            assert im.info[\"icc_profile\"] == b\"profile\"",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 650,
                            "end_lineno": 661,
                            "parent": {
                                "file_name": "Tests/test_file_jpeg.py",
                                "type": "class",
                                "name": "TestFileJpeg",
                                "content": "class TestFileJpeg:\n    def roundtrip(self, im, **options):\n        out = BytesIO()\n        im.save(out, \"JPEG\", **options)\n        test_bytes = out.tell()\n        out.seek(0)\n        im = Image.open(out)\n        im.bytes = test_bytes  # for testing only\n        return im\n\n    def gen_random_image(self, size, mode=\"RGB\"):\n        \"\"\" Generates a very hard to compress file\n        :param size: tuple\n        :param mode: optional image mode\n\n        \"\"\"\n        return Image.frombytes(mode, size, os.urandom(size[0] * size[1] * len(mode)))\n\n    def test_sanity(self):\n\n        # internal version number\n        assert re.search(r\"\\d+\\.\\d+$\", Image.core.jpeglib_version)\n\n        with Image.open(TEST_FILE) as im:\n            im.load()\n            assert im.mode == \"RGB\"\n            assert im.size == (128, 128)\n            assert im.format == \"JPEG\"\n            assert im.get_format_mimetype() == \"image/jpeg\"\n\n    def test_app(self):\n        # Test APP/COM reader (@PIL135)\n        with Image.open(TEST_FILE) as im:\n            assert im.applist[0] == (\"APP0\", b\"JFIF\\x00\\x01\\x01\\x01\\x00`\\x00`\\x00\\x00\")\n            assert im.applist[1] == (\n                \"COM\",\n                b\"File written by Adobe Photoshop\\xa8 4.0\\x00\",\n            )\n            assert len(im.applist) == 2\n\n            assert im.info[\"comment\"] == b\"File written by Adobe Photoshop\\xa8 4.0\\x00\"\n\n    def test_cmyk(self):\n        # Test CMYK handling.  Thanks to Tim and Charlie for test data,\n        # Michael for getting me to look one more time.\n        f = \"Tests/images/pil_sample_cmyk.jpg\"\n        with Image.open(f) as im:\n            # the source image has red pixels in the upper left corner.\n            c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))]\n            assert c == 0.0\n            assert m > 0.8\n            assert y > 0.8\n            assert k == 0.0\n            # the opposite corner is black\n            c, m, y, k = [\n                x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1))\n            ]\n            assert k > 0.9\n            # roundtrip, and check again\n            im = self.roundtrip(im)\n            c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))]\n            assert c == 0.0\n            assert m > 0.8\n            assert y > 0.8\n            assert k == 0.0\n            c, m, y, k = [\n                x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1))\n            ]\n            assert k > 0.9\n\n    def test_dpi(self):\n        def test(xdpi, ydpi=None):\n            with Image.open(TEST_FILE) as im:\n                im = self.roundtrip(im, dpi=(xdpi, ydpi or xdpi))\n            return im.info.get(\"dpi\")\n\n        assert test(72) == (72, 72)\n        assert test(300) == (300, 300)\n        assert test(100, 200) == (100, 200)\n        assert test(0) is None  # square pixels\n\n    def test_icc(self, tmp_path):\n        # Test ICC support\n        with Image.open(\"Tests/images/rgb.jpg\") as im1:\n            icc_profile = im1.info[\"icc_profile\"]\n            assert len(icc_profile) == 3144\n            # Roundtrip via physical file.\n            f = str(tmp_path / \"temp.jpg\")\n            im1.save(f, icc_profile=icc_profile)\n        with Image.open(f) as im2:\n            assert im2.info.get(\"icc_profile\") == icc_profile\n            # Roundtrip via memory buffer.\n            im1 = self.roundtrip(hopper())\n            im2 = self.roundtrip(hopper(), icc_profile=icc_profile)\n            assert_image_equal(im1, im2)\n            assert not im1.info.get(\"icc_profile\")\n            assert im2.info.get(\"icc_profile\")\n\n    def test_icc_big(self):\n        # Make sure that the \"extra\" support handles large blocks\n        def test(n):\n            # The ICC APP marker can store 65519 bytes per marker, so\n            # using a 4-byte test code should allow us to detect out of\n            # order issues.\n            icc_profile = (b\"Test\" * int(n / 4 + 1))[:n]\n            assert len(icc_profile) == n  # sanity\n            im1 = self.roundtrip(hopper(), icc_profile=icc_profile)\n            assert im1.info.get(\"icc_profile\") == (icc_profile or None)\n\n        test(0)\n        test(1)\n        test(3)\n        test(4)\n        test(5)\n        test(65533 - 14)  # full JPEG marker block\n        test(65533 - 14 + 1)  # full block plus one byte\n        test(ImageFile.MAXBLOCK)  # full buffer block\n        test(ImageFile.MAXBLOCK + 1)  # full buffer block plus one byte\n        test(ImageFile.MAXBLOCK * 4 + 3)  # large block\n\n    def test_large_icc_meta(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        # Sometimes the meta data on the icc_profile block is bigger than\n        # Image.MAXBLOCK or the image size.\n        with Image.open(\"Tests/images/icc_profile_big.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            icc_profile = im.info[\"icc_profile\"]\n            # Should not raise OSError for image with icc larger than image size.\n            im.save(\n                f,\n                format=\"JPEG\",\n                progressive=True,\n                quality=95,\n                icc_profile=icc_profile,\n                optimize=True,\n            )\n\n    def test_optimize(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), optimize=0)\n        im3 = self.roundtrip(hopper(), optimize=1)\n        assert_image_equal(im1, im2)\n        assert_image_equal(im1, im3)\n        assert im1.bytes >= im2.bytes\n        assert im1.bytes >= im3.bytes\n\n    def test_optimize_large_buffer(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        f = str(tmp_path / \"temp.jpg\")\n        # this requires ~ 1.5x Image.MAXBLOCK\n        im = Image.new(\"RGB\", (4096, 4096), 0xFF3333)\n        im.save(f, format=\"JPEG\", optimize=True)\n\n    def test_progressive(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), progressive=False)\n        im3 = self.roundtrip(hopper(), progressive=True)\n        assert not im1.info.get(\"progressive\")\n        assert not im2.info.get(\"progressive\")\n        assert im3.info.get(\"progressive\")\n\n        assert_image_equal(im1, im3)\n        assert im1.bytes >= im3.bytes\n\n    def test_progressive_large_buffer(self, tmp_path):\n        f = str(tmp_path / \"temp.jpg\")\n        # this requires ~ 1.5x Image.MAXBLOCK\n        im = Image.new(\"RGB\", (4096, 4096), 0xFF3333)\n        im.save(f, format=\"JPEG\", progressive=True)\n\n    def test_progressive_large_buffer_highest_quality(self, tmp_path):\n        f = str(tmp_path / \"temp.jpg\")\n        im = self.gen_random_image((255, 255))\n        # this requires more bytes than pixels in the image\n        im.save(f, format=\"JPEG\", progressive=True, quality=100)\n\n    def test_progressive_cmyk_buffer(self):\n        # Issue 2272, quality 90 cmyk image is tripping the large buffer bug.\n        f = BytesIO()\n        im = self.gen_random_image((256, 256), \"CMYK\")\n        im.save(f, format=\"JPEG\", progressive=True, quality=94)\n\n    def test_large_exif(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        f = str(tmp_path / \"temp.jpg\")\n        im = hopper()\n        im.save(f, \"JPEG\", quality=90, exif=b\"1\" * 65532)\n\n    def test_exif_typeerror(self):\n        with Image.open(\"Tests/images/exif_typeerror.jpg\") as im:\n            # Should not raise a TypeError\n            im._getexif()\n\n    def test_exif_gps(self):\n        # Arrange\n        with Image.open(\"Tests/images/exif_gps.jpg\") as im:\n            gps_index = 34853\n            expected_exif_gps = {\n                0: b\"\\x00\\x00\\x00\\x01\",\n                2: 4294967295,\n                5: b\"\\x01\",\n                30: 65535,\n                29: \"1999:99:99 99:99:99\",\n            }\n\n            # Act\n            exif = im._getexif()\n\n        # Assert\n        assert exif[gps_index] == expected_exif_gps\n\n    def test_exif_rollback(self):\n        # rolling back exif support in 3.1 to pre-3.0 formatting.\n        # expected from 2.9, with b/u qualifiers switched for 3.2 compatibility\n        # this test passes on 2.9 and 3.1, but not 3.0\n        expected_exif = {\n            34867: 4294967295,\n            258: (24, 24, 24),\n            36867: \"2099:09:29 10:10:10\",\n            34853: {\n                0: b\"\\x00\\x00\\x00\\x01\",\n                2: 4294967295,\n                5: b\"\\x01\",\n                30: 65535,\n                29: \"1999:99:99 99:99:99\",\n            },\n            296: 65535,\n            34665: 185,\n            41994: 65535,\n            514: 4294967295,\n            271: \"Make\",\n            272: \"XXX-XXX\",\n            305: \"PIL\",\n            42034: (1, 1, 1, 1),\n            42035: \"LensMake\",\n            34856: b\"\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa\",\n            282: 4294967295,\n            33434: 4294967295,\n        }\n\n        with Image.open(\"Tests/images/exif_gps.jpg\") as im:\n            exif = im._getexif()\n\n        for tag, value in expected_exif.items():\n            assert value == exif[tag]\n\n    def test_exif_gps_typeerror(self):\n        with Image.open(\"Tests/images/exif_gps_typeerror.jpg\") as im:\n\n            # Should not raise a TypeError\n            im._getexif()\n\n    def test_progressive_compat(self):\n        im1 = self.roundtrip(hopper())\n        assert not im1.info.get(\"progressive\")\n        assert not im1.info.get(\"progression\")\n\n        im2 = self.roundtrip(hopper(), progressive=0)\n        im3 = self.roundtrip(hopper(), progression=0)  # compatibility\n        assert not im2.info.get(\"progressive\")\n        assert not im2.info.get(\"progression\")\n        assert not im3.info.get(\"progressive\")\n        assert not im3.info.get(\"progression\")\n\n        im2 = self.roundtrip(hopper(), progressive=1)\n        im3 = self.roundtrip(hopper(), progression=1)  # compatibility\n        assert_image_equal(im1, im2)\n        assert_image_equal(im1, im3)\n        assert im2.info.get(\"progressive\")\n        assert im2.info.get(\"progression\")\n        assert im3.info.get(\"progressive\")\n        assert im3.info.get(\"progression\")\n\n    def test_quality(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), quality=50)\n        assert_image(im1, im2.mode, im2.size)\n        assert im1.bytes >= im2.bytes\n\n        im3 = self.roundtrip(hopper(), quality=0)\n        assert_image(im1, im3.mode, im3.size)\n        assert im2.bytes > im3.bytes\n\n    def test_smooth(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), smooth=100)\n        assert_image(im1, im2.mode, im2.size)\n\n    def test_subsampling(self):\n        def getsampling(im):\n            layer = im.layer\n            return layer[0][1:3] + layer[1][1:3] + layer[2][1:3]\n\n        # experimental API\n        im = self.roundtrip(hopper(), subsampling=-1)  # default\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=0)  # 4:4:4\n        assert getsampling(im) == (1, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=1)  # 4:2:2\n        assert getsampling(im) == (2, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=2)  # 4:2:0\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=3)  # default (undefined)\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n\n        im = self.roundtrip(hopper(), subsampling=\"4:4:4\")\n        assert getsampling(im) == (1, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:2:2\")\n        assert getsampling(im) == (2, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:2:0\")\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:1:1\")\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n\n        with pytest.raises(TypeError):\n            self.roundtrip(hopper(), subsampling=\"1:1:1\")\n\n    def test_exif(self):\n        with Image.open(\"Tests/images/pil_sample_rgb.jpg\") as im:\n            info = im._getexif()\n            assert info[305] == \"Adobe Photoshop CS Macintosh\"\n\n    def test_mp(self):\n        with Image.open(\"Tests/images/pil_sample_rgb.jpg\") as im:\n            assert im._getmp() is None\n\n    def test_quality_keep(self, tmp_path):\n        # RGB\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n        # Grayscale\n        with Image.open(\"Tests/images/hopper_gray.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n        # CMYK\n        with Image.open(\"Tests/images/pil_sample_cmyk.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n\n    def test_junk_jpeg_header(self):\n        # https://github.com/python-pillow/Pillow/issues/630\n        filename = \"Tests/images/junk_jpeg_header.jpg\"\n        with Image.open(filename):\n            pass\n\n    def test_ff00_jpeg_header(self):\n        filename = \"Tests/images/jpeg_ff00_header.jpg\"\n        with Image.open(filename):\n            pass\n\n    def test_truncated_jpeg_should_read_all_the_data(self):\n        filename = \"Tests/images/truncated_jpeg.jpg\"\n        ImageFile.LOAD_TRUNCATED_IMAGES = True\n        with Image.open(filename) as im:\n            im.load()\n            ImageFile.LOAD_TRUNCATED_IMAGES = False\n            assert im.getbbox() is not None\n\n    def test_truncated_jpeg_throws_oserror(self):\n        filename = \"Tests/images/truncated_jpeg.jpg\"\n        with Image.open(filename) as im:\n            with pytest.raises(OSError):\n                im.load()\n\n            # Test that the error is raised if loaded a second time\n            with pytest.raises(OSError):\n                im.load()\n\n    def test_qtables(self, tmp_path):\n        def _n_qtables_helper(n, test_file):\n            with Image.open(test_file) as im:\n                f = str(tmp_path / \"temp.jpg\")\n                im.save(f, qtables=[[n] * 64] * n)\n            with Image.open(f) as im:\n                assert len(im.quantization) == n\n                reloaded = self.roundtrip(im, qtables=\"keep\")\n                assert im.quantization == reloaded.quantization\n\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            qtables = im.quantization\n            reloaded = self.roundtrip(im, qtables=qtables, subsampling=0)\n            assert im.quantization == reloaded.quantization\n            assert_image_similar(im, self.roundtrip(im, qtables=\"web_low\"), 30)\n            assert_image_similar(im, self.roundtrip(im, qtables=\"web_high\"), 30)\n            assert_image_similar(im, self.roundtrip(im, qtables=\"keep\"), 30)\n\n            # valid bounds for baseline qtable\n            bounds_qtable = [int(s) for s in (\"255 1 \" * 32).split(None)]\n            self.roundtrip(im, qtables=[bounds_qtable])\n\n            # values from wizard.txt in jpeg9-a src package.\n            standard_l_qtable = [\n                int(s)\n                for s in \"\"\"\n                16  11  10  16  24  40  51  61\n                12  12  14  19  26  58  60  55\n                14  13  16  24  40  57  69  56\n                14  17  22  29  51  87  80  62\n                18  22  37  56  68 109 103  77\n                24  35  55  64  81 104 113  92\n                49  64  78  87 103 121 120 101\n                72  92  95  98 112 100 103  99\n                \"\"\".split(\n                    None\n                )\n            ]\n\n            standard_chrominance_qtable = [\n                int(s)\n                for s in \"\"\"\n                17  18  24  47  99  99  99  99\n                18  21  26  66  99  99  99  99\n                24  26  56  99  99  99  99  99\n                47  66  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                \"\"\".split(\n                    None\n                )\n            ]\n            # list of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables=[standard_l_qtable, standard_chrominance_qtable]\n                ),\n                30,\n            )\n\n            # tuple of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables=(standard_l_qtable, standard_chrominance_qtable)\n                ),\n                30,\n            )\n\n            # dict of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables={0: standard_l_qtable, 1: standard_chrominance_qtable}\n                ),\n                30,\n            )\n\n            _n_qtables_helper(1, \"Tests/images/hopper_gray.jpg\")\n            _n_qtables_helper(1, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(2, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(3, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(1, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(2, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(3, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(4, \"Tests/images/pil_sample_cmyk.jpg\")\n\n            # not a sequence\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=\"a\")\n            # sequence wrong length\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[])\n            # sequence wrong length\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[1, 2, 3, 4, 5])\n\n            # qtable entry not a sequence\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[1])\n            # qtable entry has wrong number of items\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[[1, 2, 3, 4]])\n\n    @pytest.mark.skipif(not djpeg_available(), reason=\"djpeg not available\")\n    def test_load_djpeg(self):\n        with Image.open(TEST_FILE) as img:\n            img.load_djpeg()\n            assert_image_similar(img, Image.open(TEST_FILE), 5)\n\n    @pytest.mark.skipif(not cjpeg_available(), reason=\"cjpeg not available\")\n    def test_save_cjpeg(self, tmp_path):\n        with Image.open(TEST_FILE) as img:\n            tempfile = str(tmp_path / \"temp.jpg\")\n            JpegImagePlugin._save_cjpeg(img, 0, tempfile)\n            # Default save quality is 75%, so a tiny bit of difference is alright\n            assert_image_similar(img, Image.open(tempfile), 17)\n\n    def test_no_duplicate_0x1001_tag(self):\n        # Arrange\n        tag_ids = {v: k for k, v in ExifTags.TAGS.items()}\n\n        # Assert\n        assert tag_ids[\"RelatedImageWidth\"] == 0x1001\n        assert tag_ids[\"RelatedImageLength\"] == 0x1002\n\n    def test_MAXBLOCK_scaling(self, tmp_path):\n        im = self.gen_random_image((512, 512))\n        f = str(tmp_path / \"temp.jpeg\")\n        im.save(f, quality=100, optimize=True)\n\n        with Image.open(f) as reloaded:\n            # none of these should crash\n            reloaded.save(f, quality=\"keep\")\n            reloaded.save(f, quality=\"keep\", progressive=True)\n            reloaded.save(f, quality=\"keep\", optimize=True)\n\n    def test_bad_mpo_header(self):\n        \"\"\" Treat unknown MPO as JPEG \"\"\"\n        # Arrange\n\n        # Act\n        # Shouldn't raise error\n        fn = \"Tests/images/sugarshack_bad_mpo_header.jpg\"\n        with pytest.warns(UserWarning, Image.open, fn) as im:\n\n            # Assert\n            assert im.format == \"JPEG\"\n\n    def test_save_correct_modes(self):\n        out = BytesIO()\n        for mode in [\"1\", \"L\", \"RGB\", \"RGBX\", \"CMYK\", \"YCbCr\"]:\n            img = Image.new(mode, (20, 20))\n            img.save(out, \"JPEG\")\n\n    def test_save_wrong_modes(self):\n        # ref https://github.com/python-pillow/Pillow/issues/2005\n        out = BytesIO()\n        for mode in [\"LA\", \"La\", \"RGBA\", \"RGBa\", \"P\"]:\n            img = Image.new(mode, (20, 20))\n            with pytest.raises(OSError):\n                img.save(out, \"JPEG\")\n\n    def test_save_tiff_with_dpi(self, tmp_path):\n        # Arrange\n        outfile = str(tmp_path / \"temp.tif\")\n        with Image.open(\"Tests/images/hopper.tif\") as im:\n\n            # Act\n            im.save(outfile, \"JPEG\", dpi=im.info[\"dpi\"])\n\n            # Assert\n            with Image.open(outfile) as reloaded:\n                reloaded.load()\n                assert im.info[\"dpi\"] == reloaded.info[\"dpi\"]\n\n    def test_load_dpi_rounding(self):\n        # Round up\n        with Image.open(\"Tests/images/iptc_roundUp.jpg\") as im:\n            assert im.info[\"dpi\"] == (44, 44)\n\n        # Round down\n        with Image.open(\"Tests/images/iptc_roundDown.jpg\") as im:\n            assert im.info[\"dpi\"] == (2, 2)\n\n    def test_save_dpi_rounding(self, tmp_path):\n        outfile = str(tmp_path / \"temp.jpg\")\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            im.save(outfile, dpi=(72.2, 72.2))\n\n            with Image.open(outfile) as reloaded:\n                assert reloaded.info[\"dpi\"] == (72, 72)\n\n            im.save(outfile, dpi=(72.8, 72.8))\n\n        with Image.open(outfile) as reloaded:\n            assert reloaded.info[\"dpi\"] == (73, 73)\n\n    def test_dpi_tuple_from_exif(self):\n        # Arrange\n        # This Photoshop CC 2017 image has DPI in EXIF not metadata\n        # EXIF XResolution is (2000000, 10000)\n        with Image.open(\"Tests/images/photoshop-200dpi.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (200, 200)\n\n    def test_dpi_int_from_exif(self):\n        # Arrange\n        # This image has DPI in EXIF not metadata\n        # EXIF XResolution is 72\n        with Image.open(\"Tests/images/exif-72dpi-int.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_dpi_from_dpcm_exif(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with EXIF resolution unit set to cm:\n        # exiftool -exif:ResolutionUnit=cm photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/exif-200dpcm.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (508, 508)\n\n    def test_dpi_exif_zero_division(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with EXIF resolution set to 0/0:\n        # exiftool -XResolution=0/0 -YResolution=0/0 photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/exif-dpi-zerodivision.jpg\") as im:\n\n            # Act / Assert\n            # This should return the default, and not raise a ZeroDivisionError\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_no_dpi_in_exif(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with resolution removed from EXIF:\n        # exiftool \"-*resolution*\"= photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/no-dpi-in-exif.jpg\") as im:\n\n            # Act / Assert\n            # \"When the image resolution is unknown, 72 [dpi] is designated.\"\n            # http://www.exiv2.org/tags.html\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_invalid_exif(self):\n        # This is no-dpi-in-exif with the tiff header of the exif block\n        # hexedited from MM * to FF FF FF FF\n        with Image.open(\"Tests/images/invalid-exif.jpg\") as im:\n\n            # This should return the default, and not a SyntaxError or\n            # OSError for unidentified image.\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_exif_x_resolution(self, tmp_path):\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            exif = im.getexif()\n            assert exif[282] == 180\n\n            out = str(tmp_path / \"out.jpg\")\n            with pytest.warns(None) as record:\n                im.save(out, exif=exif)\n            assert len(record) == 0\n\n        with Image.open(out) as reloaded:\n            assert reloaded.getexif()[282] == 180\n\n    def test_invalid_exif_x_resolution(self):\n        # When no x or y resolution is defined in EXIF\n        with Image.open(\"Tests/images/invalid-exif-without-x-resolution.jpg\") as im:\n\n            # This should return the default, and not a ValueError or\n            # OSError for an unidentified image.\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_ifd_offset_exif(self):\n        # Arrange\n        # This image has been manually hexedited to have an IFD offset of 10,\n        # in contrast to normal 8\n        with Image.open(\"Tests/images/exif-ifd-offset.jpg\") as im:\n\n            # Act / Assert\n            assert im._getexif()[306] == \"2017:03:13 23:03:09\"\n\n    def test_photoshop(self):\n        with Image.open(\"Tests/images/photoshop-200dpi.jpg\") as im:\n            assert im.info[\"photoshop\"][0x03ED] == {\n                \"XResolution\": 200.0,\n                \"DisplayedUnitsX\": 1,\n                \"YResolution\": 200.0,\n                \"DisplayedUnitsY\": 1,\n            }\n\n            # Test that the image can still load, even with broken Photoshop data\n            # This image had the APP13 length hexedited to be smaller\n            with Image.open(\"Tests/images/photoshop-200dpi-broken.jpg\") as im_broken:\n                assert_image_equal(im_broken, im)\n\n        # This image does not contain a Photoshop header string\n        with Image.open(\"Tests/images/app13.jpg\") as im:\n            assert \"photoshop\" not in im.info\n\n    def test_photoshop_malformed_and_multiple(self):\n        with Image.open(\"Tests/images/app13-multiple.jpg\") as im:\n            assert \"photoshop\" in im.info\n            assert 24 == len(im.info[\"photoshop\"])\n            apps_13_lengths = [len(v) for k, v in im.applist if k == \"APP13\"]\n            assert [65504, 24] == apps_13_lengths\n\n    def test_icc_after_SOF(self):\n        with Image.open(\"Tests/images/icc-after-SOF.jpg\") as im:\n            assert im.info[\"icc_profile\"] == b\"profile\"",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 23,
                                "end_lineno": 707,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "#\n# The Python Imaging Library.\n# $Id$\n#\n# the Image class wrapper\n#\n# partial release history:\n# 1995-09-09 fl   Created\n# 1996-03-11 fl   PIL release 0.0 (proof of concept)\n# 1996-04-30 fl   PIL release 0.1b1\n# 1999-07-28 fl   PIL release 1.0 final\n# 2000-06-07 fl   PIL release 1.1\n# 2000-10-20 fl   PIL release 1.1.1\n# 2001-05-07 fl   PIL release 1.1.2\n# 2002-03-15 fl   PIL release 1.1.3\n# 2003-05-10 fl   PIL release 1.1.4\n# 2005-03-28 fl   PIL release 1.1.5\n# 2006-12-02 fl   PIL release 1.1.6\n# 2009-11-15 fl   PIL release 1.1.7\n#\n# Copyright (c) 1997-2009 by Secret Labs AB.  All rights reserved.\n# Copyright (c) 1995-2009 by Fredrik Lundh.\n#\n# See the README file for information on usage and redistribution.\n#\n\nimport atexit\nimport builtins\nimport io\nimport logging\nimport math\nimport numbers\nimport os\nimport struct\nimport sys\nimport tempfile\nimport warnings\nimport xml.etree.ElementTree\nfrom collections.abc import Callable, MutableMapping\nfrom pathlib import Path\n\n# VERSION was removed in Pillow 6.0.0.\n# PILLOW_VERSION is deprecated and will be removed in a future release.\n# Use __version__ instead.\nfrom . import (\n    ImageMode,\n    TiffTags,\n    UnidentifiedImageError,\n    __version__,\n    _plugins,\n    _raise_version_warning,\n)\nfrom ._binary import i8, i32le\nfrom ._util import deferred_error, isPath\n\nif sys.version_info >= (3, 7):\n\n    def __getattr__(name):\n        if name == \"PILLOW_VERSION\":\n            _raise_version_warning()\n            return __version__\n        raise AttributeError(\"module '{}' has no attribute '{}'\".format(__name__, name))\n\n\nelse:\n\n    from . import PILLOW_VERSION\n\n    # Silence warning\n    assert PILLOW_VERSION\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass DecompressionBombWarning(RuntimeWarning):\n    pass\n\n\nclass DecompressionBombError(Exception):\n    pass\n\n\n# Limit to around a quarter gigabyte for a 24 bit (3 bpp) image\nMAX_IMAGE_PIXELS = int(1024 * 1024 * 1024 // 4 // 3)\n\n\ntry:\n    # If the _imaging C module is not present, Pillow will not load.\n    # Note that other modules should not refer to _imaging directly;\n    # import Image and use the Image.core variable instead.\n    # Also note that Image.core is not a publicly documented interface,\n    # and should be considered private and subject to change.\n    from . import _imaging as core\n\n    if __version__ != getattr(core, \"PILLOW_VERSION\", None):\n        raise ImportError(\n            \"The _imaging extension was built for another version of Pillow or PIL:\\n\"\n            \"Core version: %s\\n\"\n            \"Pillow version: %s\" % (getattr(core, \"PILLOW_VERSION\", None), __version__)\n        )\n\nexcept ImportError as v:\n    core = deferred_error(ImportError(\"The _imaging C module is not installed.\"))\n    # Explanations for ways that we know we might have an import error\n    if str(v).startswith(\"Module use of python\"):\n        # The _imaging C module is present, but not compiled for\n        # the right version (windows only).  Print a warning, if\n        # possible.\n        warnings.warn(\n            \"The _imaging extension was built for another version of Python.\",\n            RuntimeWarning,\n        )\n    elif str(v).startswith(\"The _imaging extension\"):\n        warnings.warn(str(v), RuntimeWarning)\n    # Fail here anyway. Don't let people run with a mostly broken Pillow.\n    # see docs/porting.rst\n    raise\n\n\n# works everywhere, win for pypy, not cpython\nUSE_CFFI_ACCESS = hasattr(sys, \"pypy_version_info\")\ntry:\n    import cffi\nexcept ImportError:\n    cffi = None\n\n\ndef isImageType(t):\n    \"\"\"\n    Checks if an object is an image object.\n\n    .. warning::\n\n       This function is for internal use only.\n\n    :param t: object to check if it's an image\n    :returns: True if the object is an image\n    \"\"\"\n    return hasattr(t, \"im\")\n\n\n#\n# Constants\n\nNONE = 0\n\n# transpose\nFLIP_LEFT_RIGHT = 0\nFLIP_TOP_BOTTOM = 1\nROTATE_90 = 2\nROTATE_180 = 3\nROTATE_270 = 4\nTRANSPOSE = 5\nTRANSVERSE = 6\n\n# transforms (also defined in Imaging.h)\nAFFINE = 0\nEXTENT = 1\nPERSPECTIVE = 2\nQUAD = 3\nMESH = 4\n\n# resampling filters (also defined in Imaging.h)\nNEAREST = NONE = 0\nBOX = 4\nBILINEAR = LINEAR = 2\nHAMMING = 5\nBICUBIC = CUBIC = 3\nLANCZOS = ANTIALIAS = 1\n\n_filters_support = {BOX: 0.5, BILINEAR: 1.0, HAMMING: 1.0, BICUBIC: 2.0, LANCZOS: 3.0}\n\n\n# dithers\nNEAREST = NONE = 0\nORDERED = 1  # Not yet implemented\nRASTERIZE = 2  # Not yet implemented\nFLOYDSTEINBERG = 3  # default\n\n# palettes/quantizers\nWEB = 0\nADAPTIVE = 1\n\nMEDIANCUT = 0\nMAXCOVERAGE = 1\nFASTOCTREE = 2\nLIBIMAGEQUANT = 3\n\n# categories\nNORMAL = 0\nSEQUENCE = 1\nCONTAINER = 2\n\nif hasattr(core, \"DEFAULT_STRATEGY\"):\n    DEFAULT_STRATEGY = core.DEFAULT_STRATEGY\n    FILTERED = core.FILTERED\n    HUFFMAN_ONLY = core.HUFFMAN_ONLY\n    RLE = core.RLE\n    FIXED = core.FIXED\n\n\n# --------------------------------------------------------------------\n# Registries\n\nID = []\nOPEN = {}\nMIME = {}\nSAVE = {}\nSAVE_ALL = {}\nEXTENSION = {}\nDECODERS = {}\nENCODERS = {}\n\n# --------------------------------------------------------------------\n# Modes supported by this version\n\n_MODEINFO = {\n    # NOTE: this table will be removed in future versions.  use\n    # getmode* functions or ImageMode descriptors instead.\n    # official modes\n    \"1\": (\"L\", \"L\", (\"1\",)),\n    \"L\": (\"L\", \"L\", (\"L\",)),\n    \"I\": (\"L\", \"I\", (\"I\",)),\n    \"F\": (\"L\", \"F\", (\"F\",)),\n    \"P\": (\"P\", \"L\", (\"P\",)),\n    \"RGB\": (\"RGB\", \"L\", (\"R\", \"G\", \"B\")),\n    \"RGBX\": (\"RGB\", \"L\", (\"R\", \"G\", \"B\", \"X\")),\n    \"RGBA\": (\"RGB\", \"L\", (\"R\", \"G\", \"B\", \"A\")),\n    \"CMYK\": (\"RGB\", \"L\", (\"C\", \"M\", \"Y\", \"K\")),\n    \"YCbCr\": (\"RGB\", \"L\", (\"Y\", \"Cb\", \"Cr\")),\n    \"LAB\": (\"RGB\", \"L\", (\"L\", \"A\", \"B\")),\n    \"HSV\": (\"RGB\", \"L\", (\"H\", \"S\", \"V\")),\n    # Experimental modes include I;16, I;16L, I;16B, RGBa, BGR;15, and\n    # BGR;24.  Use these modes only if you know exactly what you're\n    # doing...\n}\n\nif sys.byteorder == \"little\":\n    _ENDIAN = \"<\"\nelse:\n    _ENDIAN = \">\"\n\n_MODE_CONV = {\n    # official modes\n    \"1\": (\"|b1\", None),  # Bits need to be extended to bytes\n    \"L\": (\"|u1\", None),\n    \"LA\": (\"|u1\", 2),\n    \"I\": (_ENDIAN + \"i4\", None),\n    \"F\": (_ENDIAN + \"f4\", None),\n    \"P\": (\"|u1\", None),\n    \"RGB\": (\"|u1\", 3),\n    \"RGBX\": (\"|u1\", 4),\n    \"RGBA\": (\"|u1\", 4),\n    \"CMYK\": (\"|u1\", 4),\n    \"YCbCr\": (\"|u1\", 3),\n    \"LAB\": (\"|u1\", 3),  # UNDONE - unsigned |u1i1i1\n    \"HSV\": (\"|u1\", 3),\n    # I;16 == I;16L, and I;32 == I;32L\n    \"I;16\": (\"<u2\", None),\n    \"I;16B\": (\">u2\", None),\n    \"I;16L\": (\"<u2\", None),\n    \"I;16S\": (\"<i2\", None),\n    \"I;16BS\": (\">i2\", None),\n    \"I;16LS\": (\"<i2\", None),\n    \"I;32\": (\"<u4\", None),\n    \"I;32B\": (\">u4\", None),\n    \"I;32L\": (\"<u4\", None),\n    \"I;32S\": (\"<i4\", None),\n    \"I;32BS\": (\">i4\", None),\n    \"I;32LS\": (\"<i4\", None),\n}\n\n\ndef _conv_type_shape(im):\n    typ, extra = _MODE_CONV[im.mode]\n    if extra is None:\n        return (im.size[1], im.size[0]), typ\n    else:\n        return (im.size[1], im.size[0], extra), typ\n\n\nMODES = sorted(_MODEINFO)\n\n# raw modes that may be memory mapped.  NOTE: if you change this, you\n# may have to modify the stride calculation in map.c too!\n_MAPMODES = (\"L\", \"P\", \"RGBX\", \"RGBA\", \"CMYK\", \"I;16\", \"I;16L\", \"I;16B\")\n\n\ndef getmodebase(mode):\n    \"\"\"\n    Gets the \"base\" mode for given mode.  This function returns \"L\" for\n    images that contain grayscale data, and \"RGB\" for images that\n    contain color data.\n\n    :param mode: Input mode.\n    :returns: \"L\" or \"RGB\".\n    :exception KeyError: If the input mode was not a standard mode.\n    \"\"\"\n    return ImageMode.getmode(mode).basemode\n\n\ndef getmodetype(mode):\n    \"\"\"\n    Gets the storage type mode.  Given a mode, this function returns a\n    single-layer mode suitable for storing individual bands.\n\n    :param mode: Input mode.\n    :returns: \"L\", \"I\", or \"F\".\n    :exception KeyError: If the input mode was not a standard mode.\n    \"\"\"\n    return ImageMode.getmode(mode).basetype\n\n\ndef getmodebandnames(mode):\n    \"\"\"\n    Gets a list of individual band names.  Given a mode, this function returns\n    a tuple containing the names of individual bands (use\n    :py:method:`~PIL.Image.getmodetype` to get the mode used to store each\n    individual band.\n\n    :param mode: Input mode.\n    :returns: A tuple containing band names.  The length of the tuple\n        gives the number of bands in an image of the given mode.\n    :exception KeyError: If the input mode was not a standard mode.\n    \"\"\"\n    return ImageMode.getmode(mode).bands\n\n\ndef getmodebands(mode):\n    \"\"\"\n    Gets the number of individual bands for this mode.\n\n    :param mode: Input mode.\n    :returns: The number of bands in this mode.\n    :exception KeyError: If the input mode was not a standard mode.\n    \"\"\"\n    return len(ImageMode.getmode(mode).bands)\n\n\n# --------------------------------------------------------------------\n# Helpers\n\n_initialized = 0\n\n\ndef preinit():\n    \"\"\"Explicitly load standard file format drivers.\"\"\"\n\n    global _initialized\n    if _initialized >= 1:\n        return\n\n    try:\n        from . import BmpImagePlugin\n\n        assert BmpImagePlugin\n    except ImportError:\n        pass\n    try:\n        from . import GifImagePlugin\n\n        assert GifImagePlugin\n    except ImportError:\n        pass\n    try:\n        from . import JpegImagePlugin\n\n        assert JpegImagePlugin\n    except ImportError:\n        pass\n    try:\n        from . import PpmImagePlugin\n\n        assert PpmImagePlugin\n    except ImportError:\n        pass\n    try:\n        from . import PngImagePlugin\n\n        assert PngImagePlugin\n    except ImportError:\n        pass\n    # try:\n    #     import TiffImagePlugin\n    #     assert TiffImagePlugin\n    # except ImportError:\n    #     pass\n\n    _initialized = 1\n\n\ndef init():\n    \"\"\"\n    Explicitly initializes the Python Imaging Library. This function\n    loads all available file format drivers.\n    \"\"\"\n\n    global _initialized\n    if _initialized >= 2:\n        return 0\n\n    for plugin in _plugins:\n        try:\n            logger.debug(\"Importing %s\", plugin)\n            __import__(\"PIL.%s\" % plugin, globals(), locals(), [])\n        except ImportError as e:\n            logger.debug(\"Image: failed to import %s: %s\", plugin, e)\n\n    if OPEN or SAVE:\n        _initialized = 2\n        return 1\n\n\n# --------------------------------------------------------------------\n# Codec factories (used by tobytes/frombytes and ImageFile.load)\n\n\ndef _getdecoder(mode, decoder_name, args, extra=()):\n\n    # tweak arguments\n    if args is None:\n        args = ()\n    elif not isinstance(args, tuple):\n        args = (args,)\n\n    try:\n        decoder = DECODERS[decoder_name]\n    except KeyError:\n        pass\n    else:\n        return decoder(mode, *args + extra)\n\n    try:\n        # get decoder\n        decoder = getattr(core, decoder_name + \"_decoder\")\n    except AttributeError:\n        raise OSError(\"decoder %s not available\" % decoder_name)\n    return decoder(mode, *args + extra)\n\n\ndef _getencoder(mode, encoder_name, args, extra=()):\n\n    # tweak arguments\n    if args is None:\n        args = ()\n    elif not isinstance(args, tuple):\n        args = (args,)\n\n    try:\n        encoder = ENCODERS[encoder_name]\n    except KeyError:\n        pass\n    else:\n        return encoder(mode, *args + extra)\n\n    try:\n        # get encoder\n        encoder = getattr(core, encoder_name + \"_encoder\")\n    except AttributeError:\n        raise OSError(\"encoder %s not available\" % encoder_name)\n    return encoder(mode, *args + extra)\n\n\n# --------------------------------------------------------------------\n# Simple expression analyzer\n\n\ndef coerce_e(value):\n    return value if isinstance(value, _E) else _E(value)\n\n\nclass _E:\n    def __init__(self, data):\n        self.data = data\n\n    def __add__(self, other):\n        return _E((self.data, \"__add__\", coerce_e(other).data))\n\n    def __mul__(self, other):\n        return _E((self.data, \"__mul__\", coerce_e(other).data))\n\n\ndef _getscaleoffset(expr):\n    stub = [\"stub\"]\n    data = expr(_E(stub)).data\n    try:\n        (a, b, c) = data  # simplified syntax\n        if a is stub and b == \"__mul__\" and isinstance(c, numbers.Number):\n            return c, 0.0\n        if a is stub and b == \"__add__\" and isinstance(c, numbers.Number):\n            return 1.0, c\n    except TypeError:\n        pass\n    try:\n        ((a, b, c), d, e) = data  # full syntax\n        if (\n            a is stub\n            and b == \"__mul__\"\n            and isinstance(c, numbers.Number)\n            and d == \"__add__\"\n            and isinstance(e, numbers.Number)\n        ):\n            return c, e\n    except TypeError:\n        pass\n    raise ValueError(\"illegal expression\")\n\n\n# --------------------------------------------------------------------\n# Implementation wrapper\n\n\nclass Image:\n    \"\"\"\n    This class represents an image object.  To create\n    :py:class:`~PIL.Image.Image` objects, use the appropriate factory\n    functions.  There's hardly ever any reason to call the Image constructor\n    directly.\n\n    * :py:func:`~PIL.Image.open`\n    * :py:func:`~PIL.Image.new`\n    * :py:func:`~PIL.Image.frombytes`\n    \"\"\"\n\n    format = None\n    format_description = None\n    _close_exclusive_fp_after_loading = True\n\n    def __init__(self):\n        # FIXME: take \"new\" parameters / other image?\n        # FIXME: turn mode and size into delegating properties?\n        self.im = None\n        self.mode = \"\"\n        self._size = (0, 0)\n        self.palette = None\n        self.info = {}\n        self.category = NORMAL\n        self.readonly = 0\n        self.pyaccess = None\n        self._exif = None\n\n    @property\n    def width(self):\n        return self.size[0]\n\n    @property\n    def height(self):\n        return self.size[1]\n\n    @property\n    def size(self):\n        return self._size\n\n    def _new(self, im):\n        new = Image()\n        new.im = im\n        new.mode = im.mode\n        new._size = im.size\n        if im.mode in (\"P\", \"PA\"):\n            if self.palette:\n                new.palette = self.palette.copy()\n            else:\n                from . import ImagePalette\n\n                new.palette = ImagePalette.ImagePalette()\n        new.info = self.info.copy()\n        return new\n\n    # Context manager support\n    def __enter__(self):\n        return self\n\n    def __exit__(self, *args):\n        if hasattr(self, \"fp\") and getattr(self, \"_exclusive_fp\", False):\n            if hasattr(self, \"_close__fp\"):\n                self._close__fp()\n            if self.fp:\n                self.fp.close()\n        self.fp = None\n\n    def close(self):\n        \"\"\"\n        Closes the file pointer, if possible.\n\n        This operation will destroy the image core and release its memory.\n        The image data will be unusable afterward.\n\n        This function is only required to close images that have not\n        had their file read and closed by the\n        :py:meth:`~PIL.Image.Image.load` method. See\n        :ref:`file-handling` for more information.\n        \"\"\"\n        try:\n            if hasattr(self, \"_close__fp\"):\n                self._close__fp()\n            self.fp.close()\n            self.fp = None\n        except Exception as msg:\n            logger.debug(\"Error closing: %s\", msg)\n\n        if getattr(self, \"map\", None):\n            self.map = None\n\n        # Instead of simply setting to None, we're setting up a\n        # deferred error that will better explain that the core image\n        # object is gone.\n        self.im = deferred_error(ValueError(\"Operation on closed image\"))\n\n    def _copy(self):\n        self.load()\n        self.im = self.im.copy()\n        self.pyaccess = None\n        self.readonly = 0\n\n    def _ensure_mutable(self):\n        if self.readonly:\n            self._copy()\n        else:\n            self.load()\n\n    def _dump(self, file=None, format=None, **options):\n        suffix = \"\"\n        if format:\n            suffix = \".\" + format\n\n        if not file:\n            f, filename = tempfile.mkstemp(suffix)\n            os.close(f)\n        else:\n            filename = file\n            if not filename.endswith(suffix):\n                filename = filename + suffix\n\n        self.load()\n\n        if not format or format == \"PPM\":\n            self.im.save_ppm(filename)\n        else:\n            self.save(filename, format, **options)\n\n        return filename\n\n    def __eq__(self, other):\n        return (\n            self.__class__ is other.__class__\n            and self.mode == other.mode\n            and self.size == other.size\n            and self.info == other.info\n            and self.category == other.category\n            and self.readonly == other.readonly\n            and self.getpalette() == other.getpalette()\n            and self.tobytes() == other.tobytes()\n        )\n\n    def __repr__(self):\n        return \"<%s.%s image mode=%s size=%dx%d at 0x%X>\" % (\n            self.__class__.__module__,\n            self.__class__.__name__,\n            self.mode,\n            self.size[0],\n            self.size[1],\n            id(self),\n        )\n\n    def _repr_png_(self):\n        \"\"\" iPython display hook support\n\n        :returns: png version of the image as bytes\n        \"\"\"\n        b = io.BytesIO()\n        self.save(b, \"PNG\")\n        return b.getvalue()\n\n    @property\n    def __array_interface__(self):\n        # numpy array interface support\n        new = {}\n        shape, typestr = _conv_type_shape(self)\n        new[\"shape\"] = shape\n        new[\"typestr\"] = typestr\n        new[\"version\"] = 3\n        if self.mode == \"1\":\n            # Binary images need to be extended from bits to bytes\n            # See: https://github.com/python-pillow/Pillow/issues/350\n            new[\"data\"] = self.tobytes(\"raw\", \"L\")\n        else:\n            new[\"data\"] = self.tobytes()\n        return new\n\n    def __getstate__(self):\n        return [self.info, self.mode, self.size, self.getpalette(), self.tobytes()]\n\n    def __setstate__(self, state):\n        Image.__init__(self)\n        self.tile = []\n        info, mode, size, palette, data = state\n        self.info = info\n        self.mode = mode\n        self._size = size\n        self.im = core.new(mode, size)\n        if mode in (\"L\", \"LA\", \"P\", \"PA\") and palette:\n            self.putpalette(palette)\n        self.frombytes(data)\n\n    def tobytes(self, encoder_name=\"raw\", *args):\n        \"\"\"\n        Return image as a bytes object.\n\n        .. warning::\n\n            This method returns the raw image data from the internal\n            storage.  For compressed image data (e.g. PNG, JPEG) use\n            :meth:`~.save`, with a BytesIO parameter for in-memory\n            data.\n\n        :param encoder_name: What encoder to use.  The default is to\n                             use the standard \"raw\" encoder.\n        :param args: Extra arguments to the encoder.\n        :rtype: A bytes object.\n        \"\"\"\n\n        # may pass tuple instead of argument list\n        if len(args) == 1 and isinstance(args[0], tuple):\n            args = args[0]\n\n        if encoder_name == \"raw\" and args == ():\n            args = self.mode\n\n        self.load()\n\n        # unpack data\n        e = _getencoder(self.mode, encoder_name, args)\n        e.setimage(self.im)\n\n        bufsize = max(65536, self.size[0] * 4)  # see RawEncode.c\n\n        data = []\n        while True:\n            l, s, d = e.encode(bufsize)\n            data.append(d)\n            if s:\n                break\n        if s < 0:\n            raise RuntimeError(\"encoder error %d in tobytes\" % s)\n\n        return b\"\".join(data)\n\n    def tostring(self, *args, **kw):\n        raise NotImplementedError(\n            \"tostring() has been removed. Please call tobytes() instead.\"\n        )\n\n    def tobitmap(self, name=\"image\"):\n        \"\"\"\n        Returns the image converted to an X11 bitmap.\n\n        .. note:: This method only works for mode \"1\" images.\n\n        :param name: The name prefix to use for the bitmap variables.\n        :returns: A string containing an X11 bitmap.\n        :raises ValueError: If the mode is not \"1\"\n        \"\"\"\n\n        self.load()\n        if self.mode != \"1\":\n            raise ValueError(\"not a bitmap\")\n        data = self.tobytes(\"xbm\")\n        return b\"\".join(\n            [\n                (\"#define %s_width %d\\n\" % (name, self.size[0])).encode(\"ascii\"),\n                (\"#define %s_height %d\\n\" % (name, self.size[1])).encode(\"ascii\"),\n                (\"static char %s_bits[] = {\\n\" % name).encode(\"ascii\"),\n                data,\n                b\"};\",\n            ]\n        )\n\n    def frombytes(self, data, decoder_name=\"raw\", *args):\n        \"\"\"\n        Loads this image with pixel data from a bytes object.\n\n        This method is similar to the :py:func:`~PIL.Image.frombytes` function,\n        but loads data into this image instead of creating a new image object.\n        \"\"\"\n\n        # may pass tuple instead of argument list\n        if len(args) == 1 and isinstance(args[0], tuple):\n            args = args[0]\n\n        # default format\n        if decoder_name == \"raw\" and args == ():\n            args = self.mode\n\n        # unpack data\n        d = _getdecoder(self.mode, decoder_name, args)\n        d.setimage(self.im)\n        s = d.decode(data)\n\n        if s[0] >= 0:\n            raise ValueError(\"not enough image data\")\n        if s[1] != 0:\n            raise ValueError(\"cannot decode image data\")\n\n    def fromstring(self, *args, **kw):\n        raise NotImplementedError(\n            \"fromstring() has been removed. Please call frombytes() instead.\"\n        )\n\n    def load(self):\n        \"\"\"\n        Allocates storage for the image and loads the pixel data.  In\n        normal cases, you don't need to call this method, since the\n        Image class automatically loads an opened image when it is\n        accessed for the first time.\n\n        If the file associated with the image was opened by Pillow, then this\n        method will close it. The exception to this is if the image has\n        multiple frames, in which case the file will be left open for seek\n        operations. See :ref:`file-handling` for more information.\n\n        :returns: An image access object.\n        :rtype: :ref:`PixelAccess` or :py:class:`PIL.PyAccess`\n        \"\"\"\n        if self.im and self.palette and self.palette.dirty:\n            # realize palette\n            self.im.putpalette(*self.palette.getdata())\n            self.palette.dirty = 0\n            self.palette.mode = \"RGB\"\n            self.palette.rawmode = None\n            if \"transparency\" in self.info:\n                if isinstance(self.info[\"transparency\"], int):\n                    self.im.putpalettealpha(self.info[\"transparency\"], 0)\n                else:\n                    self.im.putpalettealphas(self.info[\"transparency\"])\n                self.palette.mode = \"RGBA\"\n\n        if self.im:\n            if cffi and USE_CFFI_ACCESS:\n                if self.pyaccess:\n                    return self.pyaccess\n                from . import PyAccess\n\n                self.pyaccess = PyAccess.new(self, self.readonly)\n                if self.pyaccess:\n                    return self.pyaccess\n            return self.im.pixel_access(self.readonly)\n\n    def verify(self):\n        \"\"\"\n        Verifies the contents of a file. For data read from a file, this\n        method attempts to determine if the file is broken, without\n        actually decoding the image data.  If this method finds any\n        problems, it raises suitable exceptions.  If you need to load\n        the image after using this method, you must reopen the image\n        file.\n        \"\"\"\n        pass\n\n    def convert(self, mode=None, matrix=None, dither=None, palette=WEB, colors=256):\n        \"\"\"\n        Returns a converted copy of this image. For the \"P\" mode, this\n        method translates pixels through the palette.  If mode is\n        omitted, a mode is chosen so that all information in the image\n        and the palette can be represented without a palette.\n\n        The current version supports all possible conversions between\n        \"L\", \"RGB\" and \"CMYK.\" The **matrix** argument only supports \"L\"\n        and \"RGB\".\n\n        When translating a color image to greyscale (mode \"L\"),\n        the library uses the ITU-R 601-2 luma transform::\n\n            L = R * 299/1000 + G * 587/1000 + B * 114/1000\n\n        The default method of converting a greyscale (\"L\") or \"RGB\"\n        image into a bilevel (mode \"1\") image uses Floyd-Steinberg\n        dither to approximate the original image luminosity levels. If\n        dither is NONE, all values larger than 128 are set to 255 (white),\n        all other values to 0 (black). To use other thresholds, use the\n        :py:meth:`~PIL.Image.Image.point` method.\n\n        When converting from \"RGBA\" to \"P\" without a **matrix** argument,\n        this passes the operation to :py:meth:`~PIL.Image.Image.quantize`,\n        and **dither** and **palette** are ignored.\n\n        :param mode: The requested mode. See: :ref:`concept-modes`.\n        :param matrix: An optional conversion matrix.  If given, this\n           should be 4- or 12-tuple containing floating point values.\n        :param dither: Dithering method, used when converting from\n           mode \"RGB\" to \"P\" or from \"RGB\" or \"L\" to \"1\".\n           Available methods are NONE or FLOYDSTEINBERG (default).\n           Note that this is not used when **matrix** is supplied.\n        :param palette: Palette to use when converting from mode \"RGB\"\n           to \"P\".  Available palettes are WEB or ADAPTIVE.\n        :param colors: Number of colors to use for the ADAPTIVE palette.\n           Defaults to 256.\n        :rtype: :py:class:`~PIL.Image.Image`\n        :returns: An :py:class:`~PIL.Image.Image` object.\n        \"\"\"\n\n        self.load()\n\n        if not mode and self.mode == \"P\":\n            # determine default mode\n            if self.palette:\n                mode = self.palette.mode\n            else:\n                mode = \"RGB\"\n        if not mode or (mode == self.mode and not matrix):\n            return self.copy()\n\n        has_transparency = self.info.get(\"transparency\") is not None\n        if matrix:\n            # matrix conversion\n            if mode not in (\"L\", \"RGB\"):\n                raise ValueError(\"illegal conversion\")\n            im = self.im.convert_matrix(mode, matrix)\n            new = self._new(im)\n            if has_transparency and self.im.bands == 3:\n                transparency = new.info[\"transparency\"]\n\n                def convert_transparency(m, v):\n                    v = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * 0.5\n                    return max(0, min(255, int(v)))\n\n                if mode == \"L\":\n                    transparency = convert_transparency(matrix, transparency)\n                elif len(mode) == 3:\n                    transparency = tuple(\n                        [\n                            convert_transparency(\n                                matrix[i * 4 : i * 4 + 4], transparency\n                            )\n                            for i in range(0, len(transparency))\n                        ]\n                    )\n                new.info[\"transparency\"] = transparency\n            return new\n\n        if mode == \"P\" and self.mode == \"RGBA\":\n            return self.quantize(colors)\n\n        trns = None\n        delete_trns = False\n        # transparency handling\n        if has_transparency:\n            if self.mode in (\"1\", \"L\", \"I\", \"RGB\") and mode == \"RGBA\":\n                # Use transparent conversion to promote from transparent\n                # color to an alpha channel.\n                new_im = self._new(\n                    self.im.convert_transparent(mode, self.info[\"transparency\"])\n                )\n                del new_im.info[\"transparency\"]\n                return new_im\n            elif self.mode in (\"L\", \"RGB\", \"P\") and mode in (\"L\", \"RGB\", \"P\"):\n                t = self.info[\"transparency\"]\n                if isinstance(t, bytes):\n                    # Dragons. This can't be represented by a single color\n                    warnings.warn(\n                        \"Palette images with Transparency expressed in bytes should be \"\n                        \"converted to RGBA images\"\n                    )\n                    delete_trns = True\n                else:\n                    # get the new transparency color.\n                    # use existing conversions\n                    trns_im = Image()._new(core.new(self.mode, (1, 1)))\n                    if self.mode == \"P\":\n                        trns_im.putpalette(self.palette)\n                        if isinstance(t, tuple):\n                            try:\n                                t = trns_im.palette.getcolor(t)\n                            except Exception:\n                                raise ValueError(\n                                    \"Couldn't allocate a palette color for transparency\"\n                                )\n                    trns_im.putpixel((0, 0), t)\n\n                    if mode in (\"L\", \"RGB\"):\n                        trns_im = trns_im.convert(mode)\n                    else:\n                        # can't just retrieve the palette number, got to do it\n                        # after quantization.\n                        trns_im = trns_im.convert(\"RGB\")\n                    trns = trns_im.getpixel((0, 0))\n\n            elif self.mode == \"P\" and mode == \"RGBA\":\n                t = self.info[\"transparency\"]\n                delete_trns = True\n\n                if isinstance(t, bytes):\n                    self.im.putpalettealphas(t)\n                elif isinstance(t, int):\n                    self.im.putpalettealpha(t, 0)\n                else:\n                    raise ValueError(\"Transparency for P mode should be bytes or int\")\n\n        if mode == \"P\" and palette == ADAPTIVE:\n            im = self.im.quantize(colors)\n            new = self._new(im)\n            from . import ImagePalette\n\n            new.palette = ImagePalette.raw(\"RGB\", new.im.getpalette(\"RGB\"))\n            if delete_trns:\n                # This could possibly happen if we requantize to fewer colors.\n                # The transparency would be totally off in that case.\n                del new.info[\"transparency\"]\n            if trns is not None:\n                try:\n                    new.info[\"transparency\"] = new.palette.getcolor(trns)\n                except Exception:\n                    # if we can't make a transparent color, don't leave the old\n                    # transparency hanging around to mess us up.\n                    del new.info[\"transparency\"]\n                    warnings.warn(\"Couldn't allocate palette entry for transparency\")\n            return new\n\n        # colorspace conversion\n        if dither is None:\n            dither = FLOYDSTEINBERG\n\n        try:\n            im = self.im.convert(mode, dither)\n        except ValueError:\n            try:\n                # normalize source image and try again\n                im = self.im.convert(getmodebase(self.mode))\n                im = im.convert(mode, dither)\n            except KeyError:\n                raise ValueError(\"illegal conversion\")\n\n        new_im = self._new(im)\n        if delete_trns:\n            # crash fail if we leave a bytes transparency in an rgb/l mode.\n            del new_im.info[\"transparency\"]\n        if trns is not None:\n            if new_im.mode == \"P\":\n                try:\n                    new_im.info[\"transparency\"] = new_im.palette.getcolor(trns)\n                except Exception:\n                    del new_im.info[\"transparency\"]\n                    warnings.warn(\"Couldn't allocate palette entry for transparency\")\n            else:\n                new_im.info[\"transparency\"] = trns\n        return new_im\n\n    def quantize(self, colors=256, method=None, kmeans=0, palette=None, dither=1):\n        \"\"\"\n        Convert the image to 'P' mode with the specified number\n        of colors.\n\n        :param colors: The desired number of colors, <= 256\n        :param method: 0 = median cut\n                       1 = maximum coverage\n                       2 = fast octree\n                       3 = libimagequant\n        :param kmeans: Integer\n        :param palette: Quantize to the palette of given\n                        :py:class:`PIL.Image.Image`.\n        :param dither: Dithering method, used when converting from\n           mode \"RGB\" to \"P\" or from \"RGB\" or \"L\" to \"1\".\n           Available methods are NONE or FLOYDSTEINBERG (default).\n           Default: 1 (legacy setting)\n        :returns: A new image\n\n        \"\"\"\n\n        self.load()\n\n        if method is None:\n            # defaults:\n            method = 0\n            if self.mode == \"RGBA\":\n                method = 2\n\n        if self.mode == \"RGBA\" and method not in (2, 3):\n            # Caller specified an invalid mode.\n            raise ValueError(\n                \"Fast Octree (method == 2) and libimagequant (method == 3) \"\n                \"are the only valid methods for quantizing RGBA images\"\n            )\n\n        if palette:\n            # use palette from reference image\n            palette.load()\n            if palette.mode != \"P\":\n                raise ValueError(\"bad mode for palette image\")\n            if self.mode != \"RGB\" and self.mode != \"L\":\n                raise ValueError(\n                    \"only RGB or L mode images can be quantized to a palette\"\n                )\n            im = self.im.convert(\"P\", dither, palette.im)\n            return self._new(im)\n\n        im = self._new(self.im.quantize(colors, method, kmeans))\n\n        from . import ImagePalette\n\n        mode = im.im.getpalettemode()\n        im.palette = ImagePalette.ImagePalette(mode, im.im.getpalette(mode, mode))\n\n        return im\n\n    def copy(self):\n        \"\"\"\n        Copies this image. Use this method if you wish to paste things\n        into an image, but still retain the original.\n\n        :rtype: :py:class:`~PIL.Image.Image`\n        :returns: An :py:class:`~PIL.Image.Image` object.\n        \"\"\"\n        self.load()\n        return self._new(self.im.copy())\n\n    __copy__ = copy\n\n    def crop(self, box=None):\n        \"\"\"\n        Returns a rectangular region from this image. The box is a\n        4-tuple defining the left, upper, right, and lower pixel\n        coordinate. See :ref:`coordinate-system`.\n\n        Note: Prior to Pillow 3.4.0, this was a lazy operation.\n\n        :param box: The crop rectangle, as a (left, upper, right, lower)-tuple.\n        :rtype: :py:class:`~PIL.Image.Image`\n        :returns: An :py:class:`~PIL.Image.Image` object.\n        \"\"\"\n\n        if box is None:\n            return self.copy()\n\n        self.load()\n        return self._new(self._crop(self.im, box))\n\n    def _crop(self, im, box):\n        \"\"\"\n        Returns a rectangular region from the core image object im.\n\n        This is equivalent to calling im.crop((x0, y0, x1, y1)), but\n        includes additional sanity checks.\n\n        :param im: a core image object\n        :param box: The crop rectangle, as a (left, upper, right, lower)-tuple.\n        :returns: A core image object.\n        \"\"\"\n\n        x0, y0, x1, y1 = map(int, map(round, box))\n\n        absolute_values = (abs(x1 - x0), abs(y1 - y0))\n\n        _decompression_bomb_check(absolute_values)\n\n        return im.crop((x0, y0, x1, y1))\n\n    def draft(self, mode, size):\n        \"\"\"\n        Configures the image file loader so it returns a version of the\n        image that as closely as possible matches the given mode and\n        size. For example, you can use this method to convert a color\n        JPEG to greyscale while loading it.\n\n        If any changes are made, returns a tuple with the chosen ``mode`` and\n        ``box`` with coordinates of the original image within the altered one.\n\n        Note that this method modifies the :py:class:`~PIL.Image.Image` object\n        in place. If the image has already been loaded, this method has no\n        effect.\n\n        Note: This method is not implemented for most images. It is\n        currently implemented only for JPEG and MPO images.\n\n        :param mode: The requested mode.\n        :param size: The requested size.\n        \"\"\"\n        pass\n\n    def _expand(self, xmargin, ymargin=None):\n        if ymargin is None:\n            ymargin = xmargin\n        self.load()\n        return self._new(self.im.expand(xmargin, ymargin, 0))\n\n    def filter(self, filter):\n        \"\"\"\n        Filters this image using the given filter.  For a list of\n        available filters, see the :py:mod:`~PIL.ImageFilter` module.\n\n        :param filter: Filter kernel.\n        :returns: An :py:class:`~PIL.Image.Image` object.  \"\"\"\n\n        from . import ImageFilter\n\n        self.load()\n\n        if isinstance(filter, Callable):\n            filter = filter()\n        if not hasattr(filter, \"filter\"):\n            raise TypeError(\n                \"filter argument should be ImageFilter.Filter instance or class\"\n            )\n\n        multiband = isinstance(filter, ImageFilter.MultibandFilter)\n        if self.im.bands == 1 or multiband:\n            return self._new(filter.filter(self.im))\n\n        ims = []\n        for c in range(self.im.bands):\n            ims.append(self._new(filter.filter(self.im.getband(c))))\n        return merge(self.mode, ims)\n\n    def getbands(self):\n        \"\"\"\n        Returns a tuple containing the name of each band in this image.\n        For example, **getbands** on an RGB image returns (\"R\", \"G\", \"B\").\n\n        :returns: A tuple containing band names.\n        :rtype: tuple\n        \"\"\"\n        return ImageMode.getmode(self.mode).bands\n\n    def getbbox(self):\n        \"\"\"\n        Calculates the bounding box of the non-zero regions in the\n        image.\n\n        :returns: The bounding box is returned as a 4-tuple defining the\n           left, upper, right, and lower pixel coordinate. See\n           :ref:`coordinate-system`. If the image is completely empty, this\n           method returns None.\n\n        \"\"\"\n\n        self.load()\n        return self.im.getbbox()\n\n    def getcolors(self, maxcolors=256):\n        \"\"\"\n        Returns a list of colors used in this image.\n\n        :param maxcolors: Maximum number of colors.  If this number is\n           exceeded, this method returns None.  The default limit is\n           256 colors.\n        :returns: An unsorted list of (count, pixel) values.\n        \"\"\"\n\n        self.load()\n        if self.mode in (\"1\", \"L\", \"P\"):\n            h = self.im.histogram()\n            out = []\n            for i in range(256):\n                if h[i]:\n                    out.append((h[i], i))\n            if len(out) > maxcolors:\n                return None\n            return out\n        return self.im.getcolors(maxcolors)\n\n    def getdata(self, band=None):\n        \"\"\"\n        Returns the contents of this image as a sequence object\n        containing pixel values.  The sequence object is flattened, so\n        that values for line one follow directly after the values of\n        line zero, and so on.\n\n        Note that the sequence object returned by this method is an\n        internal PIL data type, which only supports certain sequence\n        operations.  To convert it to an ordinary sequence (e.g. for\n        printing), use **list(im.getdata())**.\n\n        :param band: What band to return.  The default is to return\n           all bands.  To return a single band, pass in the index\n           value (e.g. 0 to get the \"R\" band from an \"RGB\" image).\n        :returns: A sequence-like object.\n        \"\"\"\n\n        self.load()\n        if band is not None:\n            return self.im.getband(band)\n        return self.im  # could be abused\n\n    def getextrema(self):\n        \"\"\"\n        Gets the the minimum and maximum pixel values for each band in\n        the image.\n\n        :returns: For a single-band image, a 2-tuple containing the\n           minimum and maximum pixel value.  For a multi-band image,\n           a tuple containing one 2-tuple for each band.\n        \"\"\"\n\n        self.load()\n        if self.im.bands > 1:\n            extrema = []\n            for i in range(self.im.bands):\n                extrema.append(self.im.getband(i).getextrema())\n            return tuple(extrema)\n        return self.im.getextrema()\n\n    def getexif(self):\n        if self._exif is None:\n            self._exif = Exif()\n\n        exif_info = self.info.get(\"exif\")\n        if exif_info is None and \"Raw profile type exif\" in self.info:\n            exif_info = bytes.fromhex(\n                \"\".join(self.info[\"Raw profile type exif\"].split(\"\\n\")[3:])\n            )\n        self._exif.load(exif_info)\n\n        # XMP tags\n        if 0x0112 not in self._exif:\n            xmp_tags = self.info.get(\"XML:com.adobe.xmp\")\n            if xmp_tags:\n                root = xml.etree.ElementTree.fromstring(xmp_tags)\n                for elem in root.iter():\n                    if elem.tag.endswith(\"}Description\"):\n                        orientation = elem.attrib.get(\n                            \"{http://ns.adobe.com/tiff/1.0/}Orientation\"\n                        )\n                        if orientation:\n                            self._exif[0x0112] = int(orientation)\n                        break\n\n        return self._exif\n\n    def getim(self):\n        \"\"\"\n        Returns a capsule that points to the internal image memory.\n\n        :returns: A capsule object.\n        \"\"\"\n\n        self.load()\n        return self.im.ptr\n\n    def getpalette(self):\n        \"\"\"\n        Returns the image palette as a list.\n\n        :returns: A list of color values [r, g, b, ...], or None if the\n           image has no palette.\n        \"\"\"\n\n        self.load()\n        try:\n            return list(self.im.getpalette())\n        except ValueError:\n            return None  # no palette\n\n    def getpixel(self, xy):\n        \"\"\"\n        Returns the pixel value at a given position.\n\n        :param xy: The coordinate, given as (x, y). See\n           :ref:`coordinate-system`.\n        :returns: The pixel value.  If the image is a multi-layer image,\n           this method returns a tuple.\n        \"\"\"\n\n        self.load()\n        if self.pyaccess:\n            return self.pyaccess.getpixel(xy)\n        return self.im.getpixel(xy)\n\n    def getprojection(self):\n        \"\"\"\n        Get projection to x and y axes\n\n        :returns: Two sequences, indicating where there are non-zero\n            pixels along the X-axis and the Y-axis, respectively.\n        \"\"\"\n\n        self.load()\n        x, y = self.im.getprojection()\n        return [i8(c) for c in x], [i8(c) for c in y]\n\n    def histogram(self, mask=None, extrema=None):\n        \"\"\"\n        Returns a histogram for the image. The histogram is returned as\n        a list of pixel counts, one for each pixel value in the source\n        image. If the image has more than one band, the histograms for\n        all bands are concatenated (for example, the histogram for an\n        \"RGB\" image contains 768 values).\n\n        A bilevel image (mode \"1\") is treated as a greyscale (\"L\") image\n        by this method.\n\n        If a mask is provided, the method returns a histogram for those\n        parts of the image where the mask image is non-zero. The mask\n        image must have the same size as the image, and be either a\n        bi-level image (mode \"1\") or a greyscale image (\"L\").\n\n        :param mask: An optional mask.\n        :param extrema: An optional tuple of manually-specified extrema.\n        :returns: A list containing pixel counts.\n        \"\"\"\n        self.load()\n        if mask:\n            mask.load()\n            return self.im.histogram((0, 0), mask.im)\n        if self.mode in (\"I\", \"F\"):\n            if extrema is None:\n                extrema = self.getextrema()\n            return self.im.histogram(extrema)\n        return self.im.histogram()\n\n    def entropy(self, mask=None, extrema=None):\n        \"\"\"\n        Calculates and returns the entropy for the image.\n\n        A bilevel image (mode \"1\") is treated as a greyscale (\"L\")\n        image by this method.\n\n        If a mask is provided, the method employs the histogram for\n        those parts of the image where the mask image is non-zero.\n        The mask image must have the same size as the image, and be\n        either a bi-level image (mode \"1\") or a greyscale image (\"L\").\n\n        :param mask: An optional mask.\n        :param extrema: An optional tuple of manually-specified extrema.\n        :returns: A float value representing the image entropy\n        \"\"\"\n        self.load()\n        if mask:\n            mask.load()\n            return self.im.entropy((0, 0), mask.im)\n        if self.mode in (\"I\", \"F\"):\n            if extrema is None:\n                extrema = self.getextrema()\n            return self.im.entropy(extrema)\n        return self.im.entropy()\n\n    def offset(self, xoffset, yoffset=None):\n        raise NotImplementedError(\n            \"offset() has been removed. Please call ImageChops.offset() instead.\"\n        )\n\n    def paste(self, im, box=None, mask=None):\n        \"\"\"\n        Pastes another image into this image. The box argument is either\n        a 2-tuple giving the upper left corner, a 4-tuple defining the\n        left, upper, right, and lower pixel coordinate, or None (same as\n        (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size\n        of the pasted image must match the size of the region.\n\n        If the modes don't match, the pasted image is converted to the mode of\n        this image (see the :py:meth:`~PIL.Image.Image.convert` method for\n        details).\n\n        Instead of an image, the source can be a integer or tuple\n        containing pixel values.  The method then fills the region\n        with the given color.  When creating RGB images, you can\n        also use color strings as supported by the ImageColor module.\n\n        If a mask is given, this method updates only the regions\n        indicated by the mask.  You can use either \"1\", \"L\" or \"RGBA\"\n        images (in the latter case, the alpha band is used as mask).\n        Where the mask is 255, the given image is copied as is.  Where\n        the mask is 0, the current value is preserved.  Intermediate\n        values will mix the two images together, including their alpha\n        channels if they have them.\n\n        See :py:meth:`~PIL.Image.Image.alpha_composite` if you want to\n        combine images with respect to their alpha channels.\n\n        :param im: Source image or pixel value (integer or tuple).\n        :param box: An optional 4-tuple giving the region to paste into.\n           If a 2-tuple is used instead, it's treated as the upper left\n           corner.  If omitted or None, the source is pasted into the\n           upper left corner.\n\n           If an image is given as the second argument and there is no\n           third, the box defaults to (0, 0), and the second argument\n           is interpreted as a mask image.\n        :param mask: An optional mask image.\n        \"\"\"\n\n        if isImageType(box) and mask is None:\n            # abbreviated paste(im, mask) syntax\n            mask = box\n            box = None\n\n        if box is None:\n            box = (0, 0)\n\n        if len(box) == 2:\n            # upper left corner given; get size from image or mask\n            if isImageType(im):\n                size = im.size\n            elif isImageType(mask):\n                size = mask.size\n            else:\n                # FIXME: use self.size here?\n                raise ValueError(\"cannot determine region size; use 4-item box\")\n            box += (box[0] + size[0], box[1] + size[1])\n\n        if isinstance(im, str):\n            from . import ImageColor\n\n            im = ImageColor.getcolor(im, self.mode)\n\n        elif isImageType(im):\n            im.load()\n            if self.mode != im.mode:\n                if self.mode != \"RGB\" or im.mode not in (\"RGBA\", \"RGBa\"):\n                    # should use an adapter for this!\n                    im = im.convert(self.mode)\n            im = im.im\n\n        self._ensure_mutable()\n\n        if mask:\n            mask.load()\n            self.im.paste(im, box, mask.im)\n        else:\n            self.im.paste(im, box)\n\n    def alpha_composite(self, im, dest=(0, 0), source=(0, 0)):\n        \"\"\" 'In-place' analog of Image.alpha_composite. Composites an image\n        onto this image.\n\n        :param im: image to composite over this one\n        :param dest: Optional 2 tuple (left, top) specifying the upper\n          left corner in this (destination) image.\n        :param source: Optional 2 (left, top) tuple for the upper left\n          corner in the overlay source image, or 4 tuple (left, top, right,\n          bottom) for the bounds of the source rectangle\n\n        Performance Note: Not currently implemented in-place in the core layer.\n        \"\"\"\n\n        if not isinstance(source, (list, tuple)):\n            raise ValueError(\"Source must be a tuple\")\n        if not isinstance(dest, (list, tuple)):\n            raise ValueError(\"Destination must be a tuple\")\n        if not len(source) in (2, 4):\n            raise ValueError(\"Source must be a 2 or 4-tuple\")\n        if not len(dest) == 2:\n            raise ValueError(\"Destination must be a 2-tuple\")\n        if min(source) < 0:\n            raise ValueError(\"Source must be non-negative\")\n        if min(dest) < 0:\n            raise ValueError(\"Destination must be non-negative\")\n\n        if len(source) == 2:\n            source = source + im.size\n\n        # over image, crop if it's not the whole thing.\n        if source == (0, 0) + im.size:\n            overlay = im\n        else:\n            overlay = im.crop(source)\n\n        # target for the paste\n        box = dest + (dest[0] + overlay.width, dest[1] + overlay.height)\n\n        # destination image. don't copy if we're using the whole image.\n        if box == (0, 0) + self.size:\n            background = self\n        else:\n            background = self.crop(box)\n\n        result = alpha_composite(background, overlay)\n        self.paste(result, box)\n\n    def point(self, lut, mode=None):\n        \"\"\"\n        Maps this image through a lookup table or function.\n\n        :param lut: A lookup table, containing 256 (or 65536 if\n           self.mode==\"I\" and mode == \"L\") values per band in the\n           image.  A function can be used instead, it should take a\n           single argument. The function is called once for each\n           possible pixel value, and the resulting table is applied to\n           all bands of the image.\n        :param mode: Output mode (default is same as input).  In the\n           current version, this can only be used if the source image\n           has mode \"L\" or \"P\", and the output has mode \"1\" or the\n           source image mode is \"I\" and the output mode is \"L\".\n        :returns: An :py:class:`~PIL.Image.Image` object.\n        \"\"\"\n\n        self.load()\n\n        if isinstance(lut, ImagePointHandler):\n            return lut.point(self)\n\n        if callable(lut):\n            # if it isn't a list, it should be a function\n            if self.mode in (\"I\", \"I;16\", \"F\"):\n                # check if the function can be used with point_transform\n                # UNDONE wiredfool -- I think this prevents us from ever doing\n                # a gamma function point transform on > 8bit images.\n                scale, offset = _getscaleoffset(lut)\n                return self._new(self.im.point_transform(scale, offset))\n            # for other modes, convert the function to a table\n            lut = [lut(i) for i in range(256)] * self.im.bands\n\n        if self.mode == \"F\":\n            # FIXME: _imaging returns a confusing error message for this case\n            raise ValueError(\"point operation not supported for this mode\")\n\n        return self._new(self.im.point(lut, mode))\n\n    def putalpha(self, alpha):\n        \"\"\"\n        Adds or replaces the alpha layer in this image.  If the image\n        does not have an alpha layer, it's converted to \"LA\" or \"RGBA\".\n        The new layer must be either \"L\" or \"1\".\n\n        :param alpha: The new alpha layer.  This can either be an \"L\" or \"1\"\n           image having the same size as this image, or an integer or\n           other color value.\n        \"\"\"\n\n        self._ensure_mutable()\n\n        if self.mode not in (\"LA\", \"PA\", \"RGBA\"):\n            # attempt to promote self to a matching alpha mode\n            try:\n                mode = getmodebase(self.mode) + \"A\"\n                try:\n                    self.im.setmode(mode)\n                except (AttributeError, ValueError):\n                    # do things the hard way\n                    im = self.im.convert(mode)\n                    if im.mode not in (\"LA\", \"PA\", \"RGBA\"):\n                        raise ValueError  # sanity check\n                    self.im = im\n                self.pyaccess = None\n                self.mode = self.im.mode\n            except (KeyError, ValueError):\n                raise ValueError(\"illegal image mode\")\n\n        if self.mode in (\"LA\", \"PA\"):\n            band = 1\n        else:\n            band = 3\n\n        if isImageType(alpha):\n            # alpha layer\n            if alpha.mode not in (\"1\", \"L\"):\n                raise ValueError(\"illegal image mode\")\n            alpha.load()\n            if alpha.mode == \"1\":\n                alpha = alpha.convert(\"L\")\n        else:\n            # constant alpha\n            try:\n                self.im.fillband(band, alpha)\n            except (AttributeError, ValueError):\n                # do things the hard way\n                alpha = new(\"L\", self.size, alpha)\n            else:\n                return\n\n        self.im.putband(alpha.im, band)\n\n    def putdata(self, data, scale=1.0, offset=0.0):\n        \"\"\"\n        Copies pixel data to this image.  This method copies data from a\n        sequence object into the image, starting at the upper left\n        corner (0, 0), and continuing until either the image or the\n        sequence ends.  The scale and offset values are used to adjust\n        the sequence values: **pixel = value*scale + offset**.\n\n        :param data: A sequence object.\n        :param scale: An optional scale value.  The default is 1.0.\n        :param offset: An optional offset value.  The default is 0.0.\n        \"\"\"\n\n        self._ensure_mutable()\n\n        self.im.putdata(data, scale, offset)\n\n    def putpalette(self, data, rawmode=\"RGB\"):\n        \"\"\"\n        Attaches a palette to this image.  The image must be a \"P\",\n        \"PA\", \"L\" or \"LA\" image, and the palette sequence must contain\n        768 integer values, where each group of three values represent\n        the red, green, and blue values for the corresponding pixel\n        index. Instead of an integer sequence, you can use an 8-bit\n        string.\n\n        :param data: A palette sequence (either a list or a string).\n        :param rawmode: The raw mode of the palette.\n        \"\"\"\n        from . import ImagePalette\n\n        if self.mode not in (\"L\", \"LA\", \"P\", \"PA\"):\n            raise ValueError(\"illegal image mode\")\n        self.load()\n        if isinstance(data, ImagePalette.ImagePalette):\n            palette = ImagePalette.raw(data.rawmode, data.palette)\n        else:\n            if not isinstance(data, bytes):\n                data = bytes(data)\n            palette = ImagePalette.raw(rawmode, data)\n        self.mode = \"PA\" if \"A\" in self.mode else \"P\"\n        self.palette = palette\n        self.palette.mode = \"RGB\"\n        self.load()  # install new palette\n\n    def putpixel(self, xy, value):\n        \"\"\"\n        Modifies the pixel at the given position. The color is given as\n        a single numerical value for single-band images, and a tuple for\n        multi-band images. In addition to this, RGB and RGBA tuples are\n        accepted for P images.\n\n        Note that this method is relatively slow.  For more extensive changes,\n        use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw`\n        module instead.\n\n        See:\n\n        * :py:meth:`~PIL.Image.Image.paste`\n        * :py:meth:`~PIL.Image.Image.putdata`\n        * :py:mod:`~PIL.ImageDraw`\n\n        :param xy: The pixel coordinate, given as (x, y). See\n           :ref:`coordinate-system`.\n        :param value: The pixel value.\n        \"\"\"\n\n        if self.readonly:\n            self._copy()\n        self.load()\n\n        if self.pyaccess:\n            return self.pyaccess.putpixel(xy, value)\n\n        if (\n            self.mode == \"P\"\n            and isinstance(value, (list, tuple))\n            and len(value) in [3, 4]\n        ):\n            # RGB or RGBA value for a P image\n            value = self.palette.getcolor(value)\n        return self.im.putpixel(xy, value)\n\n    def remap_palette(self, dest_map, source_palette=None):\n        \"\"\"\n        Rewrites the image to reorder the palette.\n\n        :param dest_map: A list of indexes into the original palette.\n           e.g. [1,0] would swap a two item palette, and list(range(256))\n           is the identity transform.\n        :param source_palette: Bytes or None.\n        :returns:  An :py:class:`~PIL.Image.Image` object.\n\n        \"\"\"\n        from . import ImagePalette\n\n        if self.mode not in (\"L\", \"P\"):\n            raise ValueError(\"illegal image mode\")\n\n        if source_palette is None:\n            if self.mode == \"P\":\n                real_source_palette = self.im.getpalette(\"RGB\")[:768]\n            else:  # L-mode\n                real_source_palette = bytearray(i // 3 for i in range(768))\n        else:\n            real_source_palette = source_palette\n\n        palette_bytes = b\"\"\n        new_positions = [0] * 256\n\n        # pick only the used colors from the palette\n        for i, oldPosition in enumerate(dest_map):\n            palette_bytes += real_source_palette[oldPosition * 3 : oldPosition * 3 + 3]\n            new_positions[oldPosition] = i\n\n        # replace the palette color id of all pixel with the new id\n\n        # Palette images are [0..255], mapped through a 1 or 3\n        # byte/color map.  We need to remap the whole image\n        # from palette 1 to palette 2. New_positions is\n        # an array of indexes into palette 1.  Palette 2 is\n        # palette 1 with any holes removed.\n\n        # We're going to leverage the convert mechanism to use the\n        # C code to remap the image from palette 1 to palette 2,\n        # by forcing the source image into 'L' mode and adding a\n        # mapping 'L' mode palette, then converting back to 'L'\n        # sans palette thus converting the image bytes, then\n        # assigning the optimized RGB palette.\n\n        # perf reference, 9500x4000 gif, w/~135 colors\n        # 14 sec prepatch, 1 sec postpatch with optimization forced.\n\n        mapping_palette = bytearray(new_positions)\n\n        m_im = self.copy()\n        m_im.mode = \"P\"\n\n        m_im.palette = ImagePalette.ImagePalette(\n            \"RGB\", palette=mapping_palette * 3, size=768\n        )\n        # possibly set palette dirty, then\n        # m_im.putpalette(mapping_palette, 'L')  # converts to 'P'\n        # or just force it.\n        # UNDONE -- this is part of the general issue with palettes\n        m_im.im.putpalette(*m_im.palette.getdata())\n\n        m_im = m_im.convert(\"L\")\n\n        # Internally, we require 768 bytes for a palette.\n        new_palette_bytes = palette_bytes + (768 - len(palette_bytes)) * b\"\\x00\"\n        m_im.putpalette(new_palette_bytes)\n        m_im.palette = ImagePalette.ImagePalette(\n            \"RGB\", palette=palette_bytes, size=len(palette_bytes)\n        )\n\n        return m_im\n\n    def _get_safe_box(self, size, resample, box):\n        \"\"\"Expands the box so it includes adjacent pixels\n        that may be used by resampling with the given resampling filter.\n        \"\"\"\n        filter_support = _filters_support[resample] - 0.5\n        scale_x = (box[2] - box[0]) / size[0]\n        scale_y = (box[3] - box[1]) / size[1]\n        support_x = filter_support * scale_x\n        support_y = filter_support * scale_y\n\n        return (\n            max(0, int(box[0] - support_x)),\n            max(0, int(box[1] - support_y)),\n            min(self.size[0], math.ceil(box[2] + support_x)),\n            min(self.size[1], math.ceil(box[3] + support_y)),\n        )\n\n    def resize(self, size, resample=BICUBIC, box=None, reducing_gap=None):\n        \"\"\"\n        Returns a resized copy of this image.\n\n        :param size: The requested size in pixels, as a 2-tuple:\n           (width, height).\n        :param resample: An optional resampling filter.  This can be\n           one of :py:attr:`PIL.Image.NEAREST`, :py:attr:`PIL.Image.BOX`,\n           :py:attr:`PIL.Image.BILINEAR`, :py:attr:`PIL.Image.HAMMING`,\n           :py:attr:`PIL.Image.BICUBIC` or :py:attr:`PIL.Image.LANCZOS`.\n           Default filter is :py:attr:`PIL.Image.BICUBIC`.\n           If the image has mode \"1\" or \"P\", it is\n           always set to :py:attr:`PIL.Image.NEAREST`.\n           See: :ref:`concept-filters`.\n        :param box: An optional 4-tuple of floats providing\n           the source image region to be scaled.\n           The values must be within (0, 0, width, height) rectangle.\n           If omitted or None, the entire source is used.\n        :param reducing_gap: Apply optimization by resizing the image\n           in two steps. First, reducing the image by integer times\n           using :py:meth:`~PIL.Image.Image.reduce`.\n           Second, resizing using regular resampling. The last step\n           changes size no less than by ``reducing_gap`` times.\n           ``reducing_gap`` may be None (no first step is performed)\n           or should be greater than 1.0. The bigger ``reducing_gap``,\n           the closer the result to the fair resampling.\n           The smaller ``reducing_gap``, the faster resizing.\n           With ``reducing_gap`` greater or equal to 3.0, the result is\n           indistinguishable from fair resampling in most cases.\n           The default value is None (no optimization).\n        :returns: An :py:class:`~PIL.Image.Image` object.\n        \"\"\"\n\n        if resample not in (NEAREST, BILINEAR, BICUBIC, LANCZOS, BOX, HAMMING):\n            message = \"Unknown resampling filter ({}).\".format(resample)\n\n            filters = [\n                \"{} ({})\".format(filter[1], filter[0])\n                for filter in (\n                    (NEAREST, \"Image.NEAREST\"),\n                    (LANCZOS, \"Image.LANCZOS\"),\n                    (BILINEAR, \"Image.BILINEAR\"),\n                    (BICUBIC, \"Image.BICUBIC\"),\n                    (BOX, \"Image.BOX\"),\n                    (HAMMING, \"Image.HAMMING\"),\n                )\n            ]\n            raise ValueError(\n                message + \" Use \" + \", \".join(filters[:-1]) + \" or \" + filters[-1]\n            )\n\n        if reducing_gap is not None and reducing_gap < 1.0:\n            raise ValueError(\"reducing_gap must be 1.0 or greater\")\n\n        size = tuple(size)\n\n        if box is None:\n            box = (0, 0) + self.size\n        else:\n            box = tuple(box)\n\n        if self.size == size and box == (0, 0) + self.size:\n            return self.copy()\n\n        if self.mode in (\"1\", \"P\"):\n            resample = NEAREST\n\n        if self.mode in [\"LA\", \"RGBA\"]:\n            im = self.convert(self.mode[:-1] + \"a\")\n            im = im.resize(size, resample, box)\n            return im.convert(self.mode)\n\n        self.load()\n\n        if reducing_gap is not None and resample != NEAREST:\n            factor_x = int((box[2] - box[0]) / size[0] / reducing_gap) or 1\n            factor_y = int((box[3] - box[1]) / size[1] / reducing_gap) or 1\n            if factor_x > 1 or factor_y > 1:\n                reduce_box = self._get_safe_box(size, resample, box)\n                factor = (factor_x, factor_y)\n                if callable(self.reduce):\n                    self = self.reduce(factor, box=reduce_box)\n                else:\n                    self = Image.reduce(self, factor, box=reduce_box)\n                box = (\n                    (box[0] - reduce_box[0]) / factor_x,\n                    (box[1] - reduce_box[1]) / factor_y,\n                    (box[2] - reduce_box[0]) / factor_x,\n                    (box[3] - reduce_box[1]) / factor_y,\n                )\n\n        return self._new(self.im.resize(size, resample, box))\n\n    def reduce(self, factor, box=None):\n        \"\"\"\n        Returns a copy of the image reduced by `factor` times.\n        If the size of the image is not dividable by the `factor`,\n        the resulting size will be rounded up.\n\n        :param factor: A greater than 0 integer or tuple of two integers\n           for width and height separately.\n        :param box: An optional 4-tuple of ints providing\n           the source image region to be reduced.\n           The values must be within (0, 0, width, height) rectangle.\n           If omitted or None, the entire source is used.\n        \"\"\"\n        if not isinstance(factor, (list, tuple)):\n            factor = (factor, factor)\n\n        if box is None:\n            box = (0, 0) + self.size\n        else:\n            box = tuple(box)\n\n        if factor == (1, 1) and box == (0, 0) + self.size:\n            return self.copy()\n\n        if self.mode in [\"LA\", \"RGBA\"]:\n            im = self.convert(self.mode[:-1] + \"a\")\n            im = im.reduce(factor, box)\n            return im.convert(self.mode)\n\n        self.load()\n\n        return self._new(self.im.reduce(factor, box))\n\n    def rotate(\n        self,\n        angle,\n        resample=NEAREST,\n        expand=0,\n        center=None,\n        translate=None,\n        fillcolor=None,\n    ):\n        \"\"\"\n        Returns a rotated copy of this image.  This method returns a\n        copy of this image, rotated the given number of degrees counter\n        clockwise around its centre.\n\n        :param angle: In degrees counter clockwise.\n        :param resample: An optional resampling filter.  This can be\n           one of :py:attr:`PIL.Image.NEAREST` (use nearest neighbour),\n           :py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2\n           environment), or :py:attr:`PIL.Image.BICUBIC`\n           (cubic spline interpolation in a 4x4 environment).\n           If omitted, or if the image has mode \"1\" or \"P\", it is\n           set to :py:attr:`PIL.Image.NEAREST`. See :ref:`concept-filters`.\n        :param expand: Optional expansion flag.  If true, expands the output\n           image to make it large enough to hold the entire rotated image.\n           If false or omitted, make the output image the same size as the\n           input image.  Note that the expand flag assumes rotation around\n           the center and no translation.\n        :param center: Optional center of rotation (a 2-tuple).  Origin is\n           the upper left corner.  Default is the center of the image.\n        :param translate: An optional post-rotate translation (a 2-tuple).\n        :param fillcolor: An optional color for area outside the rotated image.\n        :returns: An :py:class:`~PIL.Image.Image` object.\n        \"\"\"\n\n        angle = angle % 360.0\n\n        # Fast paths regardless of filter, as long as we're not\n        # translating or changing the center.\n        if not (center or translate):\n            if angle == 0:\n                return self.copy()\n            if angle == 180:\n                return self.transpose(ROTATE_180)\n            if angle == 90 and expand:\n                return self.transpose(ROTATE_90)\n            if angle == 270 and expand:\n                return self.transpose(ROTATE_270)\n\n        # Calculate the affine matrix.  Note that this is the reverse\n        # transformation (from destination image to source) because we\n        # want to interpolate the (discrete) destination pixel from\n        # the local area around the (floating) source pixel.\n\n        # The matrix we actually want (note that it operates from the right):\n        # (1, 0, tx)   (1, 0, cx)   ( cos a, sin a, 0)   (1, 0, -cx)\n        # (0, 1, ty) * (0, 1, cy) * (-sin a, cos a, 0) * (0, 1, -cy)\n        # (0, 0,  1)   (0, 0,  1)   (     0,     0, 1)   (0, 0,   1)\n\n        # The reverse matrix is thus:\n        # (1, 0, cx)   ( cos -a, sin -a, 0)   (1, 0, -cx)   (1, 0, -tx)\n        # (0, 1, cy) * (-sin -a, cos -a, 0) * (0, 1, -cy) * (0, 1, -ty)\n        # (0, 0,  1)   (      0,      0, 1)   (0, 0,   1)   (0, 0,   1)\n\n        # In any case, the final translation may be updated at the end to\n        # compensate for the expand flag.\n\n        w, h = self.size\n\n        if translate is None:\n            post_trans = (0, 0)\n        else:\n            post_trans = translate\n        if center is None:\n            # FIXME These should be rounded to ints?\n            rotn_center = (w / 2.0, h / 2.0)\n        else:\n            rotn_center = center\n\n        angle = -math.radians(angle)\n        matrix = [\n            round(math.cos(angle), 15),\n            round(math.sin(angle), 15),\n            0.0,\n            round(-math.sin(angle), 15),\n            round(math.cos(angle), 15),\n            0.0,\n        ]\n\n        def transform(x, y, matrix):\n            (a, b, c, d, e, f) = matrix\n            return a * x + b * y + c, d * x + e * y + f\n\n        matrix[2], matrix[5] = transform(\n            -rotn_center[0] - post_trans[0], -rotn_center[1] - post_trans[1], matrix\n        )\n        matrix[2] += rotn_center[0]\n        matrix[5] += rotn_center[1]\n\n        if expand:\n            # calculate output size\n            xx = []\n            yy = []\n            for x, y in ((0, 0), (w, 0), (w, h), (0, h)):\n                x, y = transform(x, y, matrix)\n                xx.append(x)\n                yy.append(y)\n            nw = math.ceil(max(xx)) - math.floor(min(xx))\n            nh = math.ceil(max(yy)) - math.floor(min(yy))\n\n            # We multiply a translation matrix from the right.  Because of its\n            # special form, this is the same as taking the image of the\n            # translation vector as new translation vector.\n            matrix[2], matrix[5] = transform(-(nw - w) / 2.0, -(nh - h) / 2.0, matrix)\n            w, h = nw, nh\n\n        return self.transform((w, h), AFFINE, matrix, resample, fillcolor=fillcolor)\n\n    def save(self, fp, format=None, **params):\n        \"\"\"\n        Saves this image under the given filename.  If no format is\n        specified, the format to use is determined from the filename\n        extension, if possible.\n\n        Keyword options can be used to provide additional instructions\n        to the writer. If a writer doesn't recognise an option, it is\n        silently ignored. The available options are described in the\n        :doc:`image format documentation\n        <../handbook/image-file-formats>` for each writer.\n\n        You can use a file object instead of a filename. In this case,\n        you must always specify the format. The file object must\n        implement the ``seek``, ``tell``, and ``write``\n        methods, and be opened in binary mode.\n\n        :param fp: A filename (string), pathlib.Path object or file object.\n        :param format: Optional format override.  If omitted, the\n           format to use is determined from the filename extension.\n           If a file object was used instead of a filename, this\n           parameter should always be used.\n        :param params: Extra parameters to the image writer.\n        :returns: None\n        :exception ValueError: If the output format could not be determined\n           from the file name.  Use the format option to solve this.\n        :exception OSError: If the file could not be written.  The file\n           may have been created, and may contain partial data.\n        \"\"\"\n\n        filename = \"\"\n        open_fp = False\n        if isPath(fp):\n            filename = fp\n            open_fp = True\n        elif isinstance(fp, Path):\n            filename = str(fp)\n            open_fp = True\n        if not filename and hasattr(fp, \"name\") and isPath(fp.name):\n            # only set the name for metadata purposes\n            filename = fp.name\n\n        # may mutate self!\n        self._ensure_mutable()\n\n        save_all = params.pop(\"save_all\", False)\n        self.encoderinfo = params\n        self.encoderconfig = ()\n\n        preinit()\n\n        ext = os.path.splitext(filename)[1].lower()\n\n        if not format:\n            if ext not in EXTENSION:\n                init()\n            try:\n                format = EXTENSION[ext]\n            except KeyError:\n                raise ValueError(\"unknown file extension: {}\".format(ext))\n\n        if format.upper() not in SAVE:\n            init()\n        if save_all:\n            save_handler = SAVE_ALL[format.upper()]\n        else:\n            save_handler = SAVE[format.upper()]\n\n        if open_fp:\n            if params.get(\"append\", False):\n                # Open also for reading (\"+\"), because TIFF save_all\n                # writer needs to go back and edit the written data.\n                fp = builtins.open(filename, \"r+b\")\n            else:\n                fp = builtins.open(filename, \"w+b\")\n\n        try:\n            save_handler(self, fp, filename)\n        finally:\n            # do what we can to clean up\n            if open_fp:\n                fp.close()\n\n    def seek(self, frame):\n        \"\"\"\n        Seeks to the given frame in this sequence file. If you seek\n        beyond the end of the sequence, the method raises an\n        **EOFError** exception. When a sequence file is opened, the\n        library automatically seeks to frame 0.\n\n        See :py:meth:`~PIL.Image.Image.tell`.\n\n        :param frame: Frame number, starting at 0.\n        :exception EOFError: If the call attempts to seek beyond the end\n            of the sequence.\n        \"\"\"\n\n        # overridden by file handlers\n        if frame != 0:\n            raise EOFError\n\n    def show(self, title=None, command=None):\n        \"\"\"\n        Displays this image. This method is mainly intended for\n        debugging purposes.\n\n        The image is first saved to a temporary file. By default, it will be in\n        PNG format.\n\n        On Unix, the image is then opened using the **display**, **eog** or\n        **xv** utility, depending on which one can be found.\n\n        On macOS, the image is opened with the native Preview application.\n\n        On Windows, the image is opened with the standard PNG display utility.\n\n        :param title: Optional title to use for the image window,\n           where possible.\n        :param command: command used to show the image\n        \"\"\"\n\n        _show(self, title=title, command=command)\n\n    def split(self):\n        \"\"\"\n        Split this image into individual bands. This method returns a\n        tuple of individual image bands from an image. For example,\n        splitting an \"RGB\" image creates three new images each\n        containing a copy of one of the original bands (red, green,\n        blue).\n\n        If you need only one band, :py:meth:`~PIL.Image.Image.getchannel`\n        method can be more convenient and faster.\n\n        :returns: A tuple containing bands.\n        \"\"\"\n\n        self.load()\n        if self.im.bands == 1:\n            ims = [self.copy()]\n        else:\n            ims = map(self._new, self.im.split())\n        return tuple(ims)\n\n    def getchannel(self, channel):\n        \"\"\"\n        Returns an image containing a single channel of the source image.\n\n        :param channel: What channel to return. Could be index\n          (0 for \"R\" channel of \"RGB\") or channel name\n          (\"A\" for alpha channel of \"RGBA\").\n        :returns: An image in \"L\" mode.\n\n        .. versionadded:: 4.3.0\n        \"\"\"\n        self.load()\n\n        if isinstance(channel, str):\n            try:\n                channel = self.getbands().index(channel)\n            except ValueError:\n                raise ValueError('The image has no channel \"{}\"'.format(channel))\n\n        return self._new(self.im.getband(channel))\n\n    def tell(self):\n        \"\"\"\n        Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`.\n\n        :returns: Frame number, starting with 0.\n        \"\"\"\n        return 0\n\n    def thumbnail(self, size, resample=BICUBIC, reducing_gap=2.0):\n        \"\"\"\n        Make this image into a thumbnail.  This method modifies the\n        image to contain a thumbnail version of itself, no larger than\n        the given size.  This method calculates an appropriate thumbnail\n        size to preserve the aspect of the image, calls the\n        :py:meth:`~PIL.Image.Image.draft` method to configure the file reader\n        (where applicable), and finally resizes the image.\n\n        Note that this function modifies the :py:class:`~PIL.Image.Image`\n        object in place.  If you need to use the full resolution image as well,\n        apply this method to a :py:meth:`~PIL.Image.Image.copy` of the original\n        image.\n\n        :param size: Requested size.\n        :param resample: Optional resampling filter.  This can be one\n           of :py:attr:`PIL.Image.NEAREST`, :py:attr:`PIL.Image.BILINEAR`,\n           :py:attr:`PIL.Image.BICUBIC`, or :py:attr:`PIL.Image.LANCZOS`.\n           If omitted, it defaults to :py:attr:`PIL.Image.BICUBIC`.\n           (was :py:attr:`PIL.Image.NEAREST` prior to version 2.5.0).\n           See: :ref:`concept-filters`.\n        :param reducing_gap: Apply optimization by resizing the image\n           in two steps. First, reducing the image by integer times\n           using :py:meth:`~PIL.Image.Image.reduce` or\n           :py:meth:`~PIL.Image.Image.draft` for JPEG images.\n           Second, resizing using regular resampling. The last step\n           changes size no less than by ``reducing_gap`` times.\n           ``reducing_gap`` may be None (no first step is performed)\n           or should be greater than 1.0. The bigger ``reducing_gap``,\n           the closer the result to the fair resampling.\n           The smaller ``reducing_gap``, the faster resizing.\n           With ``reducing_gap`` greater or equal to 3.0, the result is\n           indistinguishable from fair resampling in most cases.\n           The default value is 2.0 (very close to fair resampling\n           while still being faster in many cases).\n        :returns: None\n        \"\"\"\n\n        x, y = map(math.floor, size)\n        if x >= self.width and y >= self.height:\n            return\n\n        def round_aspect(number, key):\n            return max(min(math.floor(number), math.ceil(number), key=key), 1)\n\n        # preserve aspect ratio\n        aspect = self.width / self.height\n        if x / y >= aspect:\n            x = round_aspect(y * aspect, key=lambda n: abs(aspect - n / y))\n        else:\n            y = round_aspect(\n                x / aspect, key=lambda n: 0 if n == 0 else abs(aspect - x / n)\n            )\n        size = (x, y)\n\n        box = None\n        if reducing_gap is not None:\n            res = self.draft(None, (size[0] * reducing_gap, size[1] * reducing_gap))\n            if res is not None:\n                box = res[1]\n\n        if self.size != size:\n            im = self.resize(size, resample, box=box, reducing_gap=reducing_gap)\n\n            self.im = im.im\n            self._size = size\n            self.mode = self.im.mode\n\n        self.readonly = 0\n        self.pyaccess = None\n\n    # FIXME: the different transform methods need further explanation\n    # instead of bloating the method docs, add a separate chapter.\n    def transform(\n        self, size, method, data=None, resample=NEAREST, fill=1, fillcolor=None\n    ):\n        \"\"\"\n        Transforms this image.  This method creates a new image with the\n        given size, and the same mode as the original, and copies data\n        to the new image using the given transform.\n\n        :param size: The output size.\n        :param method: The transformation method.  This is one of\n          :py:attr:`PIL.Image.EXTENT` (cut out a rectangular subregion),\n          :py:attr:`PIL.Image.AFFINE` (affine transform),\n          :py:attr:`PIL.Image.PERSPECTIVE` (perspective transform),\n          :py:attr:`PIL.Image.QUAD` (map a quadrilateral to a rectangle), or\n          :py:attr:`PIL.Image.MESH` (map a number of source quadrilaterals\n          in one operation).\n\n          It may also be an :py:class:`~PIL.Image.ImageTransformHandler`\n          object::\n\n            class Example(Image.ImageTransformHandler):\n                def transform(size, method, data, resample, fill=1):\n                    # Return result\n\n          It may also be an object with a :py:meth:`~method.getdata` method\n          that returns a tuple supplying new **method** and **data** values::\n\n            class Example:\n                def getdata(self):\n                    method = Image.EXTENT\n                    data = (0, 0, 100, 100)\n                    return method, data\n        :param data: Extra data to the transformation method.\n        :param resample: Optional resampling filter.  It can be one of\n           :py:attr:`PIL.Image.NEAREST` (use nearest neighbour),\n           :py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2\n           environment), or :py:attr:`PIL.Image.BICUBIC` (cubic spline\n           interpolation in a 4x4 environment). If omitted, or if the image\n           has mode \"1\" or \"P\", it is set to :py:attr:`PIL.Image.NEAREST`.\n           See: :ref:`concept-filters`.\n        :param fill: If **method** is an\n          :py:class:`~PIL.Image.ImageTransformHandler` object, this is one of\n          the arguments passed to it. Otherwise, it is unused.\n        :param fillcolor: Optional fill color for the area outside the\n           transform in the output image.\n        :returns: An :py:class:`~PIL.Image.Image` object.\n        \"\"\"\n\n        if self.mode == \"LA\":\n            return (\n                self.convert(\"La\")\n                .transform(size, method, data, resample, fill, fillcolor)\n                .convert(\"LA\")\n            )\n\n        if self.mode == \"RGBA\":\n            return (\n                self.convert(\"RGBa\")\n                .transform(size, method, data, resample, fill, fillcolor)\n                .convert(\"RGBA\")\n            )\n\n        if isinstance(method, ImageTransformHandler):\n            return method.transform(size, self, resample=resample, fill=fill)\n\n        if hasattr(method, \"getdata\"):\n            # compatibility w. old-style transform objects\n            method, data = method.getdata()\n\n        if data is None:\n            raise ValueError(\"missing method data\")\n\n        im = new(self.mode, size, fillcolor)\n        im.info = self.info.copy()\n        if method == MESH:\n            # list of quads\n            for box, quad in data:\n                im.__transformer(box, self, QUAD, quad, resample, fillcolor is None)\n        else:\n            im.__transformer(\n                (0, 0) + size, self, method, data, resample, fillcolor is None\n            )\n\n        return im\n\n    def __transformer(self, box, image, method, data, resample=NEAREST, fill=1):\n        w = box[2] - box[0]\n        h = box[3] - box[1]\n\n        if method == AFFINE:\n            data = data[0:6]\n\n        elif method == EXTENT:\n            # convert extent to an affine transform\n            x0, y0, x1, y1 = data\n            xs = (x1 - x0) / w\n            ys = (y1 - y0) / h\n            method = AFFINE\n            data = (xs, 0, x0, 0, ys, y0)\n\n        elif method == PERSPECTIVE:\n            data = data[0:8]\n\n        elif method == QUAD:\n            # quadrilateral warp.  data specifies the four corners\n            # given as NW, SW, SE, and NE.\n            nw = data[0:2]\n            sw = data[2:4]\n            se = data[4:6]\n            ne = data[6:8]\n            x0, y0 = nw\n            As = 1.0 / w\n            At = 1.0 / h\n            data = (\n                x0,\n                (ne[0] - x0) * As,\n                (sw[0] - x0) * At,\n                (se[0] - sw[0] - ne[0] + x0) * As * At,\n                y0,\n                (ne[1] - y0) * As,\n                (sw[1] - y0) * At,\n                (se[1] - sw[1] - ne[1] + y0) * As * At,\n            )\n\n        else:\n            raise ValueError(\"unknown transformation method\")\n\n        if resample not in (NEAREST, BILINEAR, BICUBIC):\n            if resample in (BOX, HAMMING, LANCZOS):\n                message = {\n                    BOX: \"Image.BOX\",\n                    HAMMING: \"Image.HAMMING\",\n                    LANCZOS: \"Image.LANCZOS/Image.ANTIALIAS\",\n                }[resample] + \" ({}) cannot be used.\".format(resample)\n            else:\n                message = \"Unknown resampling filter ({}).\".format(resample)\n\n            filters = [\n                \"{} ({})\".format(filter[1], filter[0])\n                for filter in (\n                    (NEAREST, \"Image.NEAREST\"),\n                    (BILINEAR, \"Image.BILINEAR\"),\n                    (BICUBIC, \"Image.BICUBIC\"),\n                )\n            ]\n            raise ValueError(\n                message + \" Use \" + \", \".join(filters[:-1]) + \" or \" + filters[-1]\n            )\n\n        image.load()\n\n        self.load()\n\n        if image.mode in (\"1\", \"P\"):\n            resample = NEAREST\n\n        self.im.transform2(box, image.im, method, data, resample, fill)\n\n    def transpose(self, method):\n        \"\"\"\n        Transpose image (flip or rotate in 90 degree steps)\n\n        :param method: One of :py:attr:`PIL.Image.FLIP_LEFT_RIGHT`,\n          :py:attr:`PIL.Image.FLIP_TOP_BOTTOM`, :py:attr:`PIL.Image.ROTATE_90`,\n          :py:attr:`PIL.Image.ROTATE_180`, :py:attr:`PIL.Image.ROTATE_270`,\n          :py:attr:`PIL.Image.TRANSPOSE` or :py:attr:`PIL.Image.TRANSVERSE`.\n        :returns: Returns a flipped or rotated copy of this image.\n        \"\"\"\n\n        self.load()\n        return self._new(self.im.transpose(method))\n\n    def effect_spread(self, distance):\n        \"\"\"\n        Randomly spread pixels in an image.\n\n        :param distance: Distance to spread pixels.\n        \"\"\"\n        self.load()\n        return self._new(self.im.effect_spread(distance))\n\n    def toqimage(self):\n        \"\"\"Returns a QImage copy of this image\"\"\"\n        from . import ImageQt\n\n        if not ImageQt.qt_is_installed:\n            raise ImportError(\"Qt bindings are not installed\")\n        return ImageQt.toqimage(self)\n\n    def toqpixmap(self):\n        \"\"\"Returns a QPixmap copy of this image\"\"\"\n        from . import ImageQt\n\n        if not ImageQt.qt_is_installed:\n            raise ImportError(\"Qt bindings are not installed\")\n        return ImageQt.toqpixmap(self)\n\n\n# --------------------------------------------------------------------\n# Abstract handlers.\n\n\nclass ImagePointHandler:\n    # used as a mixin by point transforms (for use with im.point)\n    pass\n\n\nclass ImageTransformHandler:\n    # used as a mixin by geometry transforms (for use with im.transform)\n    pass\n\n\n# --------------------------------------------------------------------\n# Factories\n\n#\n# Debugging\n\n\ndef _wedge():\n    \"\"\"Create greyscale wedge (for debugging only)\"\"\"\n\n    return Image()._new(core.wedge(\"L\"))\n\n\ndef _check_size(size):\n    \"\"\"\n    Common check to enforce type and sanity check on size tuples\n\n    :param size: Should be a 2 tuple of (width, height)\n    :returns: True, or raises a ValueError\n    \"\"\"\n\n    if not isinstance(size, (list, tuple)):\n        raise ValueError(\"Size must be a tuple\")\n    if len(size) != 2:\n        raise ValueError(\"Size must be a tuple of length 2\")\n    if size[0] < 0 or size[1] < 0:\n        raise ValueError(\"Width and height must be >= 0\")\n\n    return True\n\n\ndef new(mode, size, color=0):\n    \"\"\"\n    Creates a new image with the given mode and size.\n\n    :param mode: The mode to use for the new image. See:\n       :ref:`concept-modes`.\n    :param size: A 2-tuple, containing (width, height) in pixels.\n    :param color: What color to use for the image.  Default is black.\n       If given, this should be a single integer or floating point value\n       for single-band modes, and a tuple for multi-band modes (one value\n       per band).  When creating RGB images, you can also use color\n       strings as supported by the ImageColor module.  If the color is\n       None, the image is not initialised.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    \"\"\"\n\n    _check_size(size)\n\n    if color is None:\n        # don't initialize\n        return Image()._new(core.new(mode, size))\n\n    if isinstance(color, str):\n        # css3-style specifier\n\n        from . import ImageColor\n\n        color = ImageColor.getcolor(color, mode)\n\n    im = Image()\n    if mode == \"P\" and isinstance(color, (list, tuple)) and len(color) in [3, 4]:\n        # RGB or RGBA value for a P image\n        from . import ImagePalette\n\n        im.palette = ImagePalette.ImagePalette()\n        color = im.palette.getcolor(color)\n    return im._new(core.fill(mode, size, color))\n\n\ndef frombytes(mode, size, data, decoder_name=\"raw\", *args):\n    \"\"\"\n    Creates a copy of an image memory from pixel data in a buffer.\n\n    In its simplest form, this function takes three arguments\n    (mode, size, and unpacked pixel data).\n\n    You can also use any pixel decoder supported by PIL.  For more\n    information on available decoders, see the section\n    :ref:`Writing Your Own File Decoder <file-decoders>`.\n\n    Note that this function decodes pixel data only, not entire images.\n    If you have an entire image in a string, wrap it in a\n    :py:class:`~io.BytesIO` object, and use :py:func:`~PIL.Image.open` to load\n    it.\n\n    :param mode: The image mode. See: :ref:`concept-modes`.\n    :param size: The image size.\n    :param data: A byte buffer containing raw data for the given mode.\n    :param decoder_name: What decoder to use.\n    :param args: Additional parameters for the given decoder.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    \"\"\"\n\n    _check_size(size)\n\n    # may pass tuple instead of argument list\n    if len(args) == 1 and isinstance(args[0], tuple):\n        args = args[0]\n\n    if decoder_name == \"raw\" and args == ():\n        args = mode\n\n    im = new(mode, size)\n    im.frombytes(data, decoder_name, args)\n    return im\n\n\ndef fromstring(*args, **kw):\n    raise NotImplementedError(\n        \"fromstring() has been removed. Please call frombytes() instead.\"\n    )\n\n\ndef frombuffer(mode, size, data, decoder_name=\"raw\", *args):\n    \"\"\"\n    Creates an image memory referencing pixel data in a byte buffer.\n\n    This function is similar to :py:func:`~PIL.Image.frombytes`, but uses data\n    in the byte buffer, where possible.  This means that changes to the\n    original buffer object are reflected in this image).  Not all modes can\n    share memory; supported modes include \"L\", \"RGBX\", \"RGBA\", and \"CMYK\".\n\n    Note that this function decodes pixel data only, not entire images.\n    If you have an entire image file in a string, wrap it in a\n    **BytesIO** object, and use :py:func:`~PIL.Image.open` to load it.\n\n    In the current version, the default parameters used for the \"raw\" decoder\n    differs from that used for :py:func:`~PIL.Image.frombytes`.  This is a\n    bug, and will probably be fixed in a future release.  The current release\n    issues a warning if you do this; to disable the warning, you should provide\n    the full set of parameters.  See below for details.\n\n    :param mode: The image mode. See: :ref:`concept-modes`.\n    :param size: The image size.\n    :param data: A bytes or other buffer object containing raw\n        data for the given mode.\n    :param decoder_name: What decoder to use.\n    :param args: Additional parameters for the given decoder.  For the\n        default encoder (\"raw\"), it's recommended that you provide the\n        full set of parameters::\n\n            frombuffer(mode, size, data, \"raw\", mode, 0, 1)\n\n    :returns: An :py:class:`~PIL.Image.Image` object.\n\n    .. versionadded:: 1.1.4\n    \"\"\"\n\n    _check_size(size)\n\n    # may pass tuple instead of argument list\n    if len(args) == 1 and isinstance(args[0], tuple):\n        args = args[0]\n\n    if decoder_name == \"raw\":\n        if args == ():\n            args = mode, 0, 1\n        if args[0] in _MAPMODES:\n            im = new(mode, (1, 1))\n            im = im._new(core.map_buffer(data, size, decoder_name, 0, args))\n            im.readonly = 1\n            return im\n\n    return frombytes(mode, size, data, decoder_name, args)\n\n\ndef fromarray(obj, mode=None):\n    \"\"\"\n    Creates an image memory from an object exporting the array interface\n    (using the buffer protocol).\n\n    If **obj** is not contiguous, then the tobytes method is called\n    and :py:func:`~PIL.Image.frombuffer` is used.\n\n    If you have an image in NumPy::\n\n      from PIL import Image\n      import numpy as np\n      im = Image.open('hopper.jpg')\n      a = np.asarray(im)\n\n    Then this can be used to convert it to a Pillow image::\n\n      im = Image.fromarray(a)\n\n    :param obj: Object with array interface\n    :param mode: Mode to use (will be determined from type if None)\n      See: :ref:`concept-modes`.\n    :returns: An image object.\n\n    .. versionadded:: 1.1.6\n    \"\"\"\n    arr = obj.__array_interface__\n    shape = arr[\"shape\"]\n    ndim = len(shape)\n    strides = arr.get(\"strides\", None)\n    if mode is None:\n        try:\n            typekey = (1, 1) + shape[2:], arr[\"typestr\"]\n        except KeyError:\n            raise TypeError(\"Cannot handle this data type\")\n        try:\n            mode, rawmode = _fromarray_typemap[typekey]\n        except KeyError:\n            raise TypeError(\"Cannot handle this data type: %s, %s\" % typekey)\n    else:\n        rawmode = mode\n    if mode in [\"1\", \"L\", \"I\", \"P\", \"F\"]:\n        ndmax = 2\n    elif mode == \"RGB\":\n        ndmax = 3\n    else:\n        ndmax = 4\n    if ndim > ndmax:\n        raise ValueError(\"Too many dimensions: %d > %d.\" % (ndim, ndmax))\n\n    size = 1 if ndim == 1 else shape[1], shape[0]\n    if strides is not None:\n        if hasattr(obj, \"tobytes\"):\n            obj = obj.tobytes()\n        else:\n            obj = obj.tostring()\n\n    return frombuffer(mode, size, obj, \"raw\", rawmode, 0, 1)\n\n\ndef fromqimage(im):\n    \"\"\"Creates an image instance from a QImage image\"\"\"\n    from . import ImageQt\n\n    if not ImageQt.qt_is_installed:\n        raise ImportError(\"Qt bindings are not installed\")\n    return ImageQt.fromqimage(im)\n\n\ndef fromqpixmap(im):\n    \"\"\"Creates an image instance from a QPixmap image\"\"\"\n    from . import ImageQt\n\n    if not ImageQt.qt_is_installed:\n        raise ImportError(\"Qt bindings are not installed\")\n    return ImageQt.fromqpixmap(im)\n\n\n_fromarray_typemap = {\n    # (shape, typestr) => mode, rawmode\n    # first two members of shape are set to one\n    ((1, 1), \"|b1\"): (\"1\", \"1;8\"),\n    ((1, 1), \"|u1\"): (\"L\", \"L\"),\n    ((1, 1), \"|i1\"): (\"I\", \"I;8\"),\n    ((1, 1), \"<u2\"): (\"I\", \"I;16\"),\n    ((1, 1), \">u2\"): (\"I\", \"I;16B\"),\n    ((1, 1), \"<i2\"): (\"I\", \"I;16S\"),\n    ((1, 1), \">i2\"): (\"I\", \"I;16BS\"),\n    ((1, 1), \"<u4\"): (\"I\", \"I;32\"),\n    ((1, 1), \">u4\"): (\"I\", \"I;32B\"),\n    ((1, 1), \"<i4\"): (\"I\", \"I;32S\"),\n    ((1, 1), \">i4\"): (\"I\", \"I;32BS\"),\n    ((1, 1), \"<f4\"): (\"F\", \"F;32F\"),\n    ((1, 1), \">f4\"): (\"F\", \"F;32BF\"),\n    ((1, 1), \"<f8\"): (\"F\", \"F;64F\"),\n    ((1, 1), \">f8\"): (\"F\", \"F;64BF\"),\n    ((1, 1, 2), \"|u1\"): (\"LA\", \"LA\"),\n    ((1, 1, 3), \"|u1\"): (\"RGB\", \"RGB\"),\n    ((1, 1, 4), \"|u1\"): (\"RGBA\", \"RGBA\"),\n}\n\n# shortcuts\n_fromarray_typemap[((1, 1), _ENDIAN + \"i4\")] = (\"I\", \"I\")\n_fromarray_typemap[((1, 1), _ENDIAN + \"f4\")] = (\"F\", \"F\")\n\n\ndef _decompression_bomb_check(size):\n    if MAX_IMAGE_PIXELS is None:\n        return\n\n    pixels = size[0] * size[1]\n\n    if pixels > 2 * MAX_IMAGE_PIXELS:\n        raise DecompressionBombError(\n            \"Image size (%d pixels) exceeds limit of %d pixels, \"\n            \"could be decompression bomb DOS attack.\" % (pixels, 2 * MAX_IMAGE_PIXELS)\n        )\n\n    if pixels > MAX_IMAGE_PIXELS:\n        warnings.warn(\n            \"Image size (%d pixels) exceeds limit of %d pixels, \"\n            \"could be decompression bomb DOS attack.\" % (pixels, MAX_IMAGE_PIXELS),\n            DecompressionBombWarning,\n        )\n\n\ndef open(fp, mode=\"r\"):\n    \"\"\"\n    Opens and identifies the given image file.\n\n    This is a lazy operation; this function identifies the file, but\n    the file remains open and the actual image data is not read from\n    the file until you try to process the data (or call the\n    :py:meth:`~PIL.Image.Image.load` method).  See\n    :py:func:`~PIL.Image.new`. See :ref:`file-handling`.\n\n    :param fp: A filename (string), pathlib.Path object or a file object.\n       The file object must implement :py:meth:`~file.read`,\n       :py:meth:`~file.seek`, and :py:meth:`~file.tell` methods,\n       and be opened in binary mode.\n    :param mode: The mode.  If given, this argument must be \"r\".\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    :exception FileNotFoundError: If the file cannot be found.\n    :exception PIL.UnidentifiedImageError: If the image cannot be opened and\n       identified.\n    :exception ValueError: If the ``mode`` is not \"r\", or if a ``StringIO``\n       instance is used for ``fp``.\n    \"\"\"\n\n    if mode != \"r\":\n        raise ValueError(\"bad mode %r\" % mode)\n    elif isinstance(fp, io.StringIO):\n        raise ValueError(\n            \"StringIO cannot be used to open an image. \"\n            \"Binary data must be used instead.\"\n        )\n\n    exclusive_fp = False\n    filename = \"\"\n    if isinstance(fp, Path):\n        filename = str(fp.resolve())\n    elif isPath(fp):\n        filename = fp\n\n    if filename:\n        fp = builtins.open(filename, \"rb\")\n        exclusive_fp = True\n\n    try:\n        fp.seek(0)\n    except (AttributeError, io.UnsupportedOperation):\n        fp = io.BytesIO(fp.read())\n        exclusive_fp = True\n\n    prefix = fp.read(16)\n\n    preinit()\n\n    accept_warnings = []\n\n    def _open_core(fp, filename, prefix):\n        for i in ID:\n            try:\n                factory, accept = OPEN[i]\n                result = not accept or accept(prefix)\n                if type(result) in [str, bytes]:\n                    accept_warnings.append(result)\n                elif result:\n                    fp.seek(0)\n                    im = factory(fp, filename)\n                    _decompression_bomb_check(im.size)\n                    return im\n            except (SyntaxError, IndexError, TypeError, struct.error):\n                # Leave disabled by default, spams the logs with image\n                # opening failures that are entirely expected.\n                # logger.debug(\"\", exc_info=True)\n                continue\n            except BaseException:\n                if exclusive_fp:\n                    fp.close()\n                raise\n        return None\n\n    im = _open_core(fp, filename, prefix)\n\n    if im is None:\n        if init():\n            im = _open_core(fp, filename, prefix)\n\n    if im:\n        im._exclusive_fp = exclusive_fp\n        return im\n\n    if exclusive_fp:\n        fp.close()\n    for message in accept_warnings:\n        warnings.warn(message)\n    raise UnidentifiedImageError(\n        \"cannot identify image file %r\" % (filename if filename else fp)\n    )\n\n\n#\n# Image processing.\n\n\ndef alpha_composite(im1, im2):\n    \"\"\"\n    Alpha composite im2 over im1.\n\n    :param im1: The first image. Must have mode RGBA.\n    :param im2: The second image.  Must have mode RGBA, and the same size as\n       the first image.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    \"\"\"\n\n    im1.load()\n    im2.load()\n    return im1._new(core.alpha_composite(im1.im, im2.im))\n\n\ndef blend(im1, im2, alpha):\n    \"\"\"\n    Creates a new image by interpolating between two input images, using\n    a constant alpha.::\n\n        out = image1 * (1.0 - alpha) + image2 * alpha\n\n    :param im1: The first image.\n    :param im2: The second image.  Must have the same mode and size as\n       the first image.\n    :param alpha: The interpolation alpha factor.  If alpha is 0.0, a\n       copy of the first image is returned. If alpha is 1.0, a copy of\n       the second image is returned. There are no restrictions on the\n       alpha value. If necessary, the result is clipped to fit into\n       the allowed output range.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    \"\"\"\n\n    im1.load()\n    im2.load()\n    return im1._new(core.blend(im1.im, im2.im, alpha))\n\n\ndef composite(image1, image2, mask):\n    \"\"\"\n    Create composite image by blending images using a transparency mask.\n\n    :param image1: The first image.\n    :param image2: The second image.  Must have the same mode and\n       size as the first image.\n    :param mask: A mask image.  This image can have mode\n       \"1\", \"L\", or \"RGBA\", and must have the same size as the\n       other two images.\n    \"\"\"\n\n    image = image2.copy()\n    image.paste(image1, None, mask)\n    return image\n\n\ndef eval(image, *args):\n    \"\"\"\n    Applies the function (which should take one argument) to each pixel\n    in the given image. If the image has more than one band, the same\n    function is applied to each band. Note that the function is\n    evaluated once for each possible pixel value, so you cannot use\n    random components or other generators.\n\n    :param image: The input image.\n    :param function: A function object, taking one integer argument.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    \"\"\"\n\n    return image.point(args[0])\n\n\ndef merge(mode, bands):\n    \"\"\"\n    Merge a set of single band images into a new multiband image.\n\n    :param mode: The mode to use for the output image. See:\n        :ref:`concept-modes`.\n    :param bands: A sequence containing one single-band image for\n        each band in the output image.  All bands must have the\n        same size.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    \"\"\"\n\n    if getmodebands(mode) != len(bands) or \"*\" in mode:\n        raise ValueError(\"wrong number of bands\")\n    for band in bands[1:]:\n        if band.mode != getmodetype(mode):\n            raise ValueError(\"mode mismatch\")\n        if band.size != bands[0].size:\n            raise ValueError(\"size mismatch\")\n    for band in bands:\n        band.load()\n    return bands[0]._new(core.merge(mode, *[b.im for b in bands]))\n\n\n# --------------------------------------------------------------------\n# Plugin registry\n\n\ndef register_open(id, factory, accept=None):\n    \"\"\"\n    Register an image file plugin.  This function should not be used\n    in application code.\n\n    :param id: An image format identifier.\n    :param factory: An image file factory method.\n    :param accept: An optional function that can be used to quickly\n       reject images having another format.\n    \"\"\"\n    id = id.upper()\n    ID.append(id)\n    OPEN[id] = factory, accept\n\n\ndef register_mime(id, mimetype):\n    \"\"\"\n    Registers an image MIME type.  This function should not be used\n    in application code.\n\n    :param id: An image format identifier.\n    :param mimetype: The image MIME type for this format.\n    \"\"\"\n    MIME[id.upper()] = mimetype\n\n\ndef register_save(id, driver):\n    \"\"\"\n    Registers an image save function.  This function should not be\n    used in application code.\n\n    :param id: An image format identifier.\n    :param driver: A function to save images in this format.\n    \"\"\"\n    SAVE[id.upper()] = driver\n\n\ndef register_save_all(id, driver):\n    \"\"\"\n    Registers an image function to save all the frames\n    of a multiframe format.  This function should not be\n    used in application code.\n\n    :param id: An image format identifier.\n    :param driver: A function to save images in this format.\n    \"\"\"\n    SAVE_ALL[id.upper()] = driver\n\n\ndef register_extension(id, extension):\n    \"\"\"\n    Registers an image extension.  This function should not be\n    used in application code.\n\n    :param id: An image format identifier.\n    :param extension: An extension used for this format.\n    \"\"\"\n    EXTENSION[extension.lower()] = id.upper()\n\n\ndef register_extensions(id, extensions):\n    \"\"\"\n    Registers image extensions.  This function should not be\n    used in application code.\n\n    :param id: An image format identifier.\n    :param extensions: A list of extensions used for this format.\n    \"\"\"\n    for extension in extensions:\n        register_extension(id, extension)\n\n\ndef registered_extensions():\n    \"\"\"\n    Returns a dictionary containing all file extensions belonging\n    to registered plugins\n    \"\"\"\n    if not EXTENSION:\n        init()\n    return EXTENSION\n\n\ndef register_decoder(name, decoder):\n    \"\"\"\n    Registers an image decoder.  This function should not be\n    used in application code.\n\n    :param name: The name of the decoder\n    :param decoder: A callable(mode, args) that returns an\n                    ImageFile.PyDecoder object\n\n    .. versionadded:: 4.1.0\n    \"\"\"\n    DECODERS[name] = decoder\n\n\ndef register_encoder(name, encoder):\n    \"\"\"\n    Registers an image encoder.  This function should not be\n    used in application code.\n\n    :param name: The name of the encoder\n    :param encoder: A callable(mode, args) that returns an\n                    ImageFile.PyEncoder object\n\n    .. versionadded:: 4.1.0\n    \"\"\"\n    ENCODERS[name] = encoder\n\n\n# --------------------------------------------------------------------\n# Simple display support.  User code may override this.\n\n\ndef _show(image, **options):\n    # override me, as necessary\n    _showxv(image, **options)\n\n\ndef _showxv(image, title=None, **options):\n    from . import ImageShow\n\n    ImageShow.show(image, title, **options)\n\n\n# --------------------------------------------------------------------\n# Effects\n\n\ndef effect_mandelbrot(size, extent, quality):\n    \"\"\"\n    Generate a Mandelbrot set covering the given extent.\n\n    :param size: The requested size in pixels, as a 2-tuple:\n       (width, height).\n    :param extent: The extent to cover, as a 4-tuple:\n       (x0, y0, x1, y2).\n    :param quality: Quality.\n    \"\"\"\n    return Image()._new(core.effect_mandelbrot(size, extent, quality))\n\n\ndef effect_noise(size, sigma):\n    \"\"\"\n    Generate Gaussian noise centered around 128.\n\n    :param size: The requested size in pixels, as a 2-tuple:\n       (width, height).\n    :param sigma: Standard deviation of noise.\n    \"\"\"\n    return Image()._new(core.effect_noise(size, sigma))\n\n\ndef linear_gradient(mode):\n    \"\"\"\n    Generate 256x256 linear gradient from black to white, top to bottom.\n\n    :param mode: Input mode.\n    \"\"\"\n    return Image()._new(core.linear_gradient(mode))\n\n\ndef radial_gradient(mode):\n    \"\"\"\n    Generate 256x256 radial gradient from black to white, centre to edge.\n\n    :param mode: Input mode.\n    \"\"\"\n    return Image()._new(core.radial_gradient(mode))\n\n\n# --------------------------------------------------------------------\n# Resources\n\n\ndef _apply_env_variables(env=None):\n    if env is None:\n        env = os.environ\n\n    for var_name, setter in [\n        (\"PILLOW_ALIGNMENT\", core.set_alignment),\n        (\"PILLOW_BLOCK_SIZE\", core.set_block_size),\n        (\"PILLOW_BLOCKS_MAX\", core.set_blocks_max),\n    ]:\n        if var_name not in env:\n            continue\n\n        var = env[var_name].lower()\n\n        units = 1\n        for postfix, mul in [(\"k\", 1024), (\"m\", 1024 * 1024)]:\n            if var.endswith(postfix):\n                units = mul\n                var = var[: -len(postfix)]\n\n        try:\n            var = int(var) * units\n        except ValueError:\n            warnings.warn(\"{} is not int\".format(var_name))\n            continue\n\n        try:\n            setter(var)\n        except ValueError as e:\n            warnings.warn(\"{}: {}\".format(var_name, e))\n\n\n_apply_env_variables()\natexit.register(core.clear_cache)\n\n\nclass Exif(MutableMapping):\n    endian = \"<\"\n\n    def __init__(self):\n        self._data = {}\n        self._ifds = {}\n        self._info = None\n        self._loaded_exif = None\n\n    def _fixup(self, value):\n        try:\n            if len(value) == 1 and not isinstance(value, dict):\n                return value[0]\n        except Exception:\n            pass\n        return value\n\n    def _fixup_dict(self, src_dict):\n        # Helper function for _getexif()\n        # returns a dict with any single item tuples/lists as individual values\n        return {k: self._fixup(v) for k, v in src_dict.items()}\n\n    def _get_ifd_dict(self, tag):\n        try:\n            # an offset pointer to the location of the nested embedded IFD.\n            # It should be a long, but may be corrupted.\n            self.fp.seek(self[tag])\n        except (KeyError, TypeError):\n            pass\n        else:\n            from . import TiffImagePlugin\n\n            info = TiffImagePlugin.ImageFileDirectory_v1(self.head)\n            info.load(self.fp)\n            return self._fixup_dict(info)\n\n    def load(self, data):\n        # Extract EXIF information.  This is highly experimental,\n        # and is likely to be replaced with something better in a future\n        # version.\n\n        # The EXIF record consists of a TIFF file embedded in a JPEG\n        # application marker (!).\n        if data == self._loaded_exif:\n            return\n        self._loaded_exif = data\n        self._data.clear()\n        self._ifds.clear()\n        self._info = None\n        if not data:\n            return\n\n        if data.startswith(b\"Exif\\x00\\x00\"):\n            data = data[6:]\n        self.fp = io.BytesIO(data)\n        self.head = self.fp.read(8)\n        # process dictionary\n        from . import TiffImagePlugin\n\n        self._info = TiffImagePlugin.ImageFileDirectory_v1(self.head)\n        self.endian = self._info._endian\n        self.fp.seek(self._info.next)\n        self._info.load(self.fp)\n\n        # get EXIF extension\n        ifd = self._get_ifd_dict(0x8769)\n        if ifd:\n            self._data.update(ifd)\n            self._ifds[0x8769] = ifd\n\n    def tobytes(self, offset=8):\n        from . import TiffImagePlugin\n\n        if self.endian == \"<\":\n            head = b\"II\\x2A\\x00\\x08\\x00\\x00\\x00\"\n        else:\n            head = b\"MM\\x00\\x2A\\x00\\x00\\x00\\x08\"\n        ifd = TiffImagePlugin.ImageFileDirectory_v2(ifh=head)\n        for tag, value in self.items():\n            ifd[tag] = value\n        return b\"Exif\\x00\\x00\" + head + ifd.tobytes(offset)\n\n    def get_ifd(self, tag):\n        if tag not in self._ifds and tag in self:\n            if tag in [0x8825, 0xA005]:\n                # gpsinfo, interop\n                self._ifds[tag] = self._get_ifd_dict(tag)\n            elif tag == 0x927C:  # makernote\n                from .TiffImagePlugin import ImageFileDirectory_v2\n\n                if self[0x927C][:8] == b\"FUJIFILM\":\n                    exif_data = self[0x927C]\n                    ifd_offset = i32le(exif_data[8:12])\n                    ifd_data = exif_data[ifd_offset:]\n\n                    makernote = {}\n                    for i in range(0, struct.unpack(\"<H\", ifd_data[:2])[0]):\n                        ifd_tag, typ, count, data = struct.unpack(\n                            \"<HHL4s\", ifd_data[i * 12 + 2 : (i + 1) * 12 + 2]\n                        )\n                        try:\n                            unit_size, handler = ImageFileDirectory_v2._load_dispatch[\n                                typ\n                            ]\n                        except KeyError:\n                            continue\n                        size = count * unit_size\n                        if size > 4:\n                            (offset,) = struct.unpack(\"<L\", data)\n                            data = ifd_data[offset - 12 : offset + size - 12]\n                        else:\n                            data = data[:size]\n\n                        if len(data) != size:\n                            warnings.warn(\n                                \"Possibly corrupt EXIF MakerNote data.  \"\n                                \"Expecting to read %d bytes but only got %d.\"\n                                \" Skipping tag %s\" % (size, len(data), ifd_tag)\n                            )\n                            continue\n\n                        if not data:\n                            continue\n\n                        makernote[ifd_tag] = handler(\n                            ImageFileDirectory_v2(), data, False\n                        )\n                    self._ifds[0x927C] = dict(self._fixup_dict(makernote))\n                elif self.get(0x010F) == \"Nintendo\":\n                    ifd_data = self[0x927C]\n\n                    makernote = {}\n                    for i in range(0, struct.unpack(\">H\", ifd_data[:2])[0]):\n                        ifd_tag, typ, count, data = struct.unpack(\n                            \">HHL4s\", ifd_data[i * 12 + 2 : (i + 1) * 12 + 2]\n                        )\n                        if ifd_tag == 0x1101:\n                            # CameraInfo\n                            (offset,) = struct.unpack(\">L\", data)\n                            self.fp.seek(offset)\n\n                            camerainfo = {\"ModelID\": self.fp.read(4)}\n\n                            self.fp.read(4)\n                            # Seconds since 2000\n                            camerainfo[\"TimeStamp\"] = i32le(self.fp.read(12))\n\n                            self.fp.read(4)\n                            camerainfo[\"InternalSerialNumber\"] = self.fp.read(4)\n\n                            self.fp.read(12)\n                            parallax = self.fp.read(4)\n                            handler = ImageFileDirectory_v2._load_dispatch[\n                                TiffTags.FLOAT\n                            ][1]\n                            camerainfo[\"Parallax\"] = handler(\n                                ImageFileDirectory_v2(), parallax, False\n                            )\n\n                            self.fp.read(4)\n                            camerainfo[\"Category\"] = self.fp.read(2)\n\n                            makernote = {0x1101: dict(self._fixup_dict(camerainfo))}\n                    self._ifds[0x927C] = makernote\n        return self._ifds.get(tag, {})\n\n    def __str__(self):\n        if self._info is not None:\n            # Load all keys into self._data\n            for tag in self._info.keys():\n                self[tag]\n\n        return str(self._data)\n\n    def __len__(self):\n        keys = set(self._data)\n        if self._info is not None:\n            keys.update(self._info)\n        return len(keys)\n\n    def __getitem__(self, tag):\n        if self._info is not None and tag not in self._data and tag in self._info:\n            self._data[tag] = self._fixup(self._info[tag])\n            if tag == 0x8825:\n                self._data[tag] = self.get_ifd(tag)\n            del self._info[tag]\n        return self._data[tag]\n\n    def __contains__(self, tag):\n        return tag in self._data or (self._info is not None and tag in self._info)\n\n    def __setitem__(self, tag, value):\n        if self._info is not None and tag in self._info:\n            del self._info[tag]\n        self._data[tag] = value\n\n    def __delitem__(self, tag):\n        if self._info is not None and tag in self._info:\n            del self._info[tag]\n        del self._data[tag]\n\n    def __iter__(self):\n        keys = set(self._data)\n        if self._info is not None:\n            keys.update(self._info)\n        return iter(keys)\n",
            "new_file_content": "#\n# The Python Imaging Library.\n# $Id$\n#\n# the Image class wrapper\n#\n# partial release history:\n# 1995-09-09 fl   Created\n# 1996-03-11 fl   PIL release 0.0 (proof of concept)\n# 1996-04-30 fl   PIL release 0.1b1\n# 1999-07-28 fl   PIL release 1.0 final\n# 2000-06-07 fl   PIL release 1.1\n# 2000-10-20 fl   PIL release 1.1.1\n# 2001-05-07 fl   PIL release 1.1.2\n# 2002-03-15 fl   PIL release 1.1.3\n# 2003-05-10 fl   PIL release 1.1.4\n# 2005-03-28 fl   PIL release 1.1.5\n# 2006-12-02 fl   PIL release 1.1.6\n# 2009-11-15 fl   PIL release 1.1.7\n#\n# Copyright (c) 1997-2009 by Secret Labs AB.  All rights reserved.\n# Copyright (c) 1995-2009 by Fredrik Lundh.\n#\n# See the README file for information on usage and redistribution.\n#\n\nimport atexit\nimport builtins\nimport io\nimport logging\nimport math\nimport numbers\nimport os\nimport struct\nimport sys\nimport tempfile\nimport warnings\nimport xml.etree.ElementTree\nfrom collections.abc import Callable, MutableMapping\nfrom pathlib import Path\n\n# VERSION was removed in Pillow 6.0.0.\n# PILLOW_VERSION is deprecated and will be removed in a future release.\n# Use __version__ instead.\nfrom . import (\n    ImageMode,\n    TiffTags,\n    UnidentifiedImageError,\n    __version__,\n    _plugins,\n    _raise_version_warning,\n)\nfrom ._binary import i8, i32le\nfrom ._util import deferred_error, isPath\n\nif sys.version_info >= (3, 7):\n\n    def __getattr__(name):\n        if name == \"PILLOW_VERSION\":\n            _raise_version_warning()\n            return __version__\n        raise AttributeError(\"module '{}' has no attribute '{}'\".format(__name__, name))\n\n\nelse:\n\n    from . import PILLOW_VERSION\n\n    # Silence warning\n    assert PILLOW_VERSION\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass DecompressionBombWarning(RuntimeWarning):\n    pass\n\n\nclass DecompressionBombError(Exception):\n    pass\n\n\n# Limit to around a quarter gigabyte for a 24 bit (3 bpp) image\nMAX_IMAGE_PIXELS = int(1024 * 1024 * 1024 // 4 // 3)\n\n\ntry:\n    # If the _imaging C module is not present, Pillow will not load.\n    # Note that other modules should not refer to _imaging directly;\n    # import Image and use the Image.core variable instead.\n    # Also note that Image.core is not a publicly documented interface,\n    # and should be considered private and subject to change.\n    from . import _imaging as core\n\n    if __version__ != getattr(core, \"PILLOW_VERSION\", None):\n        raise ImportError(\n            \"The _imaging extension was built for another version of Pillow or PIL:\\n\"\n            \"Core version: %s\\n\"\n            \"Pillow version: %s\" % (getattr(core, \"PILLOW_VERSION\", None), __version__)\n        )\n\nexcept ImportError as v:\n    core = deferred_error(ImportError(\"The _imaging C module is not installed.\"))\n    # Explanations for ways that we know we might have an import error\n    if str(v).startswith(\"Module use of python\"):\n        # The _imaging C module is present, but not compiled for\n        # the right version (windows only).  Print a warning, if\n        # possible.\n        warnings.warn(\n            \"The _imaging extension was built for another version of Python.\",\n            RuntimeWarning,\n        )\n    elif str(v).startswith(\"The _imaging extension\"):\n        warnings.warn(str(v), RuntimeWarning)\n    # Fail here anyway. Don't let people run with a mostly broken Pillow.\n    # see docs/porting.rst\n    raise\n\n\n# works everywhere, win for pypy, not cpython\nUSE_CFFI_ACCESS = hasattr(sys, \"pypy_version_info\")\ntry:\n    import cffi\nexcept ImportError:\n    cffi = None\n\n\ndef isImageType(t):\n    \"\"\"\n    Checks if an object is an image object.\n\n    .. warning::\n\n       This function is for internal use only.\n\n    :param t: object to check if it's an image\n    :returns: True if the object is an image\n    \"\"\"\n    return hasattr(t, \"im\")\n\n\n#\n# Constants\n\nNONE = 0\n\n# transpose\nFLIP_LEFT_RIGHT = 0\nFLIP_TOP_BOTTOM = 1\nROTATE_90 = 2\nROTATE_180 = 3\nROTATE_270 = 4\nTRANSPOSE = 5\nTRANSVERSE = 6\n\n# transforms (also defined in Imaging.h)\nAFFINE = 0\nEXTENT = 1\nPERSPECTIVE = 2\nQUAD = 3\nMESH = 4\n\n# resampling filters (also defined in Imaging.h)\nNEAREST = NONE = 0\nBOX = 4\nBILINEAR = LINEAR = 2\nHAMMING = 5\nBICUBIC = CUBIC = 3\nLANCZOS = ANTIALIAS = 1\n\n_filters_support = {BOX: 0.5, BILINEAR: 1.0, HAMMING: 1.0, BICUBIC: 2.0, LANCZOS: 3.0}\n\n\n# dithers\nNEAREST = NONE = 0\nORDERED = 1  # Not yet implemented\nRASTERIZE = 2  # Not yet implemented\nFLOYDSTEINBERG = 3  # default\n\n# palettes/quantizers\nWEB = 0\nADAPTIVE = 1\n\nMEDIANCUT = 0\nMAXCOVERAGE = 1\nFASTOCTREE = 2\nLIBIMAGEQUANT = 3\n\n# categories\nNORMAL = 0\nSEQUENCE = 1\nCONTAINER = 2\n\nif hasattr(core, \"DEFAULT_STRATEGY\"):\n    DEFAULT_STRATEGY = core.DEFAULT_STRATEGY\n    FILTERED = core.FILTERED\n    HUFFMAN_ONLY = core.HUFFMAN_ONLY\n    RLE = core.RLE\n    FIXED = core.FIXED\n\n\n# --------------------------------------------------------------------\n# Registries\n\nID = []\nOPEN = {}\nMIME = {}\nSAVE = {}\nSAVE_ALL = {}\nEXTENSION = {}\nDECODERS = {}\nENCODERS = {}\n\n# --------------------------------------------------------------------\n# Modes supported by this version\n\n_MODEINFO = {\n    # NOTE: this table will be removed in future versions.  use\n    # getmode* functions or ImageMode descriptors instead.\n    # official modes\n    \"1\": (\"L\", \"L\", (\"1\",)),\n    \"L\": (\"L\", \"L\", (\"L\",)),\n    \"I\": (\"L\", \"I\", (\"I\",)),\n    \"F\": (\"L\", \"F\", (\"F\",)),\n    \"P\": (\"P\", \"L\", (\"P\",)),\n    \"RGB\": (\"RGB\", \"L\", (\"R\", \"G\", \"B\")),\n    \"RGBX\": (\"RGB\", \"L\", (\"R\", \"G\", \"B\", \"X\")),\n    \"RGBA\": (\"RGB\", \"L\", (\"R\", \"G\", \"B\", \"A\")),\n    \"CMYK\": (\"RGB\", \"L\", (\"C\", \"M\", \"Y\", \"K\")),\n    \"YCbCr\": (\"RGB\", \"L\", (\"Y\", \"Cb\", \"Cr\")),\n    \"LAB\": (\"RGB\", \"L\", (\"L\", \"A\", \"B\")),\n    \"HSV\": (\"RGB\", \"L\", (\"H\", \"S\", \"V\")),\n    # Experimental modes include I;16, I;16L, I;16B, RGBa, BGR;15, and\n    # BGR;24.  Use these modes only if you know exactly what you're\n    # doing...\n}\n\nif sys.byteorder == \"little\":\n    _ENDIAN = \"<\"\nelse:\n    _ENDIAN = \">\"\n\n_MODE_CONV = {\n    # official modes\n    \"1\": (\"|b1\", None),  # Bits need to be extended to bytes\n    \"L\": (\"|u1\", None),\n    \"LA\": (\"|u1\", 2),\n    \"I\": (_ENDIAN + \"i4\", None),\n    \"F\": (_ENDIAN + \"f4\", None),\n    \"P\": (\"|u1\", None),\n    \"RGB\": (\"|u1\", 3),\n    \"RGBX\": (\"|u1\", 4),\n    \"RGBA\": (\"|u1\", 4),\n    \"CMYK\": (\"|u1\", 4),\n    \"YCbCr\": (\"|u1\", 3),\n    \"LAB\": (\"|u1\", 3),  # UNDONE - unsigned |u1i1i1\n    \"HSV\": (\"|u1\", 3),\n    # I;16 == I;16L, and I;32 == I;32L\n    \"I;16\": (\"<u2\", None),\n    \"I;16B\": (\">u2\", None),\n    \"I;16L\": (\"<u2\", None),\n    \"I;16S\": (\"<i2\", None),\n    \"I;16BS\": (\">i2\", None),\n    \"I;16LS\": (\"<i2\", None),\n    \"I;32\": (\"<u4\", None),\n    \"I;32B\": (\">u4\", None),\n    \"I;32L\": (\"<u4\", None),\n    \"I;32S\": (\"<i4\", None),\n    \"I;32BS\": (\">i4\", None),\n    \"I;32LS\": (\"<i4\", None),\n}\n\n\ndef _conv_type_shape(im):\n    typ, extra = _MODE_CONV[im.mode]\n    if extra is None:\n        return (im.size[1], im.size[0]), typ\n    else:\n        return (im.size[1], im.size[0], extra), typ\n\n\nMODES = sorted(_MODEINFO)\n\n# raw modes that may be memory mapped.  NOTE: if you change this, you\n# may have to modify the stride calculation in map.c too!\n_MAPMODES = (\"L\", \"P\", \"RGBX\", \"RGBA\", \"CMYK\", \"I;16\", \"I;16L\", \"I;16B\")\n\n\ndef getmodebase(mode):\n    \"\"\"\n    Gets the \"base\" mode for given mode.  This function returns \"L\" for\n    images that contain grayscale data, and \"RGB\" for images that\n    contain color data.\n\n    :param mode: Input mode.\n    :returns: \"L\" or \"RGB\".\n    :exception KeyError: If the input mode was not a standard mode.\n    \"\"\"\n    return ImageMode.getmode(mode).basemode\n\n\ndef getmodetype(mode):\n    \"\"\"\n    Gets the storage type mode.  Given a mode, this function returns a\n    single-layer mode suitable for storing individual bands.\n\n    :param mode: Input mode.\n    :returns: \"L\", \"I\", or \"F\".\n    :exception KeyError: If the input mode was not a standard mode.\n    \"\"\"\n    return ImageMode.getmode(mode).basetype\n\n\ndef getmodebandnames(mode):\n    \"\"\"\n    Gets a list of individual band names.  Given a mode, this function returns\n    a tuple containing the names of individual bands (use\n    :py:method:`~PIL.Image.getmodetype` to get the mode used to store each\n    individual band.\n\n    :param mode: Input mode.\n    :returns: A tuple containing band names.  The length of the tuple\n        gives the number of bands in an image of the given mode.\n    :exception KeyError: If the input mode was not a standard mode.\n    \"\"\"\n    return ImageMode.getmode(mode).bands\n\n\ndef getmodebands(mode):\n    \"\"\"\n    Gets the number of individual bands for this mode.\n\n    :param mode: Input mode.\n    :returns: The number of bands in this mode.\n    :exception KeyError: If the input mode was not a standard mode.\n    \"\"\"\n    return len(ImageMode.getmode(mode).bands)\n\n\n# --------------------------------------------------------------------\n# Helpers\n\n_initialized = 0\n\n\ndef preinit():\n    \"\"\"Explicitly load standard file format drivers.\"\"\"\n\n    global _initialized\n    if _initialized >= 1:\n        return\n\n    try:\n        from . import BmpImagePlugin\n\n        assert BmpImagePlugin\n    except ImportError:\n        pass\n    try:\n        from . import GifImagePlugin\n\n        assert GifImagePlugin\n    except ImportError:\n        pass\n    try:\n        from . import JpegImagePlugin\n\n        assert JpegImagePlugin\n    except ImportError:\n        pass\n    try:\n        from . import PpmImagePlugin\n\n        assert PpmImagePlugin\n    except ImportError:\n        pass\n    try:\n        from . import PngImagePlugin\n\n        assert PngImagePlugin\n    except ImportError:\n        pass\n    # try:\n    #     import TiffImagePlugin\n    #     assert TiffImagePlugin\n    # except ImportError:\n    #     pass\n\n    _initialized = 1\n\n\ndef init():\n    \"\"\"\n    Explicitly initializes the Python Imaging Library. This function\n    loads all available file format drivers.\n    \"\"\"\n\n    global _initialized\n    if _initialized >= 2:\n        return 0\n\n    for plugin in _plugins:\n        try:\n            logger.debug(\"Importing %s\", plugin)\n            __import__(\"PIL.%s\" % plugin, globals(), locals(), [])\n        except ImportError as e:\n            logger.debug(\"Image: failed to import %s: %s\", plugin, e)\n\n    if OPEN or SAVE:\n        _initialized = 2\n        return 1\n\n\n# --------------------------------------------------------------------\n# Codec factories (used by tobytes/frombytes and ImageFile.load)\n\n\ndef _getdecoder(mode, decoder_name, args, extra=()):\n\n    # tweak arguments\n    if args is None:\n        args = ()\n    elif not isinstance(args, tuple):\n        args = (args,)\n\n    try:\n        decoder = DECODERS[decoder_name]\n    except KeyError:\n        pass\n    else:\n        return decoder(mode, *args + extra)\n\n    try:\n        # get decoder\n        decoder = getattr(core, decoder_name + \"_decoder\")\n    except AttributeError:\n        raise OSError(\"decoder %s not available\" % decoder_name)\n    return decoder(mode, *args + extra)\n\n\ndef _getencoder(mode, encoder_name, args, extra=()):\n\n    # tweak arguments\n    if args is None:\n        args = ()\n    elif not isinstance(args, tuple):\n        args = (args,)\n\n    try:\n        encoder = ENCODERS[encoder_name]\n    except KeyError:\n        pass\n    else:\n        return encoder(mode, *args + extra)\n\n    try:\n        # get encoder\n        encoder = getattr(core, encoder_name + \"_encoder\")\n    except AttributeError:\n        raise OSError(\"encoder %s not available\" % encoder_name)\n    return encoder(mode, *args + extra)\n\n\n# --------------------------------------------------------------------\n# Simple expression analyzer\n\n\ndef coerce_e(value):\n    return value if isinstance(value, _E) else _E(value)\n\n\nclass _E:\n    def __init__(self, data):\n        self.data = data\n\n    def __add__(self, other):\n        return _E((self.data, \"__add__\", coerce_e(other).data))\n\n    def __mul__(self, other):\n        return _E((self.data, \"__mul__\", coerce_e(other).data))\n\n\ndef _getscaleoffset(expr):\n    stub = [\"stub\"]\n    data = expr(_E(stub)).data\n    try:\n        (a, b, c) = data  # simplified syntax\n        if a is stub and b == \"__mul__\" and isinstance(c, numbers.Number):\n            return c, 0.0\n        if a is stub and b == \"__add__\" and isinstance(c, numbers.Number):\n            return 1.0, c\n    except TypeError:\n        pass\n    try:\n        ((a, b, c), d, e) = data  # full syntax\n        if (\n            a is stub\n            and b == \"__mul__\"\n            and isinstance(c, numbers.Number)\n            and d == \"__add__\"\n            and isinstance(e, numbers.Number)\n        ):\n            return c, e\n    except TypeError:\n        pass\n    raise ValueError(\"illegal expression\")\n\n\n# --------------------------------------------------------------------\n# Implementation wrapper\n\n\nclass Image:\n    \"\"\"\n    This class represents an image object.  To create\n    :py:class:`~PIL.Image.Image` objects, use the appropriate factory\n    functions.  There's hardly ever any reason to call the Image constructor\n    directly.\n\n    * :py:func:`~PIL.Image.open`\n    * :py:func:`~PIL.Image.new`\n    * :py:func:`~PIL.Image.frombytes`\n    \"\"\"\n\n    format = None\n    format_description = None\n    _close_exclusive_fp_after_loading = True\n\n    def __init__(self):\n        # FIXME: take \"new\" parameters / other image?\n        # FIXME: turn mode and size into delegating properties?\n        self.im = None\n        self.mode = \"\"\n        self._size = (0, 0)\n        self.palette = None\n        self.info = {}\n        self.category = NORMAL\n        self.readonly = 0\n        self.pyaccess = None\n        self._exif = None\n\n    @property\n    def width(self):\n        return self.size[0]\n\n    @property\n    def height(self):\n        return self.size[1]\n\n    @property\n    def size(self):\n        return self._size\n\n    def _new(self, im):\n        new = Image()\n        new.im = im\n        new.mode = im.mode\n        new._size = im.size\n        if im.mode in (\"P\", \"PA\"):\n            if self.palette:\n                new.palette = self.palette.copy()\n            else:\n                from . import ImagePalette\n\n                new.palette = ImagePalette.ImagePalette()\n        new.info = self.info.copy()\n        return new\n\n    # Context manager support\n    def __enter__(self):\n        return self\n\n    def __exit__(self, *args):\n        if hasattr(self, \"fp\") and getattr(self, \"_exclusive_fp\", False):\n            if hasattr(self, \"_close__fp\"):\n                self._close__fp()\n            if self.fp:\n                self.fp.close()\n        self.fp = None\n\n    def close(self):\n        \"\"\"\n        Closes the file pointer, if possible.\n\n        This operation will destroy the image core and release its memory.\n        The image data will be unusable afterward.\n\n        This function is only required to close images that have not\n        had their file read and closed by the\n        :py:meth:`~PIL.Image.Image.load` method. See\n        :ref:`file-handling` for more information.\n        \"\"\"\n        try:\n            if hasattr(self, \"_close__fp\"):\n                self._close__fp()\n            self.fp.close()\n            self.fp = None\n        except Exception as msg:\n            logger.debug(\"Error closing: %s\", msg)\n\n        if getattr(self, \"map\", None):\n            self.map = None\n\n        # Instead of simply setting to None, we're setting up a\n        # deferred error that will better explain that the core image\n        # object is gone.\n        self.im = deferred_error(ValueError(\"Operation on closed image\"))\n\n    def _copy(self):\n        self.load()\n        self.im = self.im.copy()\n        self.pyaccess = None\n        self.readonly = 0\n\n    def _ensure_mutable(self):\n        if self.readonly:\n            self._copy()\n        else:\n            self.load()\n\n    def _dump(self, file=None, format=None, **options):\n        suffix = \"\"\n        if format:\n            suffix = \".\" + format\n\n        if not file:\n            f, filename = tempfile.mkstemp(suffix)\n            os.close(f)\n        else:\n            filename = file\n            if not filename.endswith(suffix):\n                filename = filename + suffix\n\n        self.load()\n\n        if not format or format == \"PPM\":\n            self.im.save_ppm(filename)\n        else:\n            self.save(filename, format, **options)\n\n        return filename\n\n    def __eq__(self, other):\n        return (\n            self.__class__ is other.__class__\n            and self.mode == other.mode\n            and self.size == other.size\n            and self.info == other.info\n            and self.category == other.category\n            and self.readonly == other.readonly\n            and self.getpalette() == other.getpalette()\n            and self.tobytes() == other.tobytes()\n        )\n\n    def __repr__(self):\n        return \"<%s.%s image mode=%s size=%dx%d at 0x%X>\" % (\n            self.__class__.__module__,\n            self.__class__.__name__,\n            self.mode,\n            self.size[0],\n            self.size[1],\n            id(self),\n        )\n\n    def _repr_png_(self):\n        \"\"\" iPython display hook support\n\n        :returns: png version of the image as bytes\n        \"\"\"\n        b = io.BytesIO()\n        self.save(b, \"PNG\")\n        return b.getvalue()\n\n    @property\n    def __array_interface__(self):\n        # numpy array interface support\n        new = {}\n        shape, typestr = _conv_type_shape(self)\n        new[\"shape\"] = shape\n        new[\"typestr\"] = typestr\n        new[\"version\"] = 3\n        if self.mode == \"1\":\n            # Binary images need to be extended from bits to bytes\n            # See: https://github.com/python-pillow/Pillow/issues/350\n            new[\"data\"] = self.tobytes(\"raw\", \"L\")\n        else:\n            new[\"data\"] = self.tobytes()\n        return new\n\n    def __getstate__(self):\n        return [self.info, self.mode, self.size, self.getpalette(), self.tobytes()]\n\n    def __setstate__(self, state):\n        Image.__init__(self)\n        self.tile = []\n        info, mode, size, palette, data = state\n        self.info = info\n        self.mode = mode\n        self._size = size\n        self.im = core.new(mode, size)\n        if mode in (\"L\", \"LA\", \"P\", \"PA\") and palette:\n            self.putpalette(palette)\n        self.frombytes(data)\n\n    def tobytes(self, encoder_name=\"raw\", *args):\n        \"\"\"\n        Return image as a bytes object.\n\n        .. warning::\n\n            This method returns the raw image data from the internal\n            storage.  For compressed image data (e.g. PNG, JPEG) use\n            :meth:`~.save`, with a BytesIO parameter for in-memory\n            data.\n\n        :param encoder_name: What encoder to use.  The default is to\n                             use the standard \"raw\" encoder.\n        :param args: Extra arguments to the encoder.\n        :rtype: A bytes object.\n        \"\"\"\n\n        # may pass tuple instead of argument list\n        if len(args) == 1 and isinstance(args[0], tuple):\n            args = args[0]\n\n        if encoder_name == \"raw\" and args == ():\n            args = self.mode\n\n        self.load()\n\n        # unpack data\n        e = _getencoder(self.mode, encoder_name, args)\n        e.setimage(self.im)\n\n        bufsize = max(65536, self.size[0] * 4)  # see RawEncode.c\n\n        data = []\n        while True:\n            l, s, d = e.encode(bufsize)\n            data.append(d)\n            if s:\n                break\n        if s < 0:\n            raise RuntimeError(\"encoder error %d in tobytes\" % s)\n\n        return b\"\".join(data)\n\n    def tostring(self, *args, **kw):\n        raise NotImplementedError(\n            \"tostring() has been removed. Please call tobytes() instead.\"\n        )\n\n    def tobitmap(self, name=\"image\"):\n        \"\"\"\n        Returns the image converted to an X11 bitmap.\n\n        .. note:: This method only works for mode \"1\" images.\n\n        :param name: The name prefix to use for the bitmap variables.\n        :returns: A string containing an X11 bitmap.\n        :raises ValueError: If the mode is not \"1\"\n        \"\"\"\n\n        self.load()\n        if self.mode != \"1\":\n            raise ValueError(\"not a bitmap\")\n        data = self.tobytes(\"xbm\")\n        return b\"\".join(\n            [\n                (\"#define %s_width %d\\n\" % (name, self.size[0])).encode(\"ascii\"),\n                (\"#define %s_height %d\\n\" % (name, self.size[1])).encode(\"ascii\"),\n                (\"static char %s_bits[] = {\\n\" % name).encode(\"ascii\"),\n                data,\n                b\"};\",\n            ]\n        )\n\n    def frombytes(self, data, decoder_name=\"raw\", *args):\n        \"\"\"\n        Loads this image with pixel data from a bytes object.\n\n        This method is similar to the :py:func:`~PIL.Image.frombytes` function,\n        but loads data into this image instead of creating a new image object.\n        \"\"\"\n\n        # may pass tuple instead of argument list\n        if len(args) == 1 and isinstance(args[0], tuple):\n            args = args[0]\n\n        # default format\n        if decoder_name == \"raw\" and args == ():\n            args = self.mode\n\n        # unpack data\n        d = _getdecoder(self.mode, decoder_name, args)\n        d.setimage(self.im)\n        s = d.decode(data)\n\n        if s[0] >= 0:\n            raise ValueError(\"not enough image data\")\n        if s[1] != 0:\n            raise ValueError(\"cannot decode image data\")\n\n    def fromstring(self, *args, **kw):\n        raise NotImplementedError(\n            \"fromstring() has been removed. Please call frombytes() instead.\"\n        )\n\n    def load(self):\n        \"\"\"\n        Allocates storage for the image and loads the pixel data.  In\n        normal cases, you don't need to call this method, since the\n        Image class automatically loads an opened image when it is\n        accessed for the first time.\n\n        If the file associated with the image was opened by Pillow, then this\n        method will close it. The exception to this is if the image has\n        multiple frames, in which case the file will be left open for seek\n        operations. See :ref:`file-handling` for more information.\n\n        :returns: An image access object.\n        :rtype: :ref:`PixelAccess` or :py:class:`PIL.PyAccess`\n        \"\"\"\n        if self.im and self.palette and self.palette.dirty:\n            # realize palette\n            self.im.putpalette(*self.palette.getdata())\n            self.palette.dirty = 0\n            self.palette.mode = \"RGB\"\n            self.palette.rawmode = None\n            if \"transparency\" in self.info:\n                if isinstance(self.info[\"transparency\"], int):\n                    self.im.putpalettealpha(self.info[\"transparency\"], 0)\n                else:\n                    self.im.putpalettealphas(self.info[\"transparency\"])\n                self.palette.mode = \"RGBA\"\n\n        if self.im:\n            if cffi and USE_CFFI_ACCESS:\n                if self.pyaccess:\n                    return self.pyaccess\n                from . import PyAccess\n\n                self.pyaccess = PyAccess.new(self, self.readonly)\n                if self.pyaccess:\n                    return self.pyaccess\n            return self.im.pixel_access(self.readonly)\n\n    def verify(self):\n        \"\"\"\n        Verifies the contents of a file. For data read from a file, this\n        method attempts to determine if the file is broken, without\n        actually decoding the image data.  If this method finds any\n        problems, it raises suitable exceptions.  If you need to load\n        the image after using this method, you must reopen the image\n        file.\n        \"\"\"\n        pass\n\n    def convert(self, mode=None, matrix=None, dither=None, palette=WEB, colors=256):\n        \"\"\"\n        Returns a converted copy of this image. For the \"P\" mode, this\n        method translates pixels through the palette.  If mode is\n        omitted, a mode is chosen so that all information in the image\n        and the palette can be represented without a palette.\n\n        The current version supports all possible conversions between\n        \"L\", \"RGB\" and \"CMYK.\" The **matrix** argument only supports \"L\"\n        and \"RGB\".\n\n        When translating a color image to greyscale (mode \"L\"),\n        the library uses the ITU-R 601-2 luma transform::\n\n            L = R * 299/1000 + G * 587/1000 + B * 114/1000\n\n        The default method of converting a greyscale (\"L\") or \"RGB\"\n        image into a bilevel (mode \"1\") image uses Floyd-Steinberg\n        dither to approximate the original image luminosity levels. If\n        dither is NONE, all values larger than 128 are set to 255 (white),\n        all other values to 0 (black). To use other thresholds, use the\n        :py:meth:`~PIL.Image.Image.point` method.\n\n        When converting from \"RGBA\" to \"P\" without a **matrix** argument,\n        this passes the operation to :py:meth:`~PIL.Image.Image.quantize`,\n        and **dither** and **palette** are ignored.\n\n        :param mode: The requested mode. See: :ref:`concept-modes`.\n        :param matrix: An optional conversion matrix.  If given, this\n           should be 4- or 12-tuple containing floating point values.\n        :param dither: Dithering method, used when converting from\n           mode \"RGB\" to \"P\" or from \"RGB\" or \"L\" to \"1\".\n           Available methods are NONE or FLOYDSTEINBERG (default).\n           Note that this is not used when **matrix** is supplied.\n        :param palette: Palette to use when converting from mode \"RGB\"\n           to \"P\".  Available palettes are WEB or ADAPTIVE.\n        :param colors: Number of colors to use for the ADAPTIVE palette.\n           Defaults to 256.\n        :rtype: :py:class:`~PIL.Image.Image`\n        :returns: An :py:class:`~PIL.Image.Image` object.\n        \"\"\"\n\n        self.load()\n\n        if not mode and self.mode == \"P\":\n            # determine default mode\n            if self.palette:\n                mode = self.palette.mode\n            else:\n                mode = \"RGB\"\n        if not mode or (mode == self.mode and not matrix):\n            return self.copy()\n\n        has_transparency = self.info.get(\"transparency\") is not None\n        if matrix:\n            # matrix conversion\n            if mode not in (\"L\", \"RGB\"):\n                raise ValueError(\"illegal conversion\")\n            im = self.im.convert_matrix(mode, matrix)\n            new = self._new(im)\n            if has_transparency and self.im.bands == 3:\n                transparency = new.info[\"transparency\"]\n\n                def convert_transparency(m, v):\n                    v = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * 0.5\n                    return max(0, min(255, int(v)))\n\n                if mode == \"L\":\n                    transparency = convert_transparency(matrix, transparency)\n                elif len(mode) == 3:\n                    transparency = tuple(\n                        [\n                            convert_transparency(\n                                matrix[i * 4 : i * 4 + 4], transparency\n                            )\n                            for i in range(0, len(transparency))\n                        ]\n                    )\n                new.info[\"transparency\"] = transparency\n            return new\n\n        if mode == \"P\" and self.mode == \"RGBA\":\n            return self.quantize(colors)\n\n        trns = None\n        delete_trns = False\n        # transparency handling\n        if has_transparency:\n            if self.mode in (\"1\", \"L\", \"I\", \"RGB\") and mode == \"RGBA\":\n                # Use transparent conversion to promote from transparent\n                # color to an alpha channel.\n                new_im = self._new(\n                    self.im.convert_transparent(mode, self.info[\"transparency\"])\n                )\n                del new_im.info[\"transparency\"]\n                return new_im\n            elif self.mode in (\"L\", \"RGB\", \"P\") and mode in (\"L\", \"RGB\", \"P\"):\n                t = self.info[\"transparency\"]\n                if isinstance(t, bytes):\n                    # Dragons. This can't be represented by a single color\n                    warnings.warn(\n                        \"Palette images with Transparency expressed in bytes should be \"\n                        \"converted to RGBA images\"\n                    )\n                    delete_trns = True\n                else:\n                    # get the new transparency color.\n                    # use existing conversions\n                    trns_im = Image()._new(core.new(self.mode, (1, 1)))\n                    if self.mode == \"P\":\n                        trns_im.putpalette(self.palette)\n                        if isinstance(t, tuple):\n                            try:\n                                t = trns_im.palette.getcolor(t)\n                            except Exception:\n                                raise ValueError(\n                                    \"Couldn't allocate a palette color for transparency\"\n                                )\n                    trns_im.putpixel((0, 0), t)\n\n                    if mode in (\"L\", \"RGB\"):\n                        trns_im = trns_im.convert(mode)\n                    else:\n                        # can't just retrieve the palette number, got to do it\n                        # after quantization.\n                        trns_im = trns_im.convert(\"RGB\")\n                    trns = trns_im.getpixel((0, 0))\n\n            elif self.mode == \"P\" and mode == \"RGBA\":\n                t = self.info[\"transparency\"]\n                delete_trns = True\n\n                if isinstance(t, bytes):\n                    self.im.putpalettealphas(t)\n                elif isinstance(t, int):\n                    self.im.putpalettealpha(t, 0)\n                else:\n                    raise ValueError(\"Transparency for P mode should be bytes or int\")\n\n        if mode == \"P\" and palette == ADAPTIVE:\n            im = self.im.quantize(colors)\n            new = self._new(im)\n            from . import ImagePalette\n\n            new.palette = ImagePalette.raw(\"RGB\", new.im.getpalette(\"RGB\"))\n            if delete_trns:\n                # This could possibly happen if we requantize to fewer colors.\n                # The transparency would be totally off in that case.\n                del new.info[\"transparency\"]\n            if trns is not None:\n                try:\n                    new.info[\"transparency\"] = new.palette.getcolor(trns)\n                except Exception:\n                    # if we can't make a transparent color, don't leave the old\n                    # transparency hanging around to mess us up.\n                    del new.info[\"transparency\"]\n                    warnings.warn(\"Couldn't allocate palette entry for transparency\")\n            return new\n\n        # colorspace conversion\n        if dither is None:\n            dither = FLOYDSTEINBERG\n\n        try:\n            im = self.im.convert(mode, dither)\n        except ValueError:\n            try:\n                # normalize source image and try again\n                im = self.im.convert(getmodebase(self.mode))\n                im = im.convert(mode, dither)\n            except KeyError:\n                raise ValueError(\"illegal conversion\")\n\n        new_im = self._new(im)\n        if delete_trns:\n            # crash fail if we leave a bytes transparency in an rgb/l mode.\n            del new_im.info[\"transparency\"]\n        if trns is not None:\n            if new_im.mode == \"P\":\n                try:\n                    new_im.info[\"transparency\"] = new_im.palette.getcolor(trns)\n                except Exception:\n                    del new_im.info[\"transparency\"]\n                    warnings.warn(\"Couldn't allocate palette entry for transparency\")\n            else:\n                new_im.info[\"transparency\"] = trns\n        return new_im\n\n    def quantize(self, colors=256, method=None, kmeans=0, palette=None, dither=1):\n        \"\"\"\n        Convert the image to 'P' mode with the specified number\n        of colors.\n\n        :param colors: The desired number of colors, <= 256\n        :param method: 0 = median cut\n                       1 = maximum coverage\n                       2 = fast octree\n                       3 = libimagequant\n        :param kmeans: Integer\n        :param palette: Quantize to the palette of given\n                        :py:class:`PIL.Image.Image`.\n        :param dither: Dithering method, used when converting from\n           mode \"RGB\" to \"P\" or from \"RGB\" or \"L\" to \"1\".\n           Available methods are NONE or FLOYDSTEINBERG (default).\n           Default: 1 (legacy setting)\n        :returns: A new image\n\n        \"\"\"\n\n        self.load()\n\n        if method is None:\n            # defaults:\n            method = 0\n            if self.mode == \"RGBA\":\n                method = 2\n\n        if self.mode == \"RGBA\" and method not in (2, 3):\n            # Caller specified an invalid mode.\n            raise ValueError(\n                \"Fast Octree (method == 2) and libimagequant (method == 3) \"\n                \"are the only valid methods for quantizing RGBA images\"\n            )\n\n        if palette:\n            # use palette from reference image\n            palette.load()\n            if palette.mode != \"P\":\n                raise ValueError(\"bad mode for palette image\")\n            if self.mode != \"RGB\" and self.mode != \"L\":\n                raise ValueError(\n                    \"only RGB or L mode images can be quantized to a palette\"\n                )\n            im = self.im.convert(\"P\", dither, palette.im)\n            return self._new(im)\n\n        im = self._new(self.im.quantize(colors, method, kmeans))\n\n        from . import ImagePalette\n\n        mode = im.im.getpalettemode()\n        im.palette = ImagePalette.ImagePalette(mode, im.im.getpalette(mode, mode))\n\n        return im\n\n    def copy(self):\n        \"\"\"\n        Copies this image. Use this method if you wish to paste things\n        into an image, but still retain the original.\n\n        :rtype: :py:class:`~PIL.Image.Image`\n        :returns: An :py:class:`~PIL.Image.Image` object.\n        \"\"\"\n        self.load()\n        return self._new(self.im.copy())\n\n    __copy__ = copy\n\n    def crop(self, box=None):\n        \"\"\"\n        Returns a rectangular region from this image. The box is a\n        4-tuple defining the left, upper, right, and lower pixel\n        coordinate. See :ref:`coordinate-system`.\n\n        Note: Prior to Pillow 3.4.0, this was a lazy operation.\n\n        :param box: The crop rectangle, as a (left, upper, right, lower)-tuple.\n        :rtype: :py:class:`~PIL.Image.Image`\n        :returns: An :py:class:`~PIL.Image.Image` object.\n        \"\"\"\n\n        if box is None:\n            return self.copy()\n\n        self.load()\n        return self._new(self._crop(self.im, box))\n\n    def _crop(self, im, box):\n        \"\"\"\n        Returns a rectangular region from the core image object im.\n\n        This is equivalent to calling im.crop((x0, y0, x1, y1)), but\n        includes additional sanity checks.\n\n        :param im: a core image object\n        :param box: The crop rectangle, as a (left, upper, right, lower)-tuple.\n        :returns: A core image object.\n        \"\"\"\n\n        x0, y0, x1, y1 = map(int, map(round, box))\n\n        absolute_values = (abs(x1 - x0), abs(y1 - y0))\n\n        _decompression_bomb_check(absolute_values)\n\n        return im.crop((x0, y0, x1, y1))\n\n    def draft(self, mode, size):\n        \"\"\"\n        Configures the image file loader so it returns a version of the\n        image that as closely as possible matches the given mode and\n        size. For example, you can use this method to convert a color\n        JPEG to greyscale while loading it.\n\n        If any changes are made, returns a tuple with the chosen ``mode`` and\n        ``box`` with coordinates of the original image within the altered one.\n\n        Note that this method modifies the :py:class:`~PIL.Image.Image` object\n        in place. If the image has already been loaded, this method has no\n        effect.\n\n        Note: This method is not implemented for most images. It is\n        currently implemented only for JPEG and MPO images.\n\n        :param mode: The requested mode.\n        :param size: The requested size.\n        \"\"\"\n        pass\n\n    def _expand(self, xmargin, ymargin=None):\n        if ymargin is None:\n            ymargin = xmargin\n        self.load()\n        return self._new(self.im.expand(xmargin, ymargin, 0))\n\n    def filter(self, filter):\n        \"\"\"\n        Filters this image using the given filter.  For a list of\n        available filters, see the :py:mod:`~PIL.ImageFilter` module.\n\n        :param filter: Filter kernel.\n        :returns: An :py:class:`~PIL.Image.Image` object.  \"\"\"\n\n        from . import ImageFilter\n\n        self.load()\n\n        if isinstance(filter, Callable):\n            filter = filter()\n        if not hasattr(filter, \"filter\"):\n            raise TypeError(\n                \"filter argument should be ImageFilter.Filter instance or class\"\n            )\n\n        multiband = isinstance(filter, ImageFilter.MultibandFilter)\n        if self.im.bands == 1 or multiband:\n            return self._new(filter.filter(self.im))\n\n        ims = []\n        for c in range(self.im.bands):\n            ims.append(self._new(filter.filter(self.im.getband(c))))\n        return merge(self.mode, ims)\n\n    def getbands(self):\n        \"\"\"\n        Returns a tuple containing the name of each band in this image.\n        For example, **getbands** on an RGB image returns (\"R\", \"G\", \"B\").\n\n        :returns: A tuple containing band names.\n        :rtype: tuple\n        \"\"\"\n        return ImageMode.getmode(self.mode).bands\n\n    def getbbox(self):\n        \"\"\"\n        Calculates the bounding box of the non-zero regions in the\n        image.\n\n        :returns: The bounding box is returned as a 4-tuple defining the\n           left, upper, right, and lower pixel coordinate. See\n           :ref:`coordinate-system`. If the image is completely empty, this\n           method returns None.\n\n        \"\"\"\n\n        self.load()\n        return self.im.getbbox()\n\n    def getcolors(self, maxcolors=256):\n        \"\"\"\n        Returns a list of colors used in this image.\n\n        :param maxcolors: Maximum number of colors.  If this number is\n           exceeded, this method returns None.  The default limit is\n           256 colors.\n        :returns: An unsorted list of (count, pixel) values.\n        \"\"\"\n\n        self.load()\n        if self.mode in (\"1\", \"L\", \"P\"):\n            h = self.im.histogram()\n            out = []\n            for i in range(256):\n                if h[i]:\n                    out.append((h[i], i))\n            if len(out) > maxcolors:\n                return None\n            return out\n        return self.im.getcolors(maxcolors)\n\n    def getdata(self, band=None):\n        \"\"\"\n        Returns the contents of this image as a sequence object\n        containing pixel values.  The sequence object is flattened, so\n        that values for line one follow directly after the values of\n        line zero, and so on.\n\n        Note that the sequence object returned by this method is an\n        internal PIL data type, which only supports certain sequence\n        operations.  To convert it to an ordinary sequence (e.g. for\n        printing), use **list(im.getdata())**.\n\n        :param band: What band to return.  The default is to return\n           all bands.  To return a single band, pass in the index\n           value (e.g. 0 to get the \"R\" band from an \"RGB\" image).\n        :returns: A sequence-like object.\n        \"\"\"\n\n        self.load()\n        if band is not None:\n            return self.im.getband(band)\n        return self.im  # could be abused\n\n    def getextrema(self):\n        \"\"\"\n        Gets the the minimum and maximum pixel values for each band in\n        the image.\n\n        :returns: For a single-band image, a 2-tuple containing the\n           minimum and maximum pixel value.  For a multi-band image,\n           a tuple containing one 2-tuple for each band.\n        \"\"\"\n\n        self.load()\n        if self.im.bands > 1:\n            extrema = []\n            for i in range(self.im.bands):\n                extrema.append(self.im.getband(i).getextrema())\n            return tuple(extrema)\n        return self.im.getextrema()\n\n    def getexif(self):\n        if self._exif is None:\n            self._exif = Exif()\n\n        exif_info = self.info.get(\"exif\")\n        if exif_info is None and \"Raw profile type exif\" in self.info:\n            exif_info = bytes.fromhex(\n                \"\".join(self.info[\"Raw profile type exif\"].split(\"\\n\")[3:])\n            )\n        self._exif.load(exif_info)\n\n        # XMP tags\n        if 0x0112 not in self._exif:\n            xmp_tags = self.info.get(\"XML:com.adobe.xmp\")\n            if xmp_tags:\n                root = xml.etree.ElementTree.fromstring(xmp_tags)\n                for elem in root.iter():\n                    if elem.tag.endswith(\"}Description\"):\n                        orientation = elem.attrib.get(\n                            \"{http://ns.adobe.com/tiff/1.0/}Orientation\"\n                        )\n                        if orientation:\n                            self._exif[0x0112] = int(orientation)\n                        break\n\n        return self._exif\n\n    def getim(self):\n        \"\"\"\n        Returns a capsule that points to the internal image memory.\n\n        :returns: A capsule object.\n        \"\"\"\n\n        self.load()\n        return self.im.ptr\n\n    def getpalette(self):\n        \"\"\"\n        Returns the image palette as a list.\n\n        :returns: A list of color values [r, g, b, ...], or None if the\n           image has no palette.\n        \"\"\"\n\n        self.load()\n        try:\n            return list(self.im.getpalette())\n        except ValueError:\n            return None  # no palette\n\n    def getpixel(self, xy):\n        \"\"\"\n        Returns the pixel value at a given position.\n\n        :param xy: The coordinate, given as (x, y). See\n           :ref:`coordinate-system`.\n        :returns: The pixel value.  If the image is a multi-layer image,\n           this method returns a tuple.\n        \"\"\"\n\n        self.load()\n        if self.pyaccess:\n            return self.pyaccess.getpixel(xy)\n        return self.im.getpixel(xy)\n\n    def getprojection(self):\n        \"\"\"\n        Get projection to x and y axes\n\n        :returns: Two sequences, indicating where there are non-zero\n            pixels along the X-axis and the Y-axis, respectively.\n        \"\"\"\n\n        self.load()\n        x, y = self.im.getprojection()\n        return [i8(c) for c in x], [i8(c) for c in y]\n\n    def histogram(self, mask=None, extrema=None):\n        \"\"\"\n        Returns a histogram for the image. The histogram is returned as\n        a list of pixel counts, one for each pixel value in the source\n        image. If the image has more than one band, the histograms for\n        all bands are concatenated (for example, the histogram for an\n        \"RGB\" image contains 768 values).\n\n        A bilevel image (mode \"1\") is treated as a greyscale (\"L\") image\n        by this method.\n\n        If a mask is provided, the method returns a histogram for those\n        parts of the image where the mask image is non-zero. The mask\n        image must have the same size as the image, and be either a\n        bi-level image (mode \"1\") or a greyscale image (\"L\").\n\n        :param mask: An optional mask.\n        :param extrema: An optional tuple of manually-specified extrema.\n        :returns: A list containing pixel counts.\n        \"\"\"\n        self.load()\n        if mask:\n            mask.load()\n            return self.im.histogram((0, 0), mask.im)\n        if self.mode in (\"I\", \"F\"):\n            if extrema is None:\n                extrema = self.getextrema()\n            return self.im.histogram(extrema)\n        return self.im.histogram()\n\n    def entropy(self, mask=None, extrema=None):\n        \"\"\"\n        Calculates and returns the entropy for the image.\n\n        A bilevel image (mode \"1\") is treated as a greyscale (\"L\")\n        image by this method.\n\n        If a mask is provided, the method employs the histogram for\n        those parts of the image where the mask image is non-zero.\n        The mask image must have the same size as the image, and be\n        either a bi-level image (mode \"1\") or a greyscale image (\"L\").\n\n        :param mask: An optional mask.\n        :param extrema: An optional tuple of manually-specified extrema.\n        :returns: A float value representing the image entropy\n        \"\"\"\n        self.load()\n        if mask:\n            mask.load()\n            return self.im.entropy((0, 0), mask.im)\n        if self.mode in (\"I\", \"F\"):\n            if extrema is None:\n                extrema = self.getextrema()\n            return self.im.entropy(extrema)\n        return self.im.entropy()\n\n    def offset(self, xoffset, yoffset=None):\n        raise NotImplementedError(\n            \"offset() has been removed. Please call ImageChops.offset() instead.\"\n        )\n\n    def paste(self, im, box=None, mask=None):\n        \"\"\"\n        Pastes another image into this image. The box argument is either\n        a 2-tuple giving the upper left corner, a 4-tuple defining the\n        left, upper, right, and lower pixel coordinate, or None (same as\n        (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size\n        of the pasted image must match the size of the region.\n\n        If the modes don't match, the pasted image is converted to the mode of\n        this image (see the :py:meth:`~PIL.Image.Image.convert` method for\n        details).\n\n        Instead of an image, the source can be a integer or tuple\n        containing pixel values.  The method then fills the region\n        with the given color.  When creating RGB images, you can\n        also use color strings as supported by the ImageColor module.\n\n        If a mask is given, this method updates only the regions\n        indicated by the mask.  You can use either \"1\", \"L\" or \"RGBA\"\n        images (in the latter case, the alpha band is used as mask).\n        Where the mask is 255, the given image is copied as is.  Where\n        the mask is 0, the current value is preserved.  Intermediate\n        values will mix the two images together, including their alpha\n        channels if they have them.\n\n        See :py:meth:`~PIL.Image.Image.alpha_composite` if you want to\n        combine images with respect to their alpha channels.\n\n        :param im: Source image or pixel value (integer or tuple).\n        :param box: An optional 4-tuple giving the region to paste into.\n           If a 2-tuple is used instead, it's treated as the upper left\n           corner.  If omitted or None, the source is pasted into the\n           upper left corner.\n\n           If an image is given as the second argument and there is no\n           third, the box defaults to (0, 0), and the second argument\n           is interpreted as a mask image.\n        :param mask: An optional mask image.\n        \"\"\"\n\n        if isImageType(box) and mask is None:\n            # abbreviated paste(im, mask) syntax\n            mask = box\n            box = None\n\n        if box is None:\n            box = (0, 0)\n\n        if len(box) == 2:\n            # upper left corner given; get size from image or mask\n            if isImageType(im):\n                size = im.size\n            elif isImageType(mask):\n                size = mask.size\n            else:\n                # FIXME: use self.size here?\n                raise ValueError(\"cannot determine region size; use 4-item box\")\n            box += (box[0] + size[0], box[1] + size[1])\n\n        if isinstance(im, str):\n            from . import ImageColor\n\n            im = ImageColor.getcolor(im, self.mode)\n\n        elif isImageType(im):\n            im.load()\n            if self.mode != im.mode:\n                if self.mode != \"RGB\" or im.mode not in (\"RGBA\", \"RGBa\"):\n                    # should use an adapter for this!\n                    im = im.convert(self.mode)\n            im = im.im\n\n        self._ensure_mutable()\n\n        if mask:\n            mask.load()\n            self.im.paste(im, box, mask.im)\n        else:\n            self.im.paste(im, box)\n\n    def alpha_composite(self, im, dest=(0, 0), source=(0, 0)):\n        \"\"\" 'In-place' analog of Image.alpha_composite. Composites an image\n        onto this image.\n\n        :param im: image to composite over this one\n        :param dest: Optional 2 tuple (left, top) specifying the upper\n          left corner in this (destination) image.\n        :param source: Optional 2 (left, top) tuple for the upper left\n          corner in the overlay source image, or 4 tuple (left, top, right,\n          bottom) for the bounds of the source rectangle\n\n        Performance Note: Not currently implemented in-place in the core layer.\n        \"\"\"\n\n        if not isinstance(source, (list, tuple)):\n            raise ValueError(\"Source must be a tuple\")\n        if not isinstance(dest, (list, tuple)):\n            raise ValueError(\"Destination must be a tuple\")\n        if not len(source) in (2, 4):\n            raise ValueError(\"Source must be a 2 or 4-tuple\")\n        if not len(dest) == 2:\n            raise ValueError(\"Destination must be a 2-tuple\")\n        if min(source) < 0:\n            raise ValueError(\"Source must be non-negative\")\n        if min(dest) < 0:\n            raise ValueError(\"Destination must be non-negative\")\n\n        if len(source) == 2:\n            source = source + im.size\n\n        # over image, crop if it's not the whole thing.\n        if source == (0, 0) + im.size:\n            overlay = im\n        else:\n            overlay = im.crop(source)\n\n        # target for the paste\n        box = dest + (dest[0] + overlay.width, dest[1] + overlay.height)\n\n        # destination image. don't copy if we're using the whole image.\n        if box == (0, 0) + self.size:\n            background = self\n        else:\n            background = self.crop(box)\n\n        result = alpha_composite(background, overlay)\n        self.paste(result, box)\n\n    def point(self, lut, mode=None):\n        \"\"\"\n        Maps this image through a lookup table or function.\n\n        :param lut: A lookup table, containing 256 (or 65536 if\n           self.mode==\"I\" and mode == \"L\") values per band in the\n           image.  A function can be used instead, it should take a\n           single argument. The function is called once for each\n           possible pixel value, and the resulting table is applied to\n           all bands of the image.\n        :param mode: Output mode (default is same as input).  In the\n           current version, this can only be used if the source image\n           has mode \"L\" or \"P\", and the output has mode \"1\" or the\n           source image mode is \"I\" and the output mode is \"L\".\n        :returns: An :py:class:`~PIL.Image.Image` object.\n        \"\"\"\n\n        self.load()\n\n        if isinstance(lut, ImagePointHandler):\n            return lut.point(self)\n\n        if callable(lut):\n            # if it isn't a list, it should be a function\n            if self.mode in (\"I\", \"I;16\", \"F\"):\n                # check if the function can be used with point_transform\n                # UNDONE wiredfool -- I think this prevents us from ever doing\n                # a gamma function point transform on > 8bit images.\n                scale, offset = _getscaleoffset(lut)\n                return self._new(self.im.point_transform(scale, offset))\n            # for other modes, convert the function to a table\n            lut = [lut(i) for i in range(256)] * self.im.bands\n\n        if self.mode == \"F\":\n            # FIXME: _imaging returns a confusing error message for this case\n            raise ValueError(\"point operation not supported for this mode\")\n\n        return self._new(self.im.point(lut, mode))\n\n    def putalpha(self, alpha):\n        \"\"\"\n        Adds or replaces the alpha layer in this image.  If the image\n        does not have an alpha layer, it's converted to \"LA\" or \"RGBA\".\n        The new layer must be either \"L\" or \"1\".\n\n        :param alpha: The new alpha layer.  This can either be an \"L\" or \"1\"\n           image having the same size as this image, or an integer or\n           other color value.\n        \"\"\"\n\n        self._ensure_mutable()\n\n        if self.mode not in (\"LA\", \"PA\", \"RGBA\"):\n            # attempt to promote self to a matching alpha mode\n            try:\n                mode = getmodebase(self.mode) + \"A\"\n                try:\n                    self.im.setmode(mode)\n                except (AttributeError, ValueError):\n                    # do things the hard way\n                    im = self.im.convert(mode)\n                    if im.mode not in (\"LA\", \"PA\", \"RGBA\"):\n                        raise ValueError  # sanity check\n                    self.im = im\n                self.pyaccess = None\n                self.mode = self.im.mode\n            except (KeyError, ValueError):\n                raise ValueError(\"illegal image mode\")\n\n        if self.mode in (\"LA\", \"PA\"):\n            band = 1\n        else:\n            band = 3\n\n        if isImageType(alpha):\n            # alpha layer\n            if alpha.mode not in (\"1\", \"L\"):\n                raise ValueError(\"illegal image mode\")\n            alpha.load()\n            if alpha.mode == \"1\":\n                alpha = alpha.convert(\"L\")\n        else:\n            # constant alpha\n            try:\n                self.im.fillband(band, alpha)\n            except (AttributeError, ValueError):\n                # do things the hard way\n                alpha = new(\"L\", self.size, alpha)\n            else:\n                return\n\n        self.im.putband(alpha.im, band)\n\n    def putdata(self, data, scale=1.0, offset=0.0):\n        \"\"\"\n        Copies pixel data to this image.  This method copies data from a\n        sequence object into the image, starting at the upper left\n        corner (0, 0), and continuing until either the image or the\n        sequence ends.  The scale and offset values are used to adjust\n        the sequence values: **pixel = value*scale + offset**.\n\n        :param data: A sequence object.\n        :param scale: An optional scale value.  The default is 1.0.\n        :param offset: An optional offset value.  The default is 0.0.\n        \"\"\"\n\n        self._ensure_mutable()\n\n        self.im.putdata(data, scale, offset)\n\n    def putpalette(self, data, rawmode=\"RGB\"):\n        \"\"\"\n        Attaches a palette to this image.  The image must be a \"P\",\n        \"PA\", \"L\" or \"LA\" image, and the palette sequence must contain\n        768 integer values, where each group of three values represent\n        the red, green, and blue values for the corresponding pixel\n        index. Instead of an integer sequence, you can use an 8-bit\n        string.\n\n        :param data: A palette sequence (either a list or a string).\n        :param rawmode: The raw mode of the palette.\n        \"\"\"\n        from . import ImagePalette\n\n        if self.mode not in (\"L\", \"LA\", \"P\", \"PA\"):\n            raise ValueError(\"illegal image mode\")\n        self.load()\n        if isinstance(data, ImagePalette.ImagePalette):\n            palette = ImagePalette.raw(data.rawmode, data.palette)\n        else:\n            if not isinstance(data, bytes):\n                data = bytes(data)\n            palette = ImagePalette.raw(rawmode, data)\n        self.mode = \"PA\" if \"A\" in self.mode else \"P\"\n        self.palette = palette\n        self.palette.mode = \"RGB\"\n        self.load()  # install new palette\n\n    def putpixel(self, xy, value):\n        \"\"\"\n        Modifies the pixel at the given position. The color is given as\n        a single numerical value for single-band images, and a tuple for\n        multi-band images. In addition to this, RGB and RGBA tuples are\n        accepted for P images.\n\n        Note that this method is relatively slow.  For more extensive changes,\n        use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw`\n        module instead.\n\n        See:\n\n        * :py:meth:`~PIL.Image.Image.paste`\n        * :py:meth:`~PIL.Image.Image.putdata`\n        * :py:mod:`~PIL.ImageDraw`\n\n        :param xy: The pixel coordinate, given as (x, y). See\n           :ref:`coordinate-system`.\n        :param value: The pixel value.\n        \"\"\"\n\n        if self.readonly:\n            self._copy()\n        self.load()\n\n        if self.pyaccess:\n            return self.pyaccess.putpixel(xy, value)\n\n        if (\n            self.mode == \"P\"\n            and isinstance(value, (list, tuple))\n            and len(value) in [3, 4]\n        ):\n            # RGB or RGBA value for a P image\n            value = self.palette.getcolor(value)\n        return self.im.putpixel(xy, value)\n\n    def remap_palette(self, dest_map, source_palette=None):\n        \"\"\"\n        Rewrites the image to reorder the palette.\n\n        :param dest_map: A list of indexes into the original palette.\n           e.g. [1,0] would swap a two item palette, and list(range(256))\n           is the identity transform.\n        :param source_palette: Bytes or None.\n        :returns:  An :py:class:`~PIL.Image.Image` object.\n\n        \"\"\"\n        from . import ImagePalette\n\n        if self.mode not in (\"L\", \"P\"):\n            raise ValueError(\"illegal image mode\")\n\n        if source_palette is None:\n            if self.mode == \"P\":\n                real_source_palette = self.im.getpalette(\"RGB\")[:768]\n            else:  # L-mode\n                real_source_palette = bytearray(i // 3 for i in range(768))\n        else:\n            real_source_palette = source_palette\n\n        palette_bytes = b\"\"\n        new_positions = [0] * 256\n\n        # pick only the used colors from the palette\n        for i, oldPosition in enumerate(dest_map):\n            palette_bytes += real_source_palette[oldPosition * 3 : oldPosition * 3 + 3]\n            new_positions[oldPosition] = i\n\n        # replace the palette color id of all pixel with the new id\n\n        # Palette images are [0..255], mapped through a 1 or 3\n        # byte/color map.  We need to remap the whole image\n        # from palette 1 to palette 2. New_positions is\n        # an array of indexes into palette 1.  Palette 2 is\n        # palette 1 with any holes removed.\n\n        # We're going to leverage the convert mechanism to use the\n        # C code to remap the image from palette 1 to palette 2,\n        # by forcing the source image into 'L' mode and adding a\n        # mapping 'L' mode palette, then converting back to 'L'\n        # sans palette thus converting the image bytes, then\n        # assigning the optimized RGB palette.\n\n        # perf reference, 9500x4000 gif, w/~135 colors\n        # 14 sec prepatch, 1 sec postpatch with optimization forced.\n\n        mapping_palette = bytearray(new_positions)\n\n        m_im = self.copy()\n        m_im.mode = \"P\"\n\n        m_im.palette = ImagePalette.ImagePalette(\n            \"RGB\", palette=mapping_palette * 3, size=768\n        )\n        # possibly set palette dirty, then\n        # m_im.putpalette(mapping_palette, 'L')  # converts to 'P'\n        # or just force it.\n        # UNDONE -- this is part of the general issue with palettes\n        m_im.im.putpalette(*m_im.palette.getdata())\n\n        m_im = m_im.convert(\"L\")\n\n        # Internally, we require 768 bytes for a palette.\n        new_palette_bytes = palette_bytes + (768 - len(palette_bytes)) * b\"\\x00\"\n        m_im.putpalette(new_palette_bytes)\n        m_im.palette = ImagePalette.ImagePalette(\n            \"RGB\", palette=palette_bytes, size=len(palette_bytes)\n        )\n\n        return m_im\n\n    def _get_safe_box(self, size, resample, box):\n        \"\"\"Expands the box so it includes adjacent pixels\n        that may be used by resampling with the given resampling filter.\n        \"\"\"\n        filter_support = _filters_support[resample] - 0.5\n        scale_x = (box[2] - box[0]) / size[0]\n        scale_y = (box[3] - box[1]) / size[1]\n        support_x = filter_support * scale_x\n        support_y = filter_support * scale_y\n\n        return (\n            max(0, int(box[0] - support_x)),\n            max(0, int(box[1] - support_y)),\n            min(self.size[0], math.ceil(box[2] + support_x)),\n            min(self.size[1], math.ceil(box[3] + support_y)),\n        )\n\n    def resize(self, size, resample=BICUBIC, box=None, reducing_gap=None):\n        \"\"\"\n        Returns a resized copy of this image.\n\n        :param size: The requested size in pixels, as a 2-tuple:\n           (width, height).\n        :param resample: An optional resampling filter.  This can be\n           one of :py:attr:`PIL.Image.NEAREST`, :py:attr:`PIL.Image.BOX`,\n           :py:attr:`PIL.Image.BILINEAR`, :py:attr:`PIL.Image.HAMMING`,\n           :py:attr:`PIL.Image.BICUBIC` or :py:attr:`PIL.Image.LANCZOS`.\n           Default filter is :py:attr:`PIL.Image.BICUBIC`.\n           If the image has mode \"1\" or \"P\", it is\n           always set to :py:attr:`PIL.Image.NEAREST`.\n           See: :ref:`concept-filters`.\n        :param box: An optional 4-tuple of floats providing\n           the source image region to be scaled.\n           The values must be within (0, 0, width, height) rectangle.\n           If omitted or None, the entire source is used.\n        :param reducing_gap: Apply optimization by resizing the image\n           in two steps. First, reducing the image by integer times\n           using :py:meth:`~PIL.Image.Image.reduce`.\n           Second, resizing using regular resampling. The last step\n           changes size no less than by ``reducing_gap`` times.\n           ``reducing_gap`` may be None (no first step is performed)\n           or should be greater than 1.0. The bigger ``reducing_gap``,\n           the closer the result to the fair resampling.\n           The smaller ``reducing_gap``, the faster resizing.\n           With ``reducing_gap`` greater or equal to 3.0, the result is\n           indistinguishable from fair resampling in most cases.\n           The default value is None (no optimization).\n        :returns: An :py:class:`~PIL.Image.Image` object.\n        \"\"\"\n\n        if resample not in (NEAREST, BILINEAR, BICUBIC, LANCZOS, BOX, HAMMING):\n            message = \"Unknown resampling filter ({}).\".format(resample)\n\n            filters = [\n                \"{} ({})\".format(filter[1], filter[0])\n                for filter in (\n                    (NEAREST, \"Image.NEAREST\"),\n                    (LANCZOS, \"Image.LANCZOS\"),\n                    (BILINEAR, \"Image.BILINEAR\"),\n                    (BICUBIC, \"Image.BICUBIC\"),\n                    (BOX, \"Image.BOX\"),\n                    (HAMMING, \"Image.HAMMING\"),\n                )\n            ]\n            raise ValueError(\n                message + \" Use \" + \", \".join(filters[:-1]) + \" or \" + filters[-1]\n            )\n\n        if reducing_gap is not None and reducing_gap < 1.0:\n            raise ValueError(\"reducing_gap must be 1.0 or greater\")\n\n        size = tuple(size)\n\n        if box is None:\n            box = (0, 0) + self.size\n        else:\n            box = tuple(box)\n\n        if self.size == size and box == (0, 0) + self.size:\n            return self.copy()\n\n        if self.mode in (\"1\", \"P\"):\n            resample = NEAREST\n\n        if self.mode in [\"LA\", \"RGBA\"]:\n            im = self.convert(self.mode[:-1] + \"a\")\n            im = im.resize(size, resample, box)\n            return im.convert(self.mode)\n\n        self.load()\n\n        if reducing_gap is not None and resample != NEAREST:\n            factor_x = int((box[2] - box[0]) / size[0] / reducing_gap) or 1\n            factor_y = int((box[3] - box[1]) / size[1] / reducing_gap) or 1\n            if factor_x > 1 or factor_y > 1:\n                reduce_box = self._get_safe_box(size, resample, box)\n                factor = (factor_x, factor_y)\n                if callable(self.reduce):\n                    self = self.reduce(factor, box=reduce_box)\n                else:\n                    self = Image.reduce(self, factor, box=reduce_box)\n                box = (\n                    (box[0] - reduce_box[0]) / factor_x,\n                    (box[1] - reduce_box[1]) / factor_y,\n                    (box[2] - reduce_box[0]) / factor_x,\n                    (box[3] - reduce_box[1]) / factor_y,\n                )\n\n        return self._new(self.im.resize(size, resample, box))\n\n    def reduce(self, factor, box=None):\n        \"\"\"\n        Returns a copy of the image reduced by `factor` times.\n        If the size of the image is not dividable by the `factor`,\n        the resulting size will be rounded up.\n\n        :param factor: A greater than 0 integer or tuple of two integers\n           for width and height separately.\n        :param box: An optional 4-tuple of ints providing\n           the source image region to be reduced.\n           The values must be within (0, 0, width, height) rectangle.\n           If omitted or None, the entire source is used.\n        \"\"\"\n        if not isinstance(factor, (list, tuple)):\n            factor = (factor, factor)\n\n        if box is None:\n            box = (0, 0) + self.size\n        else:\n            box = tuple(box)\n\n        if factor == (1, 1) and box == (0, 0) + self.size:\n            return self.copy()\n\n        if self.mode in [\"LA\", \"RGBA\"]:\n            im = self.convert(self.mode[:-1] + \"a\")\n            im = im.reduce(factor, box)\n            return im.convert(self.mode)\n\n        self.load()\n\n        return self._new(self.im.reduce(factor, box))\n\n    def rotate(\n        self,\n        angle,\n        resample=NEAREST,\n        expand=0,\n        center=None,\n        translate=None,\n        fillcolor=None,\n    ):\n        \"\"\"\n        Returns a rotated copy of this image.  This method returns a\n        copy of this image, rotated the given number of degrees counter\n        clockwise around its centre.\n\n        :param angle: In degrees counter clockwise.\n        :param resample: An optional resampling filter.  This can be\n           one of :py:attr:`PIL.Image.NEAREST` (use nearest neighbour),\n           :py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2\n           environment), or :py:attr:`PIL.Image.BICUBIC`\n           (cubic spline interpolation in a 4x4 environment).\n           If omitted, or if the image has mode \"1\" or \"P\", it is\n           set to :py:attr:`PIL.Image.NEAREST`. See :ref:`concept-filters`.\n        :param expand: Optional expansion flag.  If true, expands the output\n           image to make it large enough to hold the entire rotated image.\n           If false or omitted, make the output image the same size as the\n           input image.  Note that the expand flag assumes rotation around\n           the center and no translation.\n        :param center: Optional center of rotation (a 2-tuple).  Origin is\n           the upper left corner.  Default is the center of the image.\n        :param translate: An optional post-rotate translation (a 2-tuple).\n        :param fillcolor: An optional color for area outside the rotated image.\n        :returns: An :py:class:`~PIL.Image.Image` object.\n        \"\"\"\n\n        angle = angle % 360.0\n\n        # Fast paths regardless of filter, as long as we're not\n        # translating or changing the center.\n        if not (center or translate):\n            if angle == 0:\n                return self.copy()\n            if angle == 180:\n                return self.transpose(ROTATE_180)\n            if angle == 90 and expand:\n                return self.transpose(ROTATE_90)\n            if angle == 270 and expand:\n                return self.transpose(ROTATE_270)\n\n        # Calculate the affine matrix.  Note that this is the reverse\n        # transformation (from destination image to source) because we\n        # want to interpolate the (discrete) destination pixel from\n        # the local area around the (floating) source pixel.\n\n        # The matrix we actually want (note that it operates from the right):\n        # (1, 0, tx)   (1, 0, cx)   ( cos a, sin a, 0)   (1, 0, -cx)\n        # (0, 1, ty) * (0, 1, cy) * (-sin a, cos a, 0) * (0, 1, -cy)\n        # (0, 0,  1)   (0, 0,  1)   (     0,     0, 1)   (0, 0,   1)\n\n        # The reverse matrix is thus:\n        # (1, 0, cx)   ( cos -a, sin -a, 0)   (1, 0, -cx)   (1, 0, -tx)\n        # (0, 1, cy) * (-sin -a, cos -a, 0) * (0, 1, -cy) * (0, 1, -ty)\n        # (0, 0,  1)   (      0,      0, 1)   (0, 0,   1)   (0, 0,   1)\n\n        # In any case, the final translation may be updated at the end to\n        # compensate for the expand flag.\n\n        w, h = self.size\n\n        if translate is None:\n            post_trans = (0, 0)\n        else:\n            post_trans = translate\n        if center is None:\n            # FIXME These should be rounded to ints?\n            rotn_center = (w / 2.0, h / 2.0)\n        else:\n            rotn_center = center\n\n        angle = -math.radians(angle)\n        matrix = [\n            round(math.cos(angle), 15),\n            round(math.sin(angle), 15),\n            0.0,\n            round(-math.sin(angle), 15),\n            round(math.cos(angle), 15),\n            0.0,\n        ]\n\n        def transform(x, y, matrix):\n            (a, b, c, d, e, f) = matrix\n            return a * x + b * y + c, d * x + e * y + f\n\n        matrix[2], matrix[5] = transform(\n            -rotn_center[0] - post_trans[0], -rotn_center[1] - post_trans[1], matrix\n        )\n        matrix[2] += rotn_center[0]\n        matrix[5] += rotn_center[1]\n\n        if expand:\n            # calculate output size\n            xx = []\n            yy = []\n            for x, y in ((0, 0), (w, 0), (w, h), (0, h)):\n                x, y = transform(x, y, matrix)\n                xx.append(x)\n                yy.append(y)\n            nw = math.ceil(max(xx)) - math.floor(min(xx))\n            nh = math.ceil(max(yy)) - math.floor(min(yy))\n\n            # We multiply a translation matrix from the right.  Because of its\n            # special form, this is the same as taking the image of the\n            # translation vector as new translation vector.\n            matrix[2], matrix[5] = transform(-(nw - w) / 2.0, -(nh - h) / 2.0, matrix)\n            w, h = nw, nh\n\n        return self.transform((w, h), AFFINE, matrix, resample, fillcolor=fillcolor)\n\n    def save(self, fp, format=None, **params):\n        \"\"\"\n        Saves this image under the given filename.  If no format is\n        specified, the format to use is determined from the filename\n        extension, if possible.\n\n        Keyword options can be used to provide additional instructions\n        to the writer. If a writer doesn't recognise an option, it is\n        silently ignored. The available options are described in the\n        :doc:`image format documentation\n        <../handbook/image-file-formats>` for each writer.\n\n        You can use a file object instead of a filename. In this case,\n        you must always specify the format. The file object must\n        implement the ``seek``, ``tell``, and ``write``\n        methods, and be opened in binary mode.\n\n        :param fp: A filename (string), pathlib.Path object or file object.\n        :param format: Optional format override.  If omitted, the\n           format to use is determined from the filename extension.\n           If a file object was used instead of a filename, this\n           parameter should always be used.\n        :param params: Extra parameters to the image writer.\n        :returns: None\n        :exception ValueError: If the output format could not be determined\n           from the file name.  Use the format option to solve this.\n        :exception OSError: If the file could not be written.  The file\n           may have been created, and may contain partial data.\n        \"\"\"\n\n        filename = \"\"\n        open_fp = False\n        if isPath(fp):\n            filename = fp\n            open_fp = True\n        elif isinstance(fp, Path):\n            filename = str(fp)\n            open_fp = True\n        if not filename and hasattr(fp, \"name\") and isPath(fp.name):\n            # only set the name for metadata purposes\n            filename = fp.name\n\n        # may mutate self!\n        self._ensure_mutable()\n\n        save_all = params.pop(\"save_all\", False)\n        self.encoderinfo = params\n        self.encoderconfig = ()\n\n        preinit()\n\n        ext = os.path.splitext(filename)[1].lower()\n\n        if not format:\n            if ext not in EXTENSION:\n                init()\n            try:\n                format = EXTENSION[ext]\n            except KeyError:\n                raise ValueError(\"unknown file extension: {}\".format(ext))\n\n        if format.upper() not in SAVE:\n            init()\n        if save_all:\n            save_handler = SAVE_ALL[format.upper()]\n        else:\n            save_handler = SAVE[format.upper()]\n\n        if open_fp:\n            if params.get(\"append\", False):\n                # Open also for reading (\"+\"), because TIFF save_all\n                # writer needs to go back and edit the written data.\n                fp = builtins.open(filename, \"r+b\")\n            else:\n                fp = builtins.open(filename, \"w+b\")\n\n        try:\n            save_handler(self, fp, filename)\n        finally:\n            # do what we can to clean up\n            if open_fp:\n                fp.close()\n\n    def seek(self, frame):\n        \"\"\"\n        Seeks to the given frame in this sequence file. If you seek\n        beyond the end of the sequence, the method raises an\n        **EOFError** exception. When a sequence file is opened, the\n        library automatically seeks to frame 0.\n\n        See :py:meth:`~PIL.Image.Image.tell`.\n\n        :param frame: Frame number, starting at 0.\n        :exception EOFError: If the call attempts to seek beyond the end\n            of the sequence.\n        \"\"\"\n\n        # overridden by file handlers\n        if frame != 0:\n            raise EOFError\n\n    def show(self, title=None, command=None):\n        \"\"\"\n        Displays this image. This method is mainly intended for\n        debugging purposes.\n\n        The image is first saved to a temporary file. By default, it will be in\n        PNG format.\n\n        On Unix, the image is then opened using the **display**, **eog** or\n        **xv** utility, depending on which one can be found.\n\n        On macOS, the image is opened with the native Preview application.\n\n        On Windows, the image is opened with the standard PNG display utility.\n\n        :param title: Optional title to use for the image window,\n           where possible.\n        :param command: command used to show the image\n        \"\"\"\n\n        _show(self, title=title, command=command)\n\n    def split(self):\n        \"\"\"\n        Split this image into individual bands. This method returns a\n        tuple of individual image bands from an image. For example,\n        splitting an \"RGB\" image creates three new images each\n        containing a copy of one of the original bands (red, green,\n        blue).\n\n        If you need only one band, :py:meth:`~PIL.Image.Image.getchannel`\n        method can be more convenient and faster.\n\n        :returns: A tuple containing bands.\n        \"\"\"\n\n        self.load()\n        if self.im.bands == 1:\n            ims = [self.copy()]\n        else:\n            ims = map(self._new, self.im.split())\n        return tuple(ims)\n\n    def getchannel(self, channel):\n        \"\"\"\n        Returns an image containing a single channel of the source image.\n\n        :param channel: What channel to return. Could be index\n          (0 for \"R\" channel of \"RGB\") or channel name\n          (\"A\" for alpha channel of \"RGBA\").\n        :returns: An image in \"L\" mode.\n\n        .. versionadded:: 4.3.0\n        \"\"\"\n        self.load()\n\n        if isinstance(channel, str):\n            try:\n                channel = self.getbands().index(channel)\n            except ValueError:\n                raise ValueError('The image has no channel \"{}\"'.format(channel))\n\n        return self._new(self.im.getband(channel))\n\n    def tell(self):\n        \"\"\"\n        Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`.\n\n        :returns: Frame number, starting with 0.\n        \"\"\"\n        return 0\n\n    def thumbnail(self, size, resample=BICUBIC, reducing_gap=2.0):\n        \"\"\"\n        Make this image into a thumbnail.  This method modifies the\n        image to contain a thumbnail version of itself, no larger than\n        the given size.  This method calculates an appropriate thumbnail\n        size to preserve the aspect of the image, calls the\n        :py:meth:`~PIL.Image.Image.draft` method to configure the file reader\n        (where applicable), and finally resizes the image.\n\n        Note that this function modifies the :py:class:`~PIL.Image.Image`\n        object in place.  If you need to use the full resolution image as well,\n        apply this method to a :py:meth:`~PIL.Image.Image.copy` of the original\n        image.\n\n        :param size: Requested size.\n        :param resample: Optional resampling filter.  This can be one\n           of :py:attr:`PIL.Image.NEAREST`, :py:attr:`PIL.Image.BILINEAR`,\n           :py:attr:`PIL.Image.BICUBIC`, or :py:attr:`PIL.Image.LANCZOS`.\n           If omitted, it defaults to :py:attr:`PIL.Image.BICUBIC`.\n           (was :py:attr:`PIL.Image.NEAREST` prior to version 2.5.0).\n           See: :ref:`concept-filters`.\n        :param reducing_gap: Apply optimization by resizing the image\n           in two steps. First, reducing the image by integer times\n           using :py:meth:`~PIL.Image.Image.reduce` or\n           :py:meth:`~PIL.Image.Image.draft` for JPEG images.\n           Second, resizing using regular resampling. The last step\n           changes size no less than by ``reducing_gap`` times.\n           ``reducing_gap`` may be None (no first step is performed)\n           or should be greater than 1.0. The bigger ``reducing_gap``,\n           the closer the result to the fair resampling.\n           The smaller ``reducing_gap``, the faster resizing.\n           With ``reducing_gap`` greater or equal to 3.0, the result is\n           indistinguishable from fair resampling in most cases.\n           The default value is 2.0 (very close to fair resampling\n           while still being faster in many cases).\n        :returns: None\n        \"\"\"\n\n        x, y = map(math.floor, size)\n        if x >= self.width and y >= self.height:\n            return\n\n        def round_aspect(number, key):\n            return max(min(math.floor(number), math.ceil(number), key=key), 1)\n\n        # preserve aspect ratio\n        aspect = self.width / self.height\n        if x / y >= aspect:\n            x = round_aspect(y * aspect, key=lambda n: abs(aspect - n / y))\n        else:\n            y = round_aspect(\n                x / aspect, key=lambda n: 0 if n == 0 else abs(aspect - x / n)\n            )\n        size = (x, y)\n\n        box = None\n        if reducing_gap is not None:\n            res = self.draft(None, (size[0] * reducing_gap, size[1] * reducing_gap))\n            if res is not None:\n                box = res[1]\n\n        if self.size != size:\n            im = self.resize(size, resample, box=box, reducing_gap=reducing_gap)\n\n            self.im = im.im\n            self._size = size\n            self.mode = self.im.mode\n\n        self.readonly = 0\n        self.pyaccess = None\n\n    # FIXME: the different transform methods need further explanation\n    # instead of bloating the method docs, add a separate chapter.\n    def transform(\n        self, size, method, data=None, resample=NEAREST, fill=1, fillcolor=None\n    ):\n        \"\"\"\n        Transforms this image.  This method creates a new image with the\n        given size, and the same mode as the original, and copies data\n        to the new image using the given transform.\n\n        :param size: The output size.\n        :param method: The transformation method.  This is one of\n          :py:attr:`PIL.Image.EXTENT` (cut out a rectangular subregion),\n          :py:attr:`PIL.Image.AFFINE` (affine transform),\n          :py:attr:`PIL.Image.PERSPECTIVE` (perspective transform),\n          :py:attr:`PIL.Image.QUAD` (map a quadrilateral to a rectangle), or\n          :py:attr:`PIL.Image.MESH` (map a number of source quadrilaterals\n          in one operation).\n\n          It may also be an :py:class:`~PIL.Image.ImageTransformHandler`\n          object::\n\n            class Example(Image.ImageTransformHandler):\n                def transform(size, method, data, resample, fill=1):\n                    # Return result\n\n          It may also be an object with a :py:meth:`~method.getdata` method\n          that returns a tuple supplying new **method** and **data** values::\n\n            class Example:\n                def getdata(self):\n                    method = Image.EXTENT\n                    data = (0, 0, 100, 100)\n                    return method, data\n        :param data: Extra data to the transformation method.\n        :param resample: Optional resampling filter.  It can be one of\n           :py:attr:`PIL.Image.NEAREST` (use nearest neighbour),\n           :py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2\n           environment), or :py:attr:`PIL.Image.BICUBIC` (cubic spline\n           interpolation in a 4x4 environment). If omitted, or if the image\n           has mode \"1\" or \"P\", it is set to :py:attr:`PIL.Image.NEAREST`.\n           See: :ref:`concept-filters`.\n        :param fill: If **method** is an\n          :py:class:`~PIL.Image.ImageTransformHandler` object, this is one of\n          the arguments passed to it. Otherwise, it is unused.\n        :param fillcolor: Optional fill color for the area outside the\n           transform in the output image.\n        :returns: An :py:class:`~PIL.Image.Image` object.\n        \"\"\"\n\n        if self.mode == \"LA\":\n            return (\n                self.convert(\"La\")\n                .transform(size, method, data, resample, fill, fillcolor)\n                .convert(\"LA\")\n            )\n\n        if self.mode == \"RGBA\":\n            return (\n                self.convert(\"RGBa\")\n                .transform(size, method, data, resample, fill, fillcolor)\n                .convert(\"RGBA\")\n            )\n\n        if isinstance(method, ImageTransformHandler):\n            return method.transform(size, self, resample=resample, fill=fill)\n\n        if hasattr(method, \"getdata\"):\n            # compatibility w. old-style transform objects\n            method, data = method.getdata()\n\n        if data is None:\n            raise ValueError(\"missing method data\")\n\n        im = new(self.mode, size, fillcolor)\n        im.info = self.info.copy()\n        if method == MESH:\n            # list of quads\n            for box, quad in data:\n                im.__transformer(box, self, QUAD, quad, resample, fillcolor is None)\n        else:\n            im.__transformer(\n                (0, 0) + size, self, method, data, resample, fillcolor is None\n            )\n\n        return im\n\n    def __transformer(self, box, image, method, data, resample=NEAREST, fill=1):\n        w = box[2] - box[0]\n        h = box[3] - box[1]\n\n        if method == AFFINE:\n            data = data[0:6]\n\n        elif method == EXTENT:\n            # convert extent to an affine transform\n            x0, y0, x1, y1 = data\n            xs = (x1 - x0) / w\n            ys = (y1 - y0) / h\n            method = AFFINE\n            data = (xs, 0, x0, 0, ys, y0)\n\n        elif method == PERSPECTIVE:\n            data = data[0:8]\n\n        elif method == QUAD:\n            # quadrilateral warp.  data specifies the four corners\n            # given as NW, SW, SE, and NE.\n            nw = data[0:2]\n            sw = data[2:4]\n            se = data[4:6]\n            ne = data[6:8]\n            x0, y0 = nw\n            As = 1.0 / w\n            At = 1.0 / h\n            data = (\n                x0,\n                (ne[0] - x0) * As,\n                (sw[0] - x0) * At,\n                (se[0] - sw[0] - ne[0] + x0) * As * At,\n                y0,\n                (ne[1] - y0) * As,\n                (sw[1] - y0) * At,\n                (se[1] - sw[1] - ne[1] + y0) * As * At,\n            )\n\n        else:\n            raise ValueError(\"unknown transformation method\")\n\n        if resample not in (NEAREST, BILINEAR, BICUBIC):\n            if resample in (BOX, HAMMING, LANCZOS):\n                message = {\n                    BOX: \"Image.BOX\",\n                    HAMMING: \"Image.HAMMING\",\n                    LANCZOS: \"Image.LANCZOS/Image.ANTIALIAS\",\n                }[resample] + \" ({}) cannot be used.\".format(resample)\n            else:\n                message = \"Unknown resampling filter ({}).\".format(resample)\n\n            filters = [\n                \"{} ({})\".format(filter[1], filter[0])\n                for filter in (\n                    (NEAREST, \"Image.NEAREST\"),\n                    (BILINEAR, \"Image.BILINEAR\"),\n                    (BICUBIC, \"Image.BICUBIC\"),\n                )\n            ]\n            raise ValueError(\n                message + \" Use \" + \", \".join(filters[:-1]) + \" or \" + filters[-1]\n            )\n\n        image.load()\n\n        self.load()\n\n        if image.mode in (\"1\", \"P\"):\n            resample = NEAREST\n\n        self.im.transform2(box, image.im, method, data, resample, fill)\n\n    def transpose(self, method):\n        \"\"\"\n        Transpose image (flip or rotate in 90 degree steps)\n\n        :param method: One of :py:attr:`PIL.Image.FLIP_LEFT_RIGHT`,\n          :py:attr:`PIL.Image.FLIP_TOP_BOTTOM`, :py:attr:`PIL.Image.ROTATE_90`,\n          :py:attr:`PIL.Image.ROTATE_180`, :py:attr:`PIL.Image.ROTATE_270`,\n          :py:attr:`PIL.Image.TRANSPOSE` or :py:attr:`PIL.Image.TRANSVERSE`.\n        :returns: Returns a flipped or rotated copy of this image.\n        \"\"\"\n\n        self.load()\n        return self._new(self.im.transpose(method))\n\n    def effect_spread(self, distance):\n        \"\"\"\n        Randomly spread pixels in an image.\n\n        :param distance: Distance to spread pixels.\n        \"\"\"\n        self.load()\n        return self._new(self.im.effect_spread(distance))\n\n    def toqimage(self):\n        \"\"\"Returns a QImage copy of this image\"\"\"\n        from . import ImageQt\n\n        if not ImageQt.qt_is_installed:\n            raise ImportError(\"Qt bindings are not installed\")\n        return ImageQt.toqimage(self)\n\n    def toqpixmap(self):\n        \"\"\"Returns a QPixmap copy of this image\"\"\"\n        from . import ImageQt\n\n        if not ImageQt.qt_is_installed:\n            raise ImportError(\"Qt bindings are not installed\")\n        return ImageQt.toqpixmap(self)\n\n\n# --------------------------------------------------------------------\n# Abstract handlers.\n\n\nclass ImagePointHandler:\n    # used as a mixin by point transforms (for use with im.point)\n    pass\n\n\nclass ImageTransformHandler:\n    # used as a mixin by geometry transforms (for use with im.transform)\n    pass\n\n\n# --------------------------------------------------------------------\n# Factories\n\n#\n# Debugging\n\n\ndef _wedge():\n    \"\"\"Create greyscale wedge (for debugging only)\"\"\"\n\n    return Image()._new(core.wedge(\"L\"))\n\n\ndef _check_size(size):\n    \"\"\"\n    Common check to enforce type and sanity check on size tuples\n\n    :param size: Should be a 2 tuple of (width, height)\n    :returns: True, or raises a ValueError\n    \"\"\"\n\n    if not isinstance(size, (list, tuple)):\n        raise ValueError(\"Size must be a tuple\")\n    if len(size) != 2:\n        raise ValueError(\"Size must be a tuple of length 2\")\n    if size[0] < 0 or size[1] < 0:\n        raise ValueError(\"Width and height must be >= 0\")\n\n    return True\n\n\ndef new(mode, size, color=0):\n    \"\"\"\n    Creates a new image with the given mode and size.\n\n    :param mode: The mode to use for the new image. See:\n       :ref:`concept-modes`.\n    :param size: A 2-tuple, containing (width, height) in pixels.\n    :param color: What color to use for the image.  Default is black.\n       If given, this should be a single integer or floating point value\n       for single-band modes, and a tuple for multi-band modes (one value\n       per band).  When creating RGB images, you can also use color\n       strings as supported by the ImageColor module.  If the color is\n       None, the image is not initialised.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    \"\"\"\n\n    _check_size(size)\n\n    if color is None:\n        # don't initialize\n        return Image()._new(core.new(mode, size))\n\n    if isinstance(color, str):\n        # css3-style specifier\n\n        from . import ImageColor\n\n        color = ImageColor.getcolor(color, mode)\n\n    im = Image()\n    if mode == \"P\" and isinstance(color, (list, tuple)) and len(color) in [3, 4]:\n        # RGB or RGBA value for a P image\n        from . import ImagePalette\n\n        im.palette = ImagePalette.ImagePalette()\n        color = im.palette.getcolor(color)\n    return im._new(core.fill(mode, size, color))\n\n\ndef frombytes(mode, size, data, decoder_name=\"raw\", *args):\n    \"\"\"\n    Creates a copy of an image memory from pixel data in a buffer.\n\n    In its simplest form, this function takes three arguments\n    (mode, size, and unpacked pixel data).\n\n    You can also use any pixel decoder supported by PIL.  For more\n    information on available decoders, see the section\n    :ref:`Writing Your Own File Decoder <file-decoders>`.\n\n    Note that this function decodes pixel data only, not entire images.\n    If you have an entire image in a string, wrap it in a\n    :py:class:`~io.BytesIO` object, and use :py:func:`~PIL.Image.open` to load\n    it.\n\n    :param mode: The image mode. See: :ref:`concept-modes`.\n    :param size: The image size.\n    :param data: A byte buffer containing raw data for the given mode.\n    :param decoder_name: What decoder to use.\n    :param args: Additional parameters for the given decoder.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    \"\"\"\n\n    _check_size(size)\n\n    # may pass tuple instead of argument list\n    if len(args) == 1 and isinstance(args[0], tuple):\n        args = args[0]\n\n    if decoder_name == \"raw\" and args == ():\n        args = mode\n\n    im = new(mode, size)\n    im.frombytes(data, decoder_name, args)\n    return im\n\n\ndef fromstring(*args, **kw):\n    raise NotImplementedError(\n        \"fromstring() has been removed. Please call frombytes() instead.\"\n    )\n\n\ndef frombuffer(mode, size, data, decoder_name=\"raw\", *args):\n    \"\"\"\n    Creates an image memory referencing pixel data in a byte buffer.\n\n    This function is similar to :py:func:`~PIL.Image.frombytes`, but uses data\n    in the byte buffer, where possible.  This means that changes to the\n    original buffer object are reflected in this image).  Not all modes can\n    share memory; supported modes include \"L\", \"RGBX\", \"RGBA\", and \"CMYK\".\n\n    Note that this function decodes pixel data only, not entire images.\n    If you have an entire image file in a string, wrap it in a\n    **BytesIO** object, and use :py:func:`~PIL.Image.open` to load it.\n\n    In the current version, the default parameters used for the \"raw\" decoder\n    differs from that used for :py:func:`~PIL.Image.frombytes`.  This is a\n    bug, and will probably be fixed in a future release.  The current release\n    issues a warning if you do this; to disable the warning, you should provide\n    the full set of parameters.  See below for details.\n\n    :param mode: The image mode. See: :ref:`concept-modes`.\n    :param size: The image size.\n    :param data: A bytes or other buffer object containing raw\n        data for the given mode.\n    :param decoder_name: What decoder to use.\n    :param args: Additional parameters for the given decoder.  For the\n        default encoder (\"raw\"), it's recommended that you provide the\n        full set of parameters::\n\n            frombuffer(mode, size, data, \"raw\", mode, 0, 1)\n\n    :returns: An :py:class:`~PIL.Image.Image` object.\n\n    .. versionadded:: 1.1.4\n    \"\"\"\n\n    _check_size(size)\n\n    # may pass tuple instead of argument list\n    if len(args) == 1 and isinstance(args[0], tuple):\n        args = args[0]\n\n    if decoder_name == \"raw\":\n        if args == ():\n            args = mode, 0, 1\n        if args[0] in _MAPMODES:\n            im = new(mode, (1, 1))\n            im = im._new(core.map_buffer(data, size, decoder_name, 0, args))\n            im.readonly = 1\n            return im\n\n    return frombytes(mode, size, data, decoder_name, args)\n\n\ndef fromarray(obj, mode=None):\n    \"\"\"\n    Creates an image memory from an object exporting the array interface\n    (using the buffer protocol).\n\n    If **obj** is not contiguous, then the tobytes method is called\n    and :py:func:`~PIL.Image.frombuffer` is used.\n\n    If you have an image in NumPy::\n\n      from PIL import Image\n      import numpy as np\n      im = Image.open('hopper.jpg')\n      a = np.asarray(im)\n\n    Then this can be used to convert it to a Pillow image::\n\n      im = Image.fromarray(a)\n\n    :param obj: Object with array interface\n    :param mode: Mode to use (will be determined from type if None)\n      See: :ref:`concept-modes`.\n    :returns: An image object.\n\n    .. versionadded:: 1.1.6\n    \"\"\"\n    arr = obj.__array_interface__\n    shape = arr[\"shape\"]\n    ndim = len(shape)\n    strides = arr.get(\"strides\", None)\n    if mode is None:\n        try:\n            typekey = (1, 1) + shape[2:], arr[\"typestr\"]\n        except KeyError:\n            raise TypeError(\"Cannot handle this data type\")\n        try:\n            mode, rawmode = _fromarray_typemap[typekey]\n        except KeyError:\n            raise TypeError(\"Cannot handle this data type: %s, %s\" % typekey)\n    else:\n        rawmode = mode\n    if mode in [\"1\", \"L\", \"I\", \"P\", \"F\"]:\n        ndmax = 2\n    elif mode == \"RGB\":\n        ndmax = 3\n    else:\n        ndmax = 4\n    if ndim > ndmax:\n        raise ValueError(\"Too many dimensions: %d > %d.\" % (ndim, ndmax))\n\n    size = 1 if ndim == 1 else shape[1], shape[0]\n    if strides is not None:\n        if hasattr(obj, \"tobytes\"):\n            obj = obj.tobytes()\n        else:\n            obj = obj.tostring()\n\n    return frombuffer(mode, size, obj, \"raw\", rawmode, 0, 1)\n\n\ndef fromqimage(im):\n    \"\"\"Creates an image instance from a QImage image\"\"\"\n    from . import ImageQt\n\n    if not ImageQt.qt_is_installed:\n        raise ImportError(\"Qt bindings are not installed\")\n    return ImageQt.fromqimage(im)\n\n\ndef fromqpixmap(im):\n    \"\"\"Creates an image instance from a QPixmap image\"\"\"\n    from . import ImageQt\n\n    if not ImageQt.qt_is_installed:\n        raise ImportError(\"Qt bindings are not installed\")\n    return ImageQt.fromqpixmap(im)\n\n\n_fromarray_typemap = {\n    # (shape, typestr) => mode, rawmode\n    # first two members of shape are set to one\n    ((1, 1), \"|b1\"): (\"1\", \"1;8\"),\n    ((1, 1), \"|u1\"): (\"L\", \"L\"),\n    ((1, 1), \"|i1\"): (\"I\", \"I;8\"),\n    ((1, 1), \"<u2\"): (\"I\", \"I;16\"),\n    ((1, 1), \">u2\"): (\"I\", \"I;16B\"),\n    ((1, 1), \"<i2\"): (\"I\", \"I;16S\"),\n    ((1, 1), \">i2\"): (\"I\", \"I;16BS\"),\n    ((1, 1), \"<u4\"): (\"I\", \"I;32\"),\n    ((1, 1), \">u4\"): (\"I\", \"I;32B\"),\n    ((1, 1), \"<i4\"): (\"I\", \"I;32S\"),\n    ((1, 1), \">i4\"): (\"I\", \"I;32BS\"),\n    ((1, 1), \"<f4\"): (\"F\", \"F;32F\"),\n    ((1, 1), \">f4\"): (\"F\", \"F;32BF\"),\n    ((1, 1), \"<f8\"): (\"F\", \"F;64F\"),\n    ((1, 1), \">f8\"): (\"F\", \"F;64BF\"),\n    ((1, 1, 2), \"|u1\"): (\"LA\", \"LA\"),\n    ((1, 1, 3), \"|u1\"): (\"RGB\", \"RGB\"),\n    ((1, 1, 4), \"|u1\"): (\"RGBA\", \"RGBA\"),\n}\n\n# shortcuts\n_fromarray_typemap[((1, 1), _ENDIAN + \"i4\")] = (\"I\", \"I\")\n_fromarray_typemap[((1, 1), _ENDIAN + \"f4\")] = (\"F\", \"F\")\n\n\ndef _decompression_bomb_check(size):\n    if MAX_IMAGE_PIXELS is None:\n        return\n\n    pixels = size[0] * size[1]\n\n    if pixels > 2 * MAX_IMAGE_PIXELS:\n        raise DecompressionBombError(\n            \"Image size (%d pixels) exceeds limit of %d pixels, \"\n            \"could be decompression bomb DOS attack.\" % (pixels, 2 * MAX_IMAGE_PIXELS)\n        )\n\n    if pixels > MAX_IMAGE_PIXELS:\n        warnings.warn(\n            \"Image size (%d pixels) exceeds limit of %d pixels, \"\n            \"could be decompression bomb DOS attack.\" % (pixels, MAX_IMAGE_PIXELS),\n            DecompressionBombWarning,\n        )\n\n\ndef open(fp, mode=\"r\"):\n    \"\"\"\n    Opens and identifies the given image file.\n\n    This is a lazy operation; this function identifies the file, but\n    the file remains open and the actual image data is not read from\n    the file until you try to process the data (or call the\n    :py:meth:`~PIL.Image.Image.load` method).  See\n    :py:func:`~PIL.Image.new`. See :ref:`file-handling`.\n\n    :param fp: A filename (string), pathlib.Path object or a file object.\n       The file object must implement :py:meth:`~file.read`,\n       :py:meth:`~file.seek`, and :py:meth:`~file.tell` methods,\n       and be opened in binary mode.\n    :param mode: The mode.  If given, this argument must be \"r\".\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    :exception FileNotFoundError: If the file cannot be found.\n    :exception PIL.UnidentifiedImageError: If the image cannot be opened and\n       identified.\n    :exception ValueError: If the ``mode`` is not \"r\", or if a ``StringIO``\n       instance is used for ``fp``.\n    \"\"\"\n\n    if mode != \"r\":\n        raise ValueError(\"bad mode %r\" % mode)\n    elif isinstance(fp, io.StringIO):\n        raise ValueError(\n            \"StringIO cannot be used to open an image. \"\n            \"Binary data must be used instead.\"\n        )\n\n    exclusive_fp = False\n    filename = \"\"\n    if isinstance(fp, Path):\n        filename = str(fp.resolve())\n    elif isPath(fp):\n        filename = fp\n\n    if filename:\n        fp = builtins.open(filename, \"rb\")\n        exclusive_fp = True\n\n    try:\n        fp.seek(0)\n    except (AttributeError, io.UnsupportedOperation):\n        fp = io.BytesIO(fp.read())\n        exclusive_fp = True\n\n    prefix = fp.read(16)\n\n    preinit()\n\n    accept_warnings = []\n\n    def _open_core(fp, filename, prefix):\n        for i in ID:\n            try:\n                factory, accept = OPEN[i]\n                result = not accept or accept(prefix)\n                if type(result) in [str, bytes]:\n                    accept_warnings.append(result)\n                elif result:\n                    fp.seek(0)\n                    im = factory(fp, filename)\n                    _decompression_bomb_check(im.size)\n                    return im\n            except (SyntaxError, IndexError, TypeError, struct.error):\n                # Leave disabled by default, spams the logs with image\n                # opening failures that are entirely expected.\n                # logger.debug(\"\", exc_info=True)\n                continue\n            except BaseException:\n                if exclusive_fp:\n                    fp.close()\n                raise\n        return None\n\n    im = _open_core(fp, filename, prefix)\n\n    if im is None:\n        if init():\n            im = _open_core(fp, filename, prefix)\n\n    if im:\n        im._exclusive_fp = exclusive_fp\n        return im\n\n    if exclusive_fp:\n        fp.close()\n    for message in accept_warnings:\n        warnings.warn(message)\n    raise UnidentifiedImageError(\n        \"cannot identify image file %r\" % (filename if filename else fp)\n    )\n\n\n#\n# Image processing.\n\n\ndef alpha_composite(im1, im2):\n    \"\"\"\n    Alpha composite im2 over im1.\n\n    :param im1: The first image. Must have mode RGBA.\n    :param im2: The second image.  Must have mode RGBA, and the same size as\n       the first image.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    \"\"\"\n\n    im1.load()\n    im2.load()\n    return im1._new(core.alpha_composite(im1.im, im2.im))\n\n\ndef blend(im1, im2, alpha):\n    \"\"\"\n    Creates a new image by interpolating between two input images, using\n    a constant alpha.::\n\n        out = image1 * (1.0 - alpha) + image2 * alpha\n\n    :param im1: The first image.\n    :param im2: The second image.  Must have the same mode and size as\n       the first image.\n    :param alpha: The interpolation alpha factor.  If alpha is 0.0, a\n       copy of the first image is returned. If alpha is 1.0, a copy of\n       the second image is returned. There are no restrictions on the\n       alpha value. If necessary, the result is clipped to fit into\n       the allowed output range.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    \"\"\"\n\n    im1.load()\n    im2.load()\n    return im1._new(core.blend(im1.im, im2.im, alpha))\n\n\ndef composite(image1, image2, mask):\n    \"\"\"\n    Create composite image by blending images using a transparency mask.\n\n    :param image1: The first image.\n    :param image2: The second image.  Must have the same mode and\n       size as the first image.\n    :param mask: A mask image.  This image can have mode\n       \"1\", \"L\", or \"RGBA\", and must have the same size as the\n       other two images.\n    \"\"\"\n\n    image = image2.copy()\n    image.paste(image1, None, mask)\n    return image\n\n\ndef eval(image, *args):\n    \"\"\"\n    Applies the function (which should take one argument) to each pixel\n    in the given image. If the image has more than one band, the same\n    function is applied to each band. Note that the function is\n    evaluated once for each possible pixel value, so you cannot use\n    random components or other generators.\n\n    :param image: The input image.\n    :param function: A function object, taking one integer argument.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    \"\"\"\n\n    return image.point(args[0])\n\n\ndef merge(mode, bands):\n    \"\"\"\n    Merge a set of single band images into a new multiband image.\n\n    :param mode: The mode to use for the output image. See:\n        :ref:`concept-modes`.\n    :param bands: A sequence containing one single-band image for\n        each band in the output image.  All bands must have the\n        same size.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    \"\"\"\n\n    if getmodebands(mode) != len(bands) or \"*\" in mode:\n        raise ValueError(\"wrong number of bands\")\n    for band in bands[1:]:\n        if band.mode != getmodetype(mode):\n            raise ValueError(\"mode mismatch\")\n        if band.size != bands[0].size:\n            raise ValueError(\"size mismatch\")\n    for band in bands:\n        band.load()\n    return bands[0]._new(core.merge(mode, *[b.im for b in bands]))\n\n\n# --------------------------------------------------------------------\n# Plugin registry\n\n\ndef register_open(id, factory, accept=None):\n    \"\"\"\n    Register an image file plugin.  This function should not be used\n    in application code.\n\n    :param id: An image format identifier.\n    :param factory: An image file factory method.\n    :param accept: An optional function that can be used to quickly\n       reject images having another format.\n    \"\"\"\n    id = id.upper()\n    ID.append(id)\n    OPEN[id] = factory, accept\n\n\ndef register_mime(id, mimetype):\n    \"\"\"\n    Registers an image MIME type.  This function should not be used\n    in application code.\n\n    :param id: An image format identifier.\n    :param mimetype: The image MIME type for this format.\n    \"\"\"\n    MIME[id.upper()] = mimetype\n\n\ndef register_save(id, driver):\n    \"\"\"\n    Registers an image save function.  This function should not be\n    used in application code.\n\n    :param id: An image format identifier.\n    :param driver: A function to save images in this format.\n    \"\"\"\n    SAVE[id.upper()] = driver\n\n\ndef register_save_all(id, driver):\n    \"\"\"\n    Registers an image function to save all the frames\n    of a multiframe format.  This function should not be\n    used in application code.\n\n    :param id: An image format identifier.\n    :param driver: A function to save images in this format.\n    \"\"\"\n    SAVE_ALL[id.upper()] = driver\n\n\ndef register_extension(id, extension):\n    \"\"\"\n    Registers an image extension.  This function should not be\n    used in application code.\n\n    :param id: An image format identifier.\n    :param extension: An extension used for this format.\n    \"\"\"\n    EXTENSION[extension.lower()] = id.upper()\n\n\ndef register_extensions(id, extensions):\n    \"\"\"\n    Registers image extensions.  This function should not be\n    used in application code.\n\n    :param id: An image format identifier.\n    :param extensions: A list of extensions used for this format.\n    \"\"\"\n    for extension in extensions:\n        register_extension(id, extension)\n\n\ndef registered_extensions():\n    \"\"\"\n    Returns a dictionary containing all file extensions belonging\n    to registered plugins\n    \"\"\"\n    if not EXTENSION:\n        init()\n    return EXTENSION\n\n\ndef register_decoder(name, decoder):\n    \"\"\"\n    Registers an image decoder.  This function should not be\n    used in application code.\n\n    :param name: The name of the decoder\n    :param decoder: A callable(mode, args) that returns an\n                    ImageFile.PyDecoder object\n\n    .. versionadded:: 4.1.0\n    \"\"\"\n    DECODERS[name] = decoder\n\n\ndef register_encoder(name, encoder):\n    \"\"\"\n    Registers an image encoder.  This function should not be\n    used in application code.\n\n    :param name: The name of the encoder\n    :param encoder: A callable(mode, args) that returns an\n                    ImageFile.PyEncoder object\n\n    .. versionadded:: 4.1.0\n    \"\"\"\n    ENCODERS[name] = encoder\n\n\n# --------------------------------------------------------------------\n# Simple display support.  User code may override this.\n\n\ndef _show(image, **options):\n    # override me, as necessary\n    _showxv(image, **options)\n\n\ndef _showxv(image, title=None, **options):\n    from . import ImageShow\n\n    ImageShow.show(image, title, **options)\n\n\n# --------------------------------------------------------------------\n# Effects\n\n\ndef effect_mandelbrot(size, extent, quality):\n    \"\"\"\n    Generate a Mandelbrot set covering the given extent.\n\n    :param size: The requested size in pixels, as a 2-tuple:\n       (width, height).\n    :param extent: The extent to cover, as a 4-tuple:\n       (x0, y0, x1, y2).\n    :param quality: Quality.\n    \"\"\"\n    return Image()._new(core.effect_mandelbrot(size, extent, quality))\n\n\ndef effect_noise(size, sigma):\n    \"\"\"\n    Generate Gaussian noise centered around 128.\n\n    :param size: The requested size in pixels, as a 2-tuple:\n       (width, height).\n    :param sigma: Standard deviation of noise.\n    \"\"\"\n    return Image()._new(core.effect_noise(size, sigma))\n\n\ndef linear_gradient(mode):\n    \"\"\"\n    Generate 256x256 linear gradient from black to white, top to bottom.\n\n    :param mode: Input mode.\n    \"\"\"\n    return Image()._new(core.linear_gradient(mode))\n\n\ndef radial_gradient(mode):\n    \"\"\"\n    Generate 256x256 radial gradient from black to white, centre to edge.\n\n    :param mode: Input mode.\n    \"\"\"\n    return Image()._new(core.radial_gradient(mode))\n\n\n# --------------------------------------------------------------------\n# Resources\n\n\ndef _apply_env_variables(env=None):\n    if env is None:\n        env = os.environ\n\n    for var_name, setter in [\n        (\"PILLOW_ALIGNMENT\", core.set_alignment),\n        (\"PILLOW_BLOCK_SIZE\", core.set_block_size),\n        (\"PILLOW_BLOCKS_MAX\", core.set_blocks_max),\n    ]:\n        if var_name not in env:\n            continue\n\n        var = env[var_name].lower()\n\n        units = 1\n        for postfix, mul in [(\"k\", 1024), (\"m\", 1024 * 1024)]:\n            if var.endswith(postfix):\n                units = mul\n                var = var[: -len(postfix)]\n\n        try:\n            var = int(var) * units\n        except ValueError:\n            warnings.warn(\"{} is not int\".format(var_name))\n            continue\n\n        try:\n            setter(var)\n        except ValueError as e:\n            warnings.warn(\"{}: {}\".format(var_name, e))\n\n\n_apply_env_variables()\natexit.register(core.clear_cache)\n\n\nclass Exif(MutableMapping):\n    endian = \"<\"\n\n    def __init__(self):\n        self._data = {}\n        self._ifds = {}\n        self._info = None\n        self._loaded_exif = None\n\n    def _fixup(self, value):\n        try:\n            if len(value) == 1 and isinstance(value, tuple):\n                return value[0]\n        except Exception:\n            pass\n        return value\n\n    def _fixup_dict(self, src_dict):\n        # Helper function for _getexif()\n        # returns a dict with any single item tuples/lists as individual values\n        return {k: self._fixup(v) for k, v in src_dict.items()}\n\n    def _get_ifd_dict(self, tag):\n        try:\n            # an offset pointer to the location of the nested embedded IFD.\n            # It should be a long, but may be corrupted.\n            self.fp.seek(self[tag])\n        except (KeyError, TypeError):\n            pass\n        else:\n            from . import TiffImagePlugin\n\n            info = TiffImagePlugin.ImageFileDirectory_v2(self.head)\n            info.load(self.fp)\n            return self._fixup_dict(info)\n\n    def load(self, data):\n        # Extract EXIF information.  This is highly experimental,\n        # and is likely to be replaced with something better in a future\n        # version.\n\n        # The EXIF record consists of a TIFF file embedded in a JPEG\n        # application marker (!).\n        if data == self._loaded_exif:\n            return\n        self._loaded_exif = data\n        self._data.clear()\n        self._ifds.clear()\n        self._info = None\n        if not data:\n            return\n\n        if data.startswith(b\"Exif\\x00\\x00\"):\n            data = data[6:]\n        self.fp = io.BytesIO(data)\n        self.head = self.fp.read(8)\n        # process dictionary\n        from . import TiffImagePlugin\n\n        self._info = TiffImagePlugin.ImageFileDirectory_v2(self.head)\n        self.endian = self._info._endian\n        self.fp.seek(self._info.next)\n        self._info.load(self.fp)\n\n        # get EXIF extension\n        ifd = self._get_ifd_dict(0x8769)\n        if ifd:\n            self._data.update(ifd)\n            self._ifds[0x8769] = ifd\n\n    def tobytes(self, offset=8):\n        from . import TiffImagePlugin\n\n        if self.endian == \"<\":\n            head = b\"II\\x2A\\x00\\x08\\x00\\x00\\x00\"\n        else:\n            head = b\"MM\\x00\\x2A\\x00\\x00\\x00\\x08\"\n        ifd = TiffImagePlugin.ImageFileDirectory_v2(ifh=head)\n        for tag, value in self.items():\n            ifd[tag] = value\n        return b\"Exif\\x00\\x00\" + head + ifd.tobytes(offset)\n\n    def get_ifd(self, tag):\n        if tag not in self._ifds and tag in self:\n            if tag in [0x8825, 0xA005]:\n                # gpsinfo, interop\n                self._ifds[tag] = self._get_ifd_dict(tag)\n            elif tag == 0x927C:  # makernote\n                from .TiffImagePlugin import ImageFileDirectory_v2\n\n                if self[0x927C][:8] == b\"FUJIFILM\":\n                    exif_data = self[0x927C]\n                    ifd_offset = i32le(exif_data[8:12])\n                    ifd_data = exif_data[ifd_offset:]\n\n                    makernote = {}\n                    for i in range(0, struct.unpack(\"<H\", ifd_data[:2])[0]):\n                        ifd_tag, typ, count, data = struct.unpack(\n                            \"<HHL4s\", ifd_data[i * 12 + 2 : (i + 1) * 12 + 2]\n                        )\n                        try:\n                            unit_size, handler = ImageFileDirectory_v2._load_dispatch[\n                                typ\n                            ]\n                        except KeyError:\n                            continue\n                        size = count * unit_size\n                        if size > 4:\n                            (offset,) = struct.unpack(\"<L\", data)\n                            data = ifd_data[offset - 12 : offset + size - 12]\n                        else:\n                            data = data[:size]\n\n                        if len(data) != size:\n                            warnings.warn(\n                                \"Possibly corrupt EXIF MakerNote data.  \"\n                                \"Expecting to read %d bytes but only got %d.\"\n                                \" Skipping tag %s\" % (size, len(data), ifd_tag)\n                            )\n                            continue\n\n                        if not data:\n                            continue\n\n                        makernote[ifd_tag] = handler(\n                            ImageFileDirectory_v2(), data, False\n                        )\n                    self._ifds[0x927C] = dict(self._fixup_dict(makernote))\n                elif self.get(0x010F) == \"Nintendo\":\n                    ifd_data = self[0x927C]\n\n                    makernote = {}\n                    for i in range(0, struct.unpack(\">H\", ifd_data[:2])[0]):\n                        ifd_tag, typ, count, data = struct.unpack(\n                            \">HHL4s\", ifd_data[i * 12 + 2 : (i + 1) * 12 + 2]\n                        )\n                        if ifd_tag == 0x1101:\n                            # CameraInfo\n                            (offset,) = struct.unpack(\">L\", data)\n                            self.fp.seek(offset)\n\n                            camerainfo = {\"ModelID\": self.fp.read(4)}\n\n                            self.fp.read(4)\n                            # Seconds since 2000\n                            camerainfo[\"TimeStamp\"] = i32le(self.fp.read(12))\n\n                            self.fp.read(4)\n                            camerainfo[\"InternalSerialNumber\"] = self.fp.read(4)\n\n                            self.fp.read(12)\n                            parallax = self.fp.read(4)\n                            handler = ImageFileDirectory_v2._load_dispatch[\n                                TiffTags.FLOAT\n                            ][1]\n                            camerainfo[\"Parallax\"] = handler(\n                                ImageFileDirectory_v2(), parallax, False\n                            )\n\n                            self.fp.read(4)\n                            camerainfo[\"Category\"] = self.fp.read(2)\n\n                            makernote = {0x1101: dict(self._fixup_dict(camerainfo))}\n                    self._ifds[0x927C] = makernote\n        return self._ifds.get(tag, {})\n\n    def __str__(self):\n        if self._info is not None:\n            # Load all keys into self._data\n            for tag in self._info.keys():\n                self[tag]\n\n        return str(self._data)\n\n    def __len__(self):\n        keys = set(self._data)\n        if self._info is not None:\n            keys.update(self._info)\n        return len(keys)\n\n    def __getitem__(self, tag):\n        if self._info is not None and tag not in self._data and tag in self._info:\n            self._data[tag] = self._fixup(self._info[tag])\n            if tag == 0x8825:\n                self._data[tag] = self.get_ifd(tag)\n            del self._info[tag]\n        return self._data[tag]\n\n    def __contains__(self, tag):\n        return tag in self._data or (self._info is not None and tag in self._info)\n\n    def __setitem__(self, tag, value):\n        if self._info is not None and tag in self._info:\n            del self._info[tag]\n        self._data[tag] = value\n\n    def __delitem__(self, tag):\n        if self._info is not None and tag in self._info:\n            del self._info[tag]\n        del self._data[tag]\n\n    def __iter__(self):\n        keys = set(self._data)\n        if self._info is not None:\n            keys.update(self._info)\n        return iter(keys)\n",
            "header": {
                "file": {
                    "path": "src/PIL/Image.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "038829213",
                "new_commit_hash": "bb81750e6",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/src/PIL/Image.py"
            },
            "plus_file": {
                "path": "b/src/PIL/Image.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 3248,
                            "length": 7
                        },
                        "new_range": {
                            "start": 3248,
                            "length": 7
                        },
                        "section": "class Exif(MutableMapping):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def _fixup(self, value):",
                                "type": "context"
                            },
                            {
                                "content": "        try:",
                                "type": "context"
                            },
                            {
                                "content": "            if len(value) == 1 and not isinstance(value, dict):",
                                "type": "deleted"
                            },
                            {
                                "content": "            if len(value) == 1 and isinstance(value, tuple):",
                                "type": "added"
                            },
                            {
                                "content": "                return value[0]",
                                "type": "context"
                            },
                            {
                                "content": "        except Exception:",
                                "type": "context"
                            },
                            {
                                "content": "            pass",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "src/PIL/Image.py",
                            "type": "class",
                            "name": "Exif",
                            "content": "class Exif(MutableMapping):\n    endian = \"<\"\n\n    def __init__(self):\n        self._data = {}\n        self._ifds = {}\n        self._info = None\n        self._loaded_exif = None\n\n    def _fixup(self, value):\n        try:\n            if len(value) == 1 and not isinstance(value, dict):\n                return value[0]\n        except Exception:\n            pass\n        return value\n\n    def _fixup_dict(self, src_dict):\n        # Helper function for _getexif()\n        # returns a dict with any single item tuples/lists as individual values\n        return {k: self._fixup(v) for k, v in src_dict.items()}\n\n    def _get_ifd_dict(self, tag):\n        try:\n            # an offset pointer to the location of the nested embedded IFD.\n            # It should be a long, but may be corrupted.\n            self.fp.seek(self[tag])\n        except (KeyError, TypeError):\n            pass\n        else:\n            from . import TiffImagePlugin\n\n            info = TiffImagePlugin.ImageFileDirectory_v1(self.head)\n            info.load(self.fp)\n            return self._fixup_dict(info)\n\n    def load(self, data):\n        # Extract EXIF information.  This is highly experimental,\n        # and is likely to be replaced with something better in a future\n        # version.\n\n        # The EXIF record consists of a TIFF file embedded in a JPEG\n        # application marker (!).\n        if data == self._loaded_exif:\n            return\n        self._loaded_exif = data\n        self._data.clear()\n        self._ifds.clear()\n        self._info = None\n        if not data:\n            return\n\n        if data.startswith(b\"Exif\\x00\\x00\"):\n            data = data[6:]\n        self.fp = io.BytesIO(data)\n        self.head = self.fp.read(8)\n        # process dictionary\n        from . import TiffImagePlugin\n\n        self._info = TiffImagePlugin.ImageFileDirectory_v1(self.head)\n        self.endian = self._info._endian\n        self.fp.seek(self._info.next)\n        self._info.load(self.fp)\n\n        # get EXIF extension\n        ifd = self._get_ifd_dict(0x8769)\n        if ifd:\n            self._data.update(ifd)\n            self._ifds[0x8769] = ifd\n\n    def tobytes(self, offset=8):\n        from . import TiffImagePlugin\n\n        if self.endian == \"<\":\n            head = b\"II\\x2A\\x00\\x08\\x00\\x00\\x00\"\n        else:\n            head = b\"MM\\x00\\x2A\\x00\\x00\\x00\\x08\"\n        ifd = TiffImagePlugin.ImageFileDirectory_v2(ifh=head)\n        for tag, value in self.items():\n            ifd[tag] = value\n        return b\"Exif\\x00\\x00\" + head + ifd.tobytes(offset)\n\n    def get_ifd(self, tag):\n        if tag not in self._ifds and tag in self:\n            if tag in [0x8825, 0xA005]:\n                # gpsinfo, interop\n                self._ifds[tag] = self._get_ifd_dict(tag)\n            elif tag == 0x927C:  # makernote\n                from .TiffImagePlugin import ImageFileDirectory_v2\n\n                if self[0x927C][:8] == b\"FUJIFILM\":\n                    exif_data = self[0x927C]\n                    ifd_offset = i32le(exif_data[8:12])\n                    ifd_data = exif_data[ifd_offset:]\n\n                    makernote = {}\n                    for i in range(0, struct.unpack(\"<H\", ifd_data[:2])[0]):\n                        ifd_tag, typ, count, data = struct.unpack(\n                            \"<HHL4s\", ifd_data[i * 12 + 2 : (i + 1) * 12 + 2]\n                        )\n                        try:\n                            unit_size, handler = ImageFileDirectory_v2._load_dispatch[\n                                typ\n                            ]\n                        except KeyError:\n                            continue\n                        size = count * unit_size\n                        if size > 4:\n                            (offset,) = struct.unpack(\"<L\", data)\n                            data = ifd_data[offset - 12 : offset + size - 12]\n                        else:\n                            data = data[:size]\n\n                        if len(data) != size:\n                            warnings.warn(\n                                \"Possibly corrupt EXIF MakerNote data.  \"\n                                \"Expecting to read %d bytes but only got %d.\"\n                                \" Skipping tag %s\" % (size, len(data), ifd_tag)\n                            )\n                            continue\n\n                        if not data:\n                            continue\n\n                        makernote[ifd_tag] = handler(\n                            ImageFileDirectory_v2(), data, False\n                        )\n                    self._ifds[0x927C] = dict(self._fixup_dict(makernote))\n                elif self.get(0x010F) == \"Nintendo\":\n                    ifd_data = self[0x927C]\n\n                    makernote = {}\n                    for i in range(0, struct.unpack(\">H\", ifd_data[:2])[0]):\n                        ifd_tag, typ, count, data = struct.unpack(\n                            \">HHL4s\", ifd_data[i * 12 + 2 : (i + 1) * 12 + 2]\n                        )\n                        if ifd_tag == 0x1101:\n                            # CameraInfo\n                            (offset,) = struct.unpack(\">L\", data)\n                            self.fp.seek(offset)\n\n                            camerainfo = {\"ModelID\": self.fp.read(4)}\n\n                            self.fp.read(4)\n                            # Seconds since 2000\n                            camerainfo[\"TimeStamp\"] = i32le(self.fp.read(12))\n\n                            self.fp.read(4)\n                            camerainfo[\"InternalSerialNumber\"] = self.fp.read(4)\n\n                            self.fp.read(12)\n                            parallax = self.fp.read(4)\n                            handler = ImageFileDirectory_v2._load_dispatch[\n                                TiffTags.FLOAT\n                            ][1]\n                            camerainfo[\"Parallax\"] = handler(\n                                ImageFileDirectory_v2(), parallax, False\n                            )\n\n                            self.fp.read(4)\n                            camerainfo[\"Category\"] = self.fp.read(2)\n\n                            makernote = {0x1101: dict(self._fixup_dict(camerainfo))}\n                    self._ifds[0x927C] = makernote\n        return self._ifds.get(tag, {})\n\n    def __str__(self):\n        if self._info is not None:\n            # Load all keys into self._data\n            for tag in self._info.keys():\n                self[tag]\n\n        return str(self._data)\n\n    def __len__(self):\n        keys = set(self._data)\n        if self._info is not None:\n            keys.update(self._info)\n        return len(keys)\n\n    def __getitem__(self, tag):\n        if self._info is not None and tag not in self._data and tag in self._info:\n            self._data[tag] = self._fixup(self._info[tag])\n            if tag == 0x8825:\n                self._data[tag] = self.get_ifd(tag)\n            del self._info[tag]\n        return self._data[tag]\n\n    def __contains__(self, tag):\n        return tag in self._data or (self._info is not None and tag in self._info)\n\n    def __setitem__(self, tag, value):\n        if self._info is not None and tag in self._info:\n            del self._info[tag]\n        self._data[tag] = value\n\n    def __delitem__(self, tag):\n        if self._info is not None and tag in self._info:\n            del self._info[tag]\n        del self._data[tag]\n\n    def __iter__(self):\n        keys = set(self._data)\n        if self._info is not None:\n            keys.update(self._info)\n        return iter(keys)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 3240,
                            "end_lineno": 3445,
                            "parent": null
                        },
                        {
                            "file_name": "src/PIL/Image.py",
                            "type": "method",
                            "name": "Exif._fixup",
                            "content": "class Exif(MutableMapping):\n    endian = \"<\"\n\n    def __init__(self):\n        self._data = {}\n        self._ifds = {}\n        self._info = None\n        self._loaded_exif = None\n\n    def _fixup(self, value):\n        try:\n            if len(value) == 1 and not isinstance(value, dict):\n                return value[0]\n        except Exception:\n            pass\n        return value\n\n    def _fixup_dict(self, src_dict):\n        # Helper function for _getexif()\n        # returns a dict with any single item tuples/lists as individual values\n        return {k: self._fixup(v) for k, v in src_dict.items()}\n\n    def _get_ifd_dict(self, tag):\n        try:\n            # an offset pointer to the location of the nested embedded IFD.\n            # It should be a long, but may be corrupted.\n            self.fp.seek(self[tag])\n        except (KeyError, TypeError):\n            pass\n        else:\n            from . import TiffImagePlugin\n\n            info = TiffImagePlugin.ImageFileDirectory_v1(self.head)\n            info.load(self.fp)\n            return self._fixup_dict(info)\n\n    def load(self, data):\n        # Extract EXIF information.  This is highly experimental,\n        # and is likely to be replaced with something better in a future\n        # version.\n\n        # The EXIF record consists of a TIFF file embedded in a JPEG\n        # application marker (!).\n        if data == self._loaded_exif:\n            return\n        self._loaded_exif = data\n        self._data.clear()\n        self._ifds.clear()\n        self._info = None\n        if not data:\n            return\n\n        if data.startswith(b\"Exif\\x00\\x00\"):\n            data = data[6:]\n        self.fp = io.BytesIO(data)\n        self.head = self.fp.read(8)\n        # process dictionary\n        from . import TiffImagePlugin\n\n        self._info = TiffImagePlugin.ImageFileDirectory_v1(self.head)\n        self.endian = self._info._endian\n        self.fp.seek(self._info.next)\n        self._info.load(self.fp)\n\n        # get EXIF extension\n        ifd = self._get_ifd_dict(0x8769)\n        if ifd:\n            self._data.update(ifd)\n            self._ifds[0x8769] = ifd\n\n    def tobytes(self, offset=8):\n        from . import TiffImagePlugin\n\n        if self.endian == \"<\":\n            head = b\"II\\x2A\\x00\\x08\\x00\\x00\\x00\"\n        else:\n            head = b\"MM\\x00\\x2A\\x00\\x00\\x00\\x08\"\n        ifd = TiffImagePlugin.ImageFileDirectory_v2(ifh=head)\n        for tag, value in self.items():\n            ifd[tag] = value\n        return b\"Exif\\x00\\x00\" + head + ifd.tobytes(offset)\n\n    def get_ifd(self, tag):\n        if tag not in self._ifds and tag in self:\n            if tag in [0x8825, 0xA005]:\n                # gpsinfo, interop\n                self._ifds[tag] = self._get_ifd_dict(tag)\n            elif tag == 0x927C:  # makernote\n                from .TiffImagePlugin import ImageFileDirectory_v2\n\n                if self[0x927C][:8] == b\"FUJIFILM\":\n                    exif_data = self[0x927C]\n                    ifd_offset = i32le(exif_data[8:12])\n                    ifd_data = exif_data[ifd_offset:]\n\n                    makernote = {}\n                    for i in range(0, struct.unpack(\"<H\", ifd_data[:2])[0]):\n                        ifd_tag, typ, count, data = struct.unpack(\n                            \"<HHL4s\", ifd_data[i * 12 + 2 : (i + 1) * 12 + 2]\n                        )\n                        try:\n                            unit_size, handler = ImageFileDirectory_v2._load_dispatch[\n                                typ\n                            ]\n                        except KeyError:\n                            continue\n                        size = count * unit_size\n                        if size > 4:\n                            (offset,) = struct.unpack(\"<L\", data)\n                            data = ifd_data[offset - 12 : offset + size - 12]\n                        else:\n                            data = data[:size]\n\n                        if len(data) != size:\n                            warnings.warn(\n                                \"Possibly corrupt EXIF MakerNote data.  \"\n                                \"Expecting to read %d bytes but only got %d.\"\n                                \" Skipping tag %s\" % (size, len(data), ifd_tag)\n                            )\n                            continue\n\n                        if not data:\n                            continue\n\n                        makernote[ifd_tag] = handler(\n                            ImageFileDirectory_v2(), data, False\n                        )\n                    self._ifds[0x927C] = dict(self._fixup_dict(makernote))\n                elif self.get(0x010F) == \"Nintendo\":\n                    ifd_data = self[0x927C]\n\n                    makernote = {}\n                    for i in range(0, struct.unpack(\">H\", ifd_data[:2])[0]):\n                        ifd_tag, typ, count, data = struct.unpack(\n                            \">HHL4s\", ifd_data[i * 12 + 2 : (i + 1) * 12 + 2]\n                        )\n                        if ifd_tag == 0x1101:\n                            # CameraInfo\n                            (offset,) = struct.unpack(\">L\", data)\n                            self.fp.seek(offset)\n\n                            camerainfo = {\"ModelID\": self.fp.read(4)}\n\n                            self.fp.read(4)\n                            # Seconds since 2000\n                            camerainfo[\"TimeStamp\"] = i32le(self.fp.read(12))\n\n                            self.fp.read(4)\n                            camerainfo[\"InternalSerialNumber\"] = self.fp.read(4)\n\n                            self.fp.read(12)\n                            parallax = self.fp.read(4)\n                            handler = ImageFileDirectory_v2._load_dispatch[\n                                TiffTags.FLOAT\n                            ][1]\n                            camerainfo[\"Parallax\"] = handler(\n                                ImageFileDirectory_v2(), parallax, False\n                            )\n\n                            self.fp.read(4)\n                            camerainfo[\"Category\"] = self.fp.read(2)\n\n                            makernote = {0x1101: dict(self._fixup_dict(camerainfo))}\n                    self._ifds[0x927C] = makernote\n        return self._ifds.get(tag, {})\n\n    def __str__(self):\n        if self._info is not None:\n            # Load all keys into self._data\n            for tag in self._info.keys():\n                self[tag]\n\n        return str(self._data)\n\n    def __len__(self):\n        keys = set(self._data)\n        if self._info is not None:\n            keys.update(self._info)\n        return len(keys)\n\n    def __getitem__(self, tag):\n        if self._info is not None and tag not in self._data and tag in self._info:\n            self._data[tag] = self._fixup(self._info[tag])\n            if tag == 0x8825:\n                self._data[tag] = self.get_ifd(tag)\n            del self._info[tag]\n        return self._data[tag]\n\n    def __contains__(self, tag):\n        return tag in self._data or (self._info is not None and tag in self._info)\n\n    def __setitem__(self, tag, value):\n        if self._info is not None and tag in self._info:\n            del self._info[tag]\n        self._data[tag] = value\n\n    def __delitem__(self, tag):\n        if self._info is not None and tag in self._info:\n            del self._info[tag]\n        del self._data[tag]\n\n    def __iter__(self):\n        keys = set(self._data)\n        if self._info is not None:\n            keys.update(self._info)\n        return iter(keys)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 3249,
                            "end_lineno": 3255,
                            "parent": {
                                "file_name": "src/PIL/Image.py",
                                "type": "class",
                                "name": "Exif",
                                "content": "class Exif(MutableMapping):\n    endian = \"<\"\n\n    def __init__(self):\n        self._data = {}\n        self._ifds = {}\n        self._info = None\n        self._loaded_exif = None\n\n    def _fixup(self, value):\n        try:\n            if len(value) == 1 and not isinstance(value, dict):\n                return value[0]\n        except Exception:\n            pass\n        return value\n\n    def _fixup_dict(self, src_dict):\n        # Helper function for _getexif()\n        # returns a dict with any single item tuples/lists as individual values\n        return {k: self._fixup(v) for k, v in src_dict.items()}\n\n    def _get_ifd_dict(self, tag):\n        try:\n            # an offset pointer to the location of the nested embedded IFD.\n            # It should be a long, but may be corrupted.\n            self.fp.seek(self[tag])\n        except (KeyError, TypeError):\n            pass\n        else:\n            from . import TiffImagePlugin\n\n            info = TiffImagePlugin.ImageFileDirectory_v1(self.head)\n            info.load(self.fp)\n            return self._fixup_dict(info)\n\n    def load(self, data):\n        # Extract EXIF information.  This is highly experimental,\n        # and is likely to be replaced with something better in a future\n        # version.\n\n        # The EXIF record consists of a TIFF file embedded in a JPEG\n        # application marker (!).\n        if data == self._loaded_exif:\n            return\n        self._loaded_exif = data\n        self._data.clear()\n        self._ifds.clear()\n        self._info = None\n        if not data:\n            return\n\n        if data.startswith(b\"Exif\\x00\\x00\"):\n            data = data[6:]\n        self.fp = io.BytesIO(data)\n        self.head = self.fp.read(8)\n        # process dictionary\n        from . import TiffImagePlugin\n\n        self._info = TiffImagePlugin.ImageFileDirectory_v1(self.head)\n        self.endian = self._info._endian\n        self.fp.seek(self._info.next)\n        self._info.load(self.fp)\n\n        # get EXIF extension\n        ifd = self._get_ifd_dict(0x8769)\n        if ifd:\n            self._data.update(ifd)\n            self._ifds[0x8769] = ifd\n\n    def tobytes(self, offset=8):\n        from . import TiffImagePlugin\n\n        if self.endian == \"<\":\n            head = b\"II\\x2A\\x00\\x08\\x00\\x00\\x00\"\n        else:\n            head = b\"MM\\x00\\x2A\\x00\\x00\\x00\\x08\"\n        ifd = TiffImagePlugin.ImageFileDirectory_v2(ifh=head)\n        for tag, value in self.items():\n            ifd[tag] = value\n        return b\"Exif\\x00\\x00\" + head + ifd.tobytes(offset)\n\n    def get_ifd(self, tag):\n        if tag not in self._ifds and tag in self:\n            if tag in [0x8825, 0xA005]:\n                # gpsinfo, interop\n                self._ifds[tag] = self._get_ifd_dict(tag)\n            elif tag == 0x927C:  # makernote\n                from .TiffImagePlugin import ImageFileDirectory_v2\n\n                if self[0x927C][:8] == b\"FUJIFILM\":\n                    exif_data = self[0x927C]\n                    ifd_offset = i32le(exif_data[8:12])\n                    ifd_data = exif_data[ifd_offset:]\n\n                    makernote = {}\n                    for i in range(0, struct.unpack(\"<H\", ifd_data[:2])[0]):\n                        ifd_tag, typ, count, data = struct.unpack(\n                            \"<HHL4s\", ifd_data[i * 12 + 2 : (i + 1) * 12 + 2]\n                        )\n                        try:\n                            unit_size, handler = ImageFileDirectory_v2._load_dispatch[\n                                typ\n                            ]\n                        except KeyError:\n                            continue\n                        size = count * unit_size\n                        if size > 4:\n                            (offset,) = struct.unpack(\"<L\", data)\n                            data = ifd_data[offset - 12 : offset + size - 12]\n                        else:\n                            data = data[:size]\n\n                        if len(data) != size:\n                            warnings.warn(\n                                \"Possibly corrupt EXIF MakerNote data.  \"\n                                \"Expecting to read %d bytes but only got %d.\"\n                                \" Skipping tag %s\" % (size, len(data), ifd_tag)\n                            )\n                            continue\n\n                        if not data:\n                            continue\n\n                        makernote[ifd_tag] = handler(\n                            ImageFileDirectory_v2(), data, False\n                        )\n                    self._ifds[0x927C] = dict(self._fixup_dict(makernote))\n                elif self.get(0x010F) == \"Nintendo\":\n                    ifd_data = self[0x927C]\n\n                    makernote = {}\n                    for i in range(0, struct.unpack(\">H\", ifd_data[:2])[0]):\n                        ifd_tag, typ, count, data = struct.unpack(\n                            \">HHL4s\", ifd_data[i * 12 + 2 : (i + 1) * 12 + 2]\n                        )\n                        if ifd_tag == 0x1101:\n                            # CameraInfo\n                            (offset,) = struct.unpack(\">L\", data)\n                            self.fp.seek(offset)\n\n                            camerainfo = {\"ModelID\": self.fp.read(4)}\n\n                            self.fp.read(4)\n                            # Seconds since 2000\n                            camerainfo[\"TimeStamp\"] = i32le(self.fp.read(12))\n\n                            self.fp.read(4)\n                            camerainfo[\"InternalSerialNumber\"] = self.fp.read(4)\n\n                            self.fp.read(12)\n                            parallax = self.fp.read(4)\n                            handler = ImageFileDirectory_v2._load_dispatch[\n                                TiffTags.FLOAT\n                            ][1]\n                            camerainfo[\"Parallax\"] = handler(\n                                ImageFileDirectory_v2(), parallax, False\n                            )\n\n                            self.fp.read(4)\n                            camerainfo[\"Category\"] = self.fp.read(2)\n\n                            makernote = {0x1101: dict(self._fixup_dict(camerainfo))}\n                    self._ifds[0x927C] = makernote\n        return self._ifds.get(tag, {})\n\n    def __str__(self):\n        if self._info is not None:\n            # Load all keys into self._data\n            for tag in self._info.keys():\n                self[tag]\n\n        return str(self._data)\n\n    def __len__(self):\n        keys = set(self._data)\n        if self._info is not None:\n            keys.update(self._info)\n        return len(keys)\n\n    def __getitem__(self, tag):\n        if self._info is not None and tag not in self._data and tag in self._info:\n            self._data[tag] = self._fixup(self._info[tag])\n            if tag == 0x8825:\n                self._data[tag] = self.get_ifd(tag)\n            del self._info[tag]\n        return self._data[tag]\n\n    def __contains__(self, tag):\n        return tag in self._data or (self._info is not None and tag in self._info)\n\n    def __setitem__(self, tag, value):\n        if self._info is not None and tag in self._info:\n            del self._info[tag]\n        self._data[tag] = value\n\n    def __delitem__(self, tag):\n        if self._info is not None and tag in self._info:\n            del self._info[tag]\n        del self._data[tag]\n\n    def __iter__(self):\n        keys = set(self._data)\n        if self._info is not None:\n            keys.update(self._info)\n        return iter(keys)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 3240,
                                "end_lineno": 3445,
                                "parent": null
                            }
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 3269,
                            "length": 7
                        },
                        "new_range": {
                            "start": 3269,
                            "length": 7
                        },
                        "section": "class Exif(MutableMapping):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        else:",
                                "type": "context"
                            },
                            {
                                "content": "            from . import TiffImagePlugin",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "            info = TiffImagePlugin.ImageFileDirectory_v1(self.head)",
                                "type": "deleted"
                            },
                            {
                                "content": "            info = TiffImagePlugin.ImageFileDirectory_v2(self.head)",
                                "type": "added"
                            },
                            {
                                "content": "            info.load(self.fp)",
                                "type": "context"
                            },
                            {
                                "content": "            return self._fixup_dict(info)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "src/PIL/Image.py",
                            "type": "class",
                            "name": "Exif",
                            "content": "class Exif(MutableMapping):\n    endian = \"<\"\n\n    def __init__(self):\n        self._data = {}\n        self._ifds = {}\n        self._info = None\n        self._loaded_exif = None\n\n    def _fixup(self, value):\n        try:\n            if len(value) == 1 and not isinstance(value, dict):\n                return value[0]\n        except Exception:\n            pass\n        return value\n\n    def _fixup_dict(self, src_dict):\n        # Helper function for _getexif()\n        # returns a dict with any single item tuples/lists as individual values\n        return {k: self._fixup(v) for k, v in src_dict.items()}\n\n    def _get_ifd_dict(self, tag):\n        try:\n            # an offset pointer to the location of the nested embedded IFD.\n            # It should be a long, but may be corrupted.\n            self.fp.seek(self[tag])\n        except (KeyError, TypeError):\n            pass\n        else:\n            from . import TiffImagePlugin\n\n            info = TiffImagePlugin.ImageFileDirectory_v1(self.head)\n            info.load(self.fp)\n            return self._fixup_dict(info)\n\n    def load(self, data):\n        # Extract EXIF information.  This is highly experimental,\n        # and is likely to be replaced with something better in a future\n        # version.\n\n        # The EXIF record consists of a TIFF file embedded in a JPEG\n        # application marker (!).\n        if data == self._loaded_exif:\n            return\n        self._loaded_exif = data\n        self._data.clear()\n        self._ifds.clear()\n        self._info = None\n        if not data:\n            return\n\n        if data.startswith(b\"Exif\\x00\\x00\"):\n            data = data[6:]\n        self.fp = io.BytesIO(data)\n        self.head = self.fp.read(8)\n        # process dictionary\n        from . import TiffImagePlugin\n\n        self._info = TiffImagePlugin.ImageFileDirectory_v1(self.head)\n        self.endian = self._info._endian\n        self.fp.seek(self._info.next)\n        self._info.load(self.fp)\n\n        # get EXIF extension\n        ifd = self._get_ifd_dict(0x8769)\n        if ifd:\n            self._data.update(ifd)\n            self._ifds[0x8769] = ifd\n\n    def tobytes(self, offset=8):\n        from . import TiffImagePlugin\n\n        if self.endian == \"<\":\n            head = b\"II\\x2A\\x00\\x08\\x00\\x00\\x00\"\n        else:\n            head = b\"MM\\x00\\x2A\\x00\\x00\\x00\\x08\"\n        ifd = TiffImagePlugin.ImageFileDirectory_v2(ifh=head)\n        for tag, value in self.items():\n            ifd[tag] = value\n        return b\"Exif\\x00\\x00\" + head + ifd.tobytes(offset)\n\n    def get_ifd(self, tag):\n        if tag not in self._ifds and tag in self:\n            if tag in [0x8825, 0xA005]:\n                # gpsinfo, interop\n                self._ifds[tag] = self._get_ifd_dict(tag)\n            elif tag == 0x927C:  # makernote\n                from .TiffImagePlugin import ImageFileDirectory_v2\n\n                if self[0x927C][:8] == b\"FUJIFILM\":\n                    exif_data = self[0x927C]\n                    ifd_offset = i32le(exif_data[8:12])\n                    ifd_data = exif_data[ifd_offset:]\n\n                    makernote = {}\n                    for i in range(0, struct.unpack(\"<H\", ifd_data[:2])[0]):\n                        ifd_tag, typ, count, data = struct.unpack(\n                            \"<HHL4s\", ifd_data[i * 12 + 2 : (i + 1) * 12 + 2]\n                        )\n                        try:\n                            unit_size, handler = ImageFileDirectory_v2._load_dispatch[\n                                typ\n                            ]\n                        except KeyError:\n                            continue\n                        size = count * unit_size\n                        if size > 4:\n                            (offset,) = struct.unpack(\"<L\", data)\n                            data = ifd_data[offset - 12 : offset + size - 12]\n                        else:\n                            data = data[:size]\n\n                        if len(data) != size:\n                            warnings.warn(\n                                \"Possibly corrupt EXIF MakerNote data.  \"\n                                \"Expecting to read %d bytes but only got %d.\"\n                                \" Skipping tag %s\" % (size, len(data), ifd_tag)\n                            )\n                            continue\n\n                        if not data:\n                            continue\n\n                        makernote[ifd_tag] = handler(\n                            ImageFileDirectory_v2(), data, False\n                        )\n                    self._ifds[0x927C] = dict(self._fixup_dict(makernote))\n                elif self.get(0x010F) == \"Nintendo\":\n                    ifd_data = self[0x927C]\n\n                    makernote = {}\n                    for i in range(0, struct.unpack(\">H\", ifd_data[:2])[0]):\n                        ifd_tag, typ, count, data = struct.unpack(\n                            \">HHL4s\", ifd_data[i * 12 + 2 : (i + 1) * 12 + 2]\n                        )\n                        if ifd_tag == 0x1101:\n                            # CameraInfo\n                            (offset,) = struct.unpack(\">L\", data)\n                            self.fp.seek(offset)\n\n                            camerainfo = {\"ModelID\": self.fp.read(4)}\n\n                            self.fp.read(4)\n                            # Seconds since 2000\n                            camerainfo[\"TimeStamp\"] = i32le(self.fp.read(12))\n\n                            self.fp.read(4)\n                            camerainfo[\"InternalSerialNumber\"] = self.fp.read(4)\n\n                            self.fp.read(12)\n                            parallax = self.fp.read(4)\n                            handler = ImageFileDirectory_v2._load_dispatch[\n                                TiffTags.FLOAT\n                            ][1]\n                            camerainfo[\"Parallax\"] = handler(\n                                ImageFileDirectory_v2(), parallax, False\n                            )\n\n                            self.fp.read(4)\n                            camerainfo[\"Category\"] = self.fp.read(2)\n\n                            makernote = {0x1101: dict(self._fixup_dict(camerainfo))}\n                    self._ifds[0x927C] = makernote\n        return self._ifds.get(tag, {})\n\n    def __str__(self):\n        if self._info is not None:\n            # Load all keys into self._data\n            for tag in self._info.keys():\n                self[tag]\n\n        return str(self._data)\n\n    def __len__(self):\n        keys = set(self._data)\n        if self._info is not None:\n            keys.update(self._info)\n        return len(keys)\n\n    def __getitem__(self, tag):\n        if self._info is not None and tag not in self._data and tag in self._info:\n            self._data[tag] = self._fixup(self._info[tag])\n            if tag == 0x8825:\n                self._data[tag] = self.get_ifd(tag)\n            del self._info[tag]\n        return self._data[tag]\n\n    def __contains__(self, tag):\n        return tag in self._data or (self._info is not None and tag in self._info)\n\n    def __setitem__(self, tag, value):\n        if self._info is not None and tag in self._info:\n            del self._info[tag]\n        self._data[tag] = value\n\n    def __delitem__(self, tag):\n        if self._info is not None and tag in self._info:\n            del self._info[tag]\n        del self._data[tag]\n\n    def __iter__(self):\n        keys = set(self._data)\n        if self._info is not None:\n            keys.update(self._info)\n        return iter(keys)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 3240,
                            "end_lineno": 3445,
                            "parent": null
                        },
                        {
                            "file_name": "src/PIL/Image.py",
                            "type": "method",
                            "name": "Exif._get_ifd_dict",
                            "content": "class Exif(MutableMapping):\n    endian = \"<\"\n\n    def __init__(self):\n        self._data = {}\n        self._ifds = {}\n        self._info = None\n        self._loaded_exif = None\n\n    def _fixup(self, value):\n        try:\n            if len(value) == 1 and not isinstance(value, dict):\n                return value[0]\n        except Exception:\n            pass\n        return value\n\n    def _fixup_dict(self, src_dict):\n        # Helper function for _getexif()\n        # returns a dict with any single item tuples/lists as individual values\n        return {k: self._fixup(v) for k, v in src_dict.items()}\n\n    def _get_ifd_dict(self, tag):\n        try:\n            # an offset pointer to the location of the nested embedded IFD.\n            # It should be a long, but may be corrupted.\n            self.fp.seek(self[tag])\n        except (KeyError, TypeError):\n            pass\n        else:\n            from . import TiffImagePlugin\n\n            info = TiffImagePlugin.ImageFileDirectory_v1(self.head)\n            info.load(self.fp)\n            return self._fixup_dict(info)\n\n    def load(self, data):\n        # Extract EXIF information.  This is highly experimental,\n        # and is likely to be replaced with something better in a future\n        # version.\n\n        # The EXIF record consists of a TIFF file embedded in a JPEG\n        # application marker (!).\n        if data == self._loaded_exif:\n            return\n        self._loaded_exif = data\n        self._data.clear()\n        self._ifds.clear()\n        self._info = None\n        if not data:\n            return\n\n        if data.startswith(b\"Exif\\x00\\x00\"):\n            data = data[6:]\n        self.fp = io.BytesIO(data)\n        self.head = self.fp.read(8)\n        # process dictionary\n        from . import TiffImagePlugin\n\n        self._info = TiffImagePlugin.ImageFileDirectory_v1(self.head)\n        self.endian = self._info._endian\n        self.fp.seek(self._info.next)\n        self._info.load(self.fp)\n\n        # get EXIF extension\n        ifd = self._get_ifd_dict(0x8769)\n        if ifd:\n            self._data.update(ifd)\n            self._ifds[0x8769] = ifd\n\n    def tobytes(self, offset=8):\n        from . import TiffImagePlugin\n\n        if self.endian == \"<\":\n            head = b\"II\\x2A\\x00\\x08\\x00\\x00\\x00\"\n        else:\n            head = b\"MM\\x00\\x2A\\x00\\x00\\x00\\x08\"\n        ifd = TiffImagePlugin.ImageFileDirectory_v2(ifh=head)\n        for tag, value in self.items():\n            ifd[tag] = value\n        return b\"Exif\\x00\\x00\" + head + ifd.tobytes(offset)\n\n    def get_ifd(self, tag):\n        if tag not in self._ifds and tag in self:\n            if tag in [0x8825, 0xA005]:\n                # gpsinfo, interop\n                self._ifds[tag] = self._get_ifd_dict(tag)\n            elif tag == 0x927C:  # makernote\n                from .TiffImagePlugin import ImageFileDirectory_v2\n\n                if self[0x927C][:8] == b\"FUJIFILM\":\n                    exif_data = self[0x927C]\n                    ifd_offset = i32le(exif_data[8:12])\n                    ifd_data = exif_data[ifd_offset:]\n\n                    makernote = {}\n                    for i in range(0, struct.unpack(\"<H\", ifd_data[:2])[0]):\n                        ifd_tag, typ, count, data = struct.unpack(\n                            \"<HHL4s\", ifd_data[i * 12 + 2 : (i + 1) * 12 + 2]\n                        )\n                        try:\n                            unit_size, handler = ImageFileDirectory_v2._load_dispatch[\n                                typ\n                            ]\n                        except KeyError:\n                            continue\n                        size = count * unit_size\n                        if size > 4:\n                            (offset,) = struct.unpack(\"<L\", data)\n                            data = ifd_data[offset - 12 : offset + size - 12]\n                        else:\n                            data = data[:size]\n\n                        if len(data) != size:\n                            warnings.warn(\n                                \"Possibly corrupt EXIF MakerNote data.  \"\n                                \"Expecting to read %d bytes but only got %d.\"\n                                \" Skipping tag %s\" % (size, len(data), ifd_tag)\n                            )\n                            continue\n\n                        if not data:\n                            continue\n\n                        makernote[ifd_tag] = handler(\n                            ImageFileDirectory_v2(), data, False\n                        )\n                    self._ifds[0x927C] = dict(self._fixup_dict(makernote))\n                elif self.get(0x010F) == \"Nintendo\":\n                    ifd_data = self[0x927C]\n\n                    makernote = {}\n                    for i in range(0, struct.unpack(\">H\", ifd_data[:2])[0]):\n                        ifd_tag, typ, count, data = struct.unpack(\n                            \">HHL4s\", ifd_data[i * 12 + 2 : (i + 1) * 12 + 2]\n                        )\n                        if ifd_tag == 0x1101:\n                            # CameraInfo\n                            (offset,) = struct.unpack(\">L\", data)\n                            self.fp.seek(offset)\n\n                            camerainfo = {\"ModelID\": self.fp.read(4)}\n\n                            self.fp.read(4)\n                            # Seconds since 2000\n                            camerainfo[\"TimeStamp\"] = i32le(self.fp.read(12))\n\n                            self.fp.read(4)\n                            camerainfo[\"InternalSerialNumber\"] = self.fp.read(4)\n\n                            self.fp.read(12)\n                            parallax = self.fp.read(4)\n                            handler = ImageFileDirectory_v2._load_dispatch[\n                                TiffTags.FLOAT\n                            ][1]\n                            camerainfo[\"Parallax\"] = handler(\n                                ImageFileDirectory_v2(), parallax, False\n                            )\n\n                            self.fp.read(4)\n                            camerainfo[\"Category\"] = self.fp.read(2)\n\n                            makernote = {0x1101: dict(self._fixup_dict(camerainfo))}\n                    self._ifds[0x927C] = makernote\n        return self._ifds.get(tag, {})\n\n    def __str__(self):\n        if self._info is not None:\n            # Load all keys into self._data\n            for tag in self._info.keys():\n                self[tag]\n\n        return str(self._data)\n\n    def __len__(self):\n        keys = set(self._data)\n        if self._info is not None:\n            keys.update(self._info)\n        return len(keys)\n\n    def __getitem__(self, tag):\n        if self._info is not None and tag not in self._data and tag in self._info:\n            self._data[tag] = self._fixup(self._info[tag])\n            if tag == 0x8825:\n                self._data[tag] = self.get_ifd(tag)\n            del self._info[tag]\n        return self._data[tag]\n\n    def __contains__(self, tag):\n        return tag in self._data or (self._info is not None and tag in self._info)\n\n    def __setitem__(self, tag, value):\n        if self._info is not None and tag in self._info:\n            del self._info[tag]\n        self._data[tag] = value\n\n    def __delitem__(self, tag):\n        if self._info is not None and tag in self._info:\n            del self._info[tag]\n        del self._data[tag]\n\n    def __iter__(self):\n        keys = set(self._data)\n        if self._info is not None:\n            keys.update(self._info)\n        return iter(keys)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 3262,
                            "end_lineno": 3274,
                            "parent": {
                                "file_name": "src/PIL/Image.py",
                                "type": "class",
                                "name": "Exif",
                                "content": "class Exif(MutableMapping):\n    endian = \"<\"\n\n    def __init__(self):\n        self._data = {}\n        self._ifds = {}\n        self._info = None\n        self._loaded_exif = None\n\n    def _fixup(self, value):\n        try:\n            if len(value) == 1 and not isinstance(value, dict):\n                return value[0]\n        except Exception:\n            pass\n        return value\n\n    def _fixup_dict(self, src_dict):\n        # Helper function for _getexif()\n        # returns a dict with any single item tuples/lists as individual values\n        return {k: self._fixup(v) for k, v in src_dict.items()}\n\n    def _get_ifd_dict(self, tag):\n        try:\n            # an offset pointer to the location of the nested embedded IFD.\n            # It should be a long, but may be corrupted.\n            self.fp.seek(self[tag])\n        except (KeyError, TypeError):\n            pass\n        else:\n            from . import TiffImagePlugin\n\n            info = TiffImagePlugin.ImageFileDirectory_v1(self.head)\n            info.load(self.fp)\n            return self._fixup_dict(info)\n\n    def load(self, data):\n        # Extract EXIF information.  This is highly experimental,\n        # and is likely to be replaced with something better in a future\n        # version.\n\n        # The EXIF record consists of a TIFF file embedded in a JPEG\n        # application marker (!).\n        if data == self._loaded_exif:\n            return\n        self._loaded_exif = data\n        self._data.clear()\n        self._ifds.clear()\n        self._info = None\n        if not data:\n            return\n\n        if data.startswith(b\"Exif\\x00\\x00\"):\n            data = data[6:]\n        self.fp = io.BytesIO(data)\n        self.head = self.fp.read(8)\n        # process dictionary\n        from . import TiffImagePlugin\n\n        self._info = TiffImagePlugin.ImageFileDirectory_v1(self.head)\n        self.endian = self._info._endian\n        self.fp.seek(self._info.next)\n        self._info.load(self.fp)\n\n        # get EXIF extension\n        ifd = self._get_ifd_dict(0x8769)\n        if ifd:\n            self._data.update(ifd)\n            self._ifds[0x8769] = ifd\n\n    def tobytes(self, offset=8):\n        from . import TiffImagePlugin\n\n        if self.endian == \"<\":\n            head = b\"II\\x2A\\x00\\x08\\x00\\x00\\x00\"\n        else:\n            head = b\"MM\\x00\\x2A\\x00\\x00\\x00\\x08\"\n        ifd = TiffImagePlugin.ImageFileDirectory_v2(ifh=head)\n        for tag, value in self.items():\n            ifd[tag] = value\n        return b\"Exif\\x00\\x00\" + head + ifd.tobytes(offset)\n\n    def get_ifd(self, tag):\n        if tag not in self._ifds and tag in self:\n            if tag in [0x8825, 0xA005]:\n                # gpsinfo, interop\n                self._ifds[tag] = self._get_ifd_dict(tag)\n            elif tag == 0x927C:  # makernote\n                from .TiffImagePlugin import ImageFileDirectory_v2\n\n                if self[0x927C][:8] == b\"FUJIFILM\":\n                    exif_data = self[0x927C]\n                    ifd_offset = i32le(exif_data[8:12])\n                    ifd_data = exif_data[ifd_offset:]\n\n                    makernote = {}\n                    for i in range(0, struct.unpack(\"<H\", ifd_data[:2])[0]):\n                        ifd_tag, typ, count, data = struct.unpack(\n                            \"<HHL4s\", ifd_data[i * 12 + 2 : (i + 1) * 12 + 2]\n                        )\n                        try:\n                            unit_size, handler = ImageFileDirectory_v2._load_dispatch[\n                                typ\n                            ]\n                        except KeyError:\n                            continue\n                        size = count * unit_size\n                        if size > 4:\n                            (offset,) = struct.unpack(\"<L\", data)\n                            data = ifd_data[offset - 12 : offset + size - 12]\n                        else:\n                            data = data[:size]\n\n                        if len(data) != size:\n                            warnings.warn(\n                                \"Possibly corrupt EXIF MakerNote data.  \"\n                                \"Expecting to read %d bytes but only got %d.\"\n                                \" Skipping tag %s\" % (size, len(data), ifd_tag)\n                            )\n                            continue\n\n                        if not data:\n                            continue\n\n                        makernote[ifd_tag] = handler(\n                            ImageFileDirectory_v2(), data, False\n                        )\n                    self._ifds[0x927C] = dict(self._fixup_dict(makernote))\n                elif self.get(0x010F) == \"Nintendo\":\n                    ifd_data = self[0x927C]\n\n                    makernote = {}\n                    for i in range(0, struct.unpack(\">H\", ifd_data[:2])[0]):\n                        ifd_tag, typ, count, data = struct.unpack(\n                            \">HHL4s\", ifd_data[i * 12 + 2 : (i + 1) * 12 + 2]\n                        )\n                        if ifd_tag == 0x1101:\n                            # CameraInfo\n                            (offset,) = struct.unpack(\">L\", data)\n                            self.fp.seek(offset)\n\n                            camerainfo = {\"ModelID\": self.fp.read(4)}\n\n                            self.fp.read(4)\n                            # Seconds since 2000\n                            camerainfo[\"TimeStamp\"] = i32le(self.fp.read(12))\n\n                            self.fp.read(4)\n                            camerainfo[\"InternalSerialNumber\"] = self.fp.read(4)\n\n                            self.fp.read(12)\n                            parallax = self.fp.read(4)\n                            handler = ImageFileDirectory_v2._load_dispatch[\n                                TiffTags.FLOAT\n                            ][1]\n                            camerainfo[\"Parallax\"] = handler(\n                                ImageFileDirectory_v2(), parallax, False\n                            )\n\n                            self.fp.read(4)\n                            camerainfo[\"Category\"] = self.fp.read(2)\n\n                            makernote = {0x1101: dict(self._fixup_dict(camerainfo))}\n                    self._ifds[0x927C] = makernote\n        return self._ifds.get(tag, {})\n\n    def __str__(self):\n        if self._info is not None:\n            # Load all keys into self._data\n            for tag in self._info.keys():\n                self[tag]\n\n        return str(self._data)\n\n    def __len__(self):\n        keys = set(self._data)\n        if self._info is not None:\n            keys.update(self._info)\n        return len(keys)\n\n    def __getitem__(self, tag):\n        if self._info is not None and tag not in self._data and tag in self._info:\n            self._data[tag] = self._fixup(self._info[tag])\n            if tag == 0x8825:\n                self._data[tag] = self.get_ifd(tag)\n            del self._info[tag]\n        return self._data[tag]\n\n    def __contains__(self, tag):\n        return tag in self._data or (self._info is not None and tag in self._info)\n\n    def __setitem__(self, tag, value):\n        if self._info is not None and tag in self._info:\n            del self._info[tag]\n        self._data[tag] = value\n\n    def __delitem__(self, tag):\n        if self._info is not None and tag in self._info:\n            del self._info[tag]\n        del self._data[tag]\n\n    def __iter__(self):\n        keys = set(self._data)\n        if self._info is not None:\n            keys.update(self._info)\n        return iter(keys)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 3240,
                                "end_lineno": 3445,
                                "parent": null
                            }
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 3296,
                            "length": 7
                        },
                        "new_range": {
                            "start": 3296,
                            "length": 7
                        },
                        "section": "class Exif(MutableMapping):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        # process dictionary",
                                "type": "context"
                            },
                            {
                                "content": "        from . import TiffImagePlugin",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        self._info = TiffImagePlugin.ImageFileDirectory_v1(self.head)",
                                "type": "deleted"
                            },
                            {
                                "content": "        self._info = TiffImagePlugin.ImageFileDirectory_v2(self.head)",
                                "type": "added"
                            },
                            {
                                "content": "        self.endian = self._info._endian",
                                "type": "context"
                            },
                            {
                                "content": "        self.fp.seek(self._info.next)",
                                "type": "context"
                            },
                            {
                                "content": "        self._info.load(self.fp)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "src/PIL/Image.py",
                            "type": "method",
                            "name": "Exif.load",
                            "content": "class Exif(MutableMapping):\n    endian = \"<\"\n\n    def __init__(self):\n        self._data = {}\n        self._ifds = {}\n        self._info = None\n        self._loaded_exif = None\n\n    def _fixup(self, value):\n        try:\n            if len(value) == 1 and not isinstance(value, dict):\n                return value[0]\n        except Exception:\n            pass\n        return value\n\n    def _fixup_dict(self, src_dict):\n        # Helper function for _getexif()\n        # returns a dict with any single item tuples/lists as individual values\n        return {k: self._fixup(v) for k, v in src_dict.items()}\n\n    def _get_ifd_dict(self, tag):\n        try:\n            # an offset pointer to the location of the nested embedded IFD.\n            # It should be a long, but may be corrupted.\n            self.fp.seek(self[tag])\n        except (KeyError, TypeError):\n            pass\n        else:\n            from . import TiffImagePlugin\n\n            info = TiffImagePlugin.ImageFileDirectory_v1(self.head)\n            info.load(self.fp)\n            return self._fixup_dict(info)\n\n    def load(self, data):\n        # Extract EXIF information.  This is highly experimental,\n        # and is likely to be replaced with something better in a future\n        # version.\n\n        # The EXIF record consists of a TIFF file embedded in a JPEG\n        # application marker (!).\n        if data == self._loaded_exif:\n            return\n        self._loaded_exif = data\n        self._data.clear()\n        self._ifds.clear()\n        self._info = None\n        if not data:\n            return\n\n        if data.startswith(b\"Exif\\x00\\x00\"):\n            data = data[6:]\n        self.fp = io.BytesIO(data)\n        self.head = self.fp.read(8)\n        # process dictionary\n        from . import TiffImagePlugin\n\n        self._info = TiffImagePlugin.ImageFileDirectory_v1(self.head)\n        self.endian = self._info._endian\n        self.fp.seek(self._info.next)\n        self._info.load(self.fp)\n\n        # get EXIF extension\n        ifd = self._get_ifd_dict(0x8769)\n        if ifd:\n            self._data.update(ifd)\n            self._ifds[0x8769] = ifd\n\n    def tobytes(self, offset=8):\n        from . import TiffImagePlugin\n\n        if self.endian == \"<\":\n            head = b\"II\\x2A\\x00\\x08\\x00\\x00\\x00\"\n        else:\n            head = b\"MM\\x00\\x2A\\x00\\x00\\x00\\x08\"\n        ifd = TiffImagePlugin.ImageFileDirectory_v2(ifh=head)\n        for tag, value in self.items():\n            ifd[tag] = value\n        return b\"Exif\\x00\\x00\" + head + ifd.tobytes(offset)\n\n    def get_ifd(self, tag):\n        if tag not in self._ifds and tag in self:\n            if tag in [0x8825, 0xA005]:\n                # gpsinfo, interop\n                self._ifds[tag] = self._get_ifd_dict(tag)\n            elif tag == 0x927C:  # makernote\n                from .TiffImagePlugin import ImageFileDirectory_v2\n\n                if self[0x927C][:8] == b\"FUJIFILM\":\n                    exif_data = self[0x927C]\n                    ifd_offset = i32le(exif_data[8:12])\n                    ifd_data = exif_data[ifd_offset:]\n\n                    makernote = {}\n                    for i in range(0, struct.unpack(\"<H\", ifd_data[:2])[0]):\n                        ifd_tag, typ, count, data = struct.unpack(\n                            \"<HHL4s\", ifd_data[i * 12 + 2 : (i + 1) * 12 + 2]\n                        )\n                        try:\n                            unit_size, handler = ImageFileDirectory_v2._load_dispatch[\n                                typ\n                            ]\n                        except KeyError:\n                            continue\n                        size = count * unit_size\n                        if size > 4:\n                            (offset,) = struct.unpack(\"<L\", data)\n                            data = ifd_data[offset - 12 : offset + size - 12]\n                        else:\n                            data = data[:size]\n\n                        if len(data) != size:\n                            warnings.warn(\n                                \"Possibly corrupt EXIF MakerNote data.  \"\n                                \"Expecting to read %d bytes but only got %d.\"\n                                \" Skipping tag %s\" % (size, len(data), ifd_tag)\n                            )\n                            continue\n\n                        if not data:\n                            continue\n\n                        makernote[ifd_tag] = handler(\n                            ImageFileDirectory_v2(), data, False\n                        )\n                    self._ifds[0x927C] = dict(self._fixup_dict(makernote))\n                elif self.get(0x010F) == \"Nintendo\":\n                    ifd_data = self[0x927C]\n\n                    makernote = {}\n                    for i in range(0, struct.unpack(\">H\", ifd_data[:2])[0]):\n                        ifd_tag, typ, count, data = struct.unpack(\n                            \">HHL4s\", ifd_data[i * 12 + 2 : (i + 1) * 12 + 2]\n                        )\n                        if ifd_tag == 0x1101:\n                            # CameraInfo\n                            (offset,) = struct.unpack(\">L\", data)\n                            self.fp.seek(offset)\n\n                            camerainfo = {\"ModelID\": self.fp.read(4)}\n\n                            self.fp.read(4)\n                            # Seconds since 2000\n                            camerainfo[\"TimeStamp\"] = i32le(self.fp.read(12))\n\n                            self.fp.read(4)\n                            camerainfo[\"InternalSerialNumber\"] = self.fp.read(4)\n\n                            self.fp.read(12)\n                            parallax = self.fp.read(4)\n                            handler = ImageFileDirectory_v2._load_dispatch[\n                                TiffTags.FLOAT\n                            ][1]\n                            camerainfo[\"Parallax\"] = handler(\n                                ImageFileDirectory_v2(), parallax, False\n                            )\n\n                            self.fp.read(4)\n                            camerainfo[\"Category\"] = self.fp.read(2)\n\n                            makernote = {0x1101: dict(self._fixup_dict(camerainfo))}\n                    self._ifds[0x927C] = makernote\n        return self._ifds.get(tag, {})\n\n    def __str__(self):\n        if self._info is not None:\n            # Load all keys into self._data\n            for tag in self._info.keys():\n                self[tag]\n\n        return str(self._data)\n\n    def __len__(self):\n        keys = set(self._data)\n        if self._info is not None:\n            keys.update(self._info)\n        return len(keys)\n\n    def __getitem__(self, tag):\n        if self._info is not None and tag not in self._data and tag in self._info:\n            self._data[tag] = self._fixup(self._info[tag])\n            if tag == 0x8825:\n                self._data[tag] = self.get_ifd(tag)\n            del self._info[tag]\n        return self._data[tag]\n\n    def __contains__(self, tag):\n        return tag in self._data or (self._info is not None and tag in self._info)\n\n    def __setitem__(self, tag, value):\n        if self._info is not None and tag in self._info:\n            del self._info[tag]\n        self._data[tag] = value\n\n    def __delitem__(self, tag):\n        if self._info is not None and tag in self._info:\n            del self._info[tag]\n        del self._data[tag]\n\n    def __iter__(self):\n        keys = set(self._data)\n        if self._info is not None:\n            keys.update(self._info)\n        return iter(keys)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 3276,
                            "end_lineno": 3308,
                            "parent": {
                                "file_name": "src/PIL/Image.py",
                                "type": "class",
                                "name": "Exif",
                                "content": "class Exif(MutableMapping):\n    endian = \"<\"\n\n    def __init__(self):\n        self._data = {}\n        self._ifds = {}\n        self._info = None\n        self._loaded_exif = None\n\n    def _fixup(self, value):\n        try:\n            if len(value) == 1 and not isinstance(value, dict):\n                return value[0]\n        except Exception:\n            pass\n        return value\n\n    def _fixup_dict(self, src_dict):\n        # Helper function for _getexif()\n        # returns a dict with any single item tuples/lists as individual values\n        return {k: self._fixup(v) for k, v in src_dict.items()}\n\n    def _get_ifd_dict(self, tag):\n        try:\n            # an offset pointer to the location of the nested embedded IFD.\n            # It should be a long, but may be corrupted.\n            self.fp.seek(self[tag])\n        except (KeyError, TypeError):\n            pass\n        else:\n            from . import TiffImagePlugin\n\n            info = TiffImagePlugin.ImageFileDirectory_v1(self.head)\n            info.load(self.fp)\n            return self._fixup_dict(info)\n\n    def load(self, data):\n        # Extract EXIF information.  This is highly experimental,\n        # and is likely to be replaced with something better in a future\n        # version.\n\n        # The EXIF record consists of a TIFF file embedded in a JPEG\n        # application marker (!).\n        if data == self._loaded_exif:\n            return\n        self._loaded_exif = data\n        self._data.clear()\n        self._ifds.clear()\n        self._info = None\n        if not data:\n            return\n\n        if data.startswith(b\"Exif\\x00\\x00\"):\n            data = data[6:]\n        self.fp = io.BytesIO(data)\n        self.head = self.fp.read(8)\n        # process dictionary\n        from . import TiffImagePlugin\n\n        self._info = TiffImagePlugin.ImageFileDirectory_v1(self.head)\n        self.endian = self._info._endian\n        self.fp.seek(self._info.next)\n        self._info.load(self.fp)\n\n        # get EXIF extension\n        ifd = self._get_ifd_dict(0x8769)\n        if ifd:\n            self._data.update(ifd)\n            self._ifds[0x8769] = ifd\n\n    def tobytes(self, offset=8):\n        from . import TiffImagePlugin\n\n        if self.endian == \"<\":\n            head = b\"II\\x2A\\x00\\x08\\x00\\x00\\x00\"\n        else:\n            head = b\"MM\\x00\\x2A\\x00\\x00\\x00\\x08\"\n        ifd = TiffImagePlugin.ImageFileDirectory_v2(ifh=head)\n        for tag, value in self.items():\n            ifd[tag] = value\n        return b\"Exif\\x00\\x00\" + head + ifd.tobytes(offset)\n\n    def get_ifd(self, tag):\n        if tag not in self._ifds and tag in self:\n            if tag in [0x8825, 0xA005]:\n                # gpsinfo, interop\n                self._ifds[tag] = self._get_ifd_dict(tag)\n            elif tag == 0x927C:  # makernote\n                from .TiffImagePlugin import ImageFileDirectory_v2\n\n                if self[0x927C][:8] == b\"FUJIFILM\":\n                    exif_data = self[0x927C]\n                    ifd_offset = i32le(exif_data[8:12])\n                    ifd_data = exif_data[ifd_offset:]\n\n                    makernote = {}\n                    for i in range(0, struct.unpack(\"<H\", ifd_data[:2])[0]):\n                        ifd_tag, typ, count, data = struct.unpack(\n                            \"<HHL4s\", ifd_data[i * 12 + 2 : (i + 1) * 12 + 2]\n                        )\n                        try:\n                            unit_size, handler = ImageFileDirectory_v2._load_dispatch[\n                                typ\n                            ]\n                        except KeyError:\n                            continue\n                        size = count * unit_size\n                        if size > 4:\n                            (offset,) = struct.unpack(\"<L\", data)\n                            data = ifd_data[offset - 12 : offset + size - 12]\n                        else:\n                            data = data[:size]\n\n                        if len(data) != size:\n                            warnings.warn(\n                                \"Possibly corrupt EXIF MakerNote data.  \"\n                                \"Expecting to read %d bytes but only got %d.\"\n                                \" Skipping tag %s\" % (size, len(data), ifd_tag)\n                            )\n                            continue\n\n                        if not data:\n                            continue\n\n                        makernote[ifd_tag] = handler(\n                            ImageFileDirectory_v2(), data, False\n                        )\n                    self._ifds[0x927C] = dict(self._fixup_dict(makernote))\n                elif self.get(0x010F) == \"Nintendo\":\n                    ifd_data = self[0x927C]\n\n                    makernote = {}\n                    for i in range(0, struct.unpack(\">H\", ifd_data[:2])[0]):\n                        ifd_tag, typ, count, data = struct.unpack(\n                            \">HHL4s\", ifd_data[i * 12 + 2 : (i + 1) * 12 + 2]\n                        )\n                        if ifd_tag == 0x1101:\n                            # CameraInfo\n                            (offset,) = struct.unpack(\">L\", data)\n                            self.fp.seek(offset)\n\n                            camerainfo = {\"ModelID\": self.fp.read(4)}\n\n                            self.fp.read(4)\n                            # Seconds since 2000\n                            camerainfo[\"TimeStamp\"] = i32le(self.fp.read(12))\n\n                            self.fp.read(4)\n                            camerainfo[\"InternalSerialNumber\"] = self.fp.read(4)\n\n                            self.fp.read(12)\n                            parallax = self.fp.read(4)\n                            handler = ImageFileDirectory_v2._load_dispatch[\n                                TiffTags.FLOAT\n                            ][1]\n                            camerainfo[\"Parallax\"] = handler(\n                                ImageFileDirectory_v2(), parallax, False\n                            )\n\n                            self.fp.read(4)\n                            camerainfo[\"Category\"] = self.fp.read(2)\n\n                            makernote = {0x1101: dict(self._fixup_dict(camerainfo))}\n                    self._ifds[0x927C] = makernote\n        return self._ifds.get(tag, {})\n\n    def __str__(self):\n        if self._info is not None:\n            # Load all keys into self._data\n            for tag in self._info.keys():\n                self[tag]\n\n        return str(self._data)\n\n    def __len__(self):\n        keys = set(self._data)\n        if self._info is not None:\n            keys.update(self._info)\n        return len(keys)\n\n    def __getitem__(self, tag):\n        if self._info is not None and tag not in self._data and tag in self._info:\n            self._data[tag] = self._fixup(self._info[tag])\n            if tag == 0x8825:\n                self._data[tag] = self.get_ifd(tag)\n            del self._info[tag]\n        return self._data[tag]\n\n    def __contains__(self, tag):\n        return tag in self._data or (self._info is not None and tag in self._info)\n\n    def __setitem__(self, tag, value):\n        if self._info is not None and tag in self._info:\n            del self._info[tag]\n        self._data[tag] = value\n\n    def __delitem__(self, tag):\n        if self._info is not None and tag in self._info:\n            del self._info[tag]\n        del self._data[tag]\n\n    def __iter__(self):\n        keys = set(self._data)\n        if self._info is not None:\n            keys.update(self._info)\n        return iter(keys)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 3240,
                                "end_lineno": 3445,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "src/PIL/Image.py",
                            "type": "class",
                            "name": "Exif",
                            "content": "class Exif(MutableMapping):\n    endian = \"<\"\n\n    def __init__(self):\n        self._data = {}\n        self._ifds = {}\n        self._info = None\n        self._loaded_exif = None\n\n    def _fixup(self, value):\n        try:\n            if len(value) == 1 and not isinstance(value, dict):\n                return value[0]\n        except Exception:\n            pass\n        return value\n\n    def _fixup_dict(self, src_dict):\n        # Helper function for _getexif()\n        # returns a dict with any single item tuples/lists as individual values\n        return {k: self._fixup(v) for k, v in src_dict.items()}\n\n    def _get_ifd_dict(self, tag):\n        try:\n            # an offset pointer to the location of the nested embedded IFD.\n            # It should be a long, but may be corrupted.\n            self.fp.seek(self[tag])\n        except (KeyError, TypeError):\n            pass\n        else:\n            from . import TiffImagePlugin\n\n            info = TiffImagePlugin.ImageFileDirectory_v1(self.head)\n            info.load(self.fp)\n            return self._fixup_dict(info)\n\n    def load(self, data):\n        # Extract EXIF information.  This is highly experimental,\n        # and is likely to be replaced with something better in a future\n        # version.\n\n        # The EXIF record consists of a TIFF file embedded in a JPEG\n        # application marker (!).\n        if data == self._loaded_exif:\n            return\n        self._loaded_exif = data\n        self._data.clear()\n        self._ifds.clear()\n        self._info = None\n        if not data:\n            return\n\n        if data.startswith(b\"Exif\\x00\\x00\"):\n            data = data[6:]\n        self.fp = io.BytesIO(data)\n        self.head = self.fp.read(8)\n        # process dictionary\n        from . import TiffImagePlugin\n\n        self._info = TiffImagePlugin.ImageFileDirectory_v1(self.head)\n        self.endian = self._info._endian\n        self.fp.seek(self._info.next)\n        self._info.load(self.fp)\n\n        # get EXIF extension\n        ifd = self._get_ifd_dict(0x8769)\n        if ifd:\n            self._data.update(ifd)\n            self._ifds[0x8769] = ifd\n\n    def tobytes(self, offset=8):\n        from . import TiffImagePlugin\n\n        if self.endian == \"<\":\n            head = b\"II\\x2A\\x00\\x08\\x00\\x00\\x00\"\n        else:\n            head = b\"MM\\x00\\x2A\\x00\\x00\\x00\\x08\"\n        ifd = TiffImagePlugin.ImageFileDirectory_v2(ifh=head)\n        for tag, value in self.items():\n            ifd[tag] = value\n        return b\"Exif\\x00\\x00\" + head + ifd.tobytes(offset)\n\n    def get_ifd(self, tag):\n        if tag not in self._ifds and tag in self:\n            if tag in [0x8825, 0xA005]:\n                # gpsinfo, interop\n                self._ifds[tag] = self._get_ifd_dict(tag)\n            elif tag == 0x927C:  # makernote\n                from .TiffImagePlugin import ImageFileDirectory_v2\n\n                if self[0x927C][:8] == b\"FUJIFILM\":\n                    exif_data = self[0x927C]\n                    ifd_offset = i32le(exif_data[8:12])\n                    ifd_data = exif_data[ifd_offset:]\n\n                    makernote = {}\n                    for i in range(0, struct.unpack(\"<H\", ifd_data[:2])[0]):\n                        ifd_tag, typ, count, data = struct.unpack(\n                            \"<HHL4s\", ifd_data[i * 12 + 2 : (i + 1) * 12 + 2]\n                        )\n                        try:\n                            unit_size, handler = ImageFileDirectory_v2._load_dispatch[\n                                typ\n                            ]\n                        except KeyError:\n                            continue\n                        size = count * unit_size\n                        if size > 4:\n                            (offset,) = struct.unpack(\"<L\", data)\n                            data = ifd_data[offset - 12 : offset + size - 12]\n                        else:\n                            data = data[:size]\n\n                        if len(data) != size:\n                            warnings.warn(\n                                \"Possibly corrupt EXIF MakerNote data.  \"\n                                \"Expecting to read %d bytes but only got %d.\"\n                                \" Skipping tag %s\" % (size, len(data), ifd_tag)\n                            )\n                            continue\n\n                        if not data:\n                            continue\n\n                        makernote[ifd_tag] = handler(\n                            ImageFileDirectory_v2(), data, False\n                        )\n                    self._ifds[0x927C] = dict(self._fixup_dict(makernote))\n                elif self.get(0x010F) == \"Nintendo\":\n                    ifd_data = self[0x927C]\n\n                    makernote = {}\n                    for i in range(0, struct.unpack(\">H\", ifd_data[:2])[0]):\n                        ifd_tag, typ, count, data = struct.unpack(\n                            \">HHL4s\", ifd_data[i * 12 + 2 : (i + 1) * 12 + 2]\n                        )\n                        if ifd_tag == 0x1101:\n                            # CameraInfo\n                            (offset,) = struct.unpack(\">L\", data)\n                            self.fp.seek(offset)\n\n                            camerainfo = {\"ModelID\": self.fp.read(4)}\n\n                            self.fp.read(4)\n                            # Seconds since 2000\n                            camerainfo[\"TimeStamp\"] = i32le(self.fp.read(12))\n\n                            self.fp.read(4)\n                            camerainfo[\"InternalSerialNumber\"] = self.fp.read(4)\n\n                            self.fp.read(12)\n                            parallax = self.fp.read(4)\n                            handler = ImageFileDirectory_v2._load_dispatch[\n                                TiffTags.FLOAT\n                            ][1]\n                            camerainfo[\"Parallax\"] = handler(\n                                ImageFileDirectory_v2(), parallax, False\n                            )\n\n                            self.fp.read(4)\n                            camerainfo[\"Category\"] = self.fp.read(2)\n\n                            makernote = {0x1101: dict(self._fixup_dict(camerainfo))}\n                    self._ifds[0x927C] = makernote\n        return self._ifds.get(tag, {})\n\n    def __str__(self):\n        if self._info is not None:\n            # Load all keys into self._data\n            for tag in self._info.keys():\n                self[tag]\n\n        return str(self._data)\n\n    def __len__(self):\n        keys = set(self._data)\n        if self._info is not None:\n            keys.update(self._info)\n        return len(keys)\n\n    def __getitem__(self, tag):\n        if self._info is not None and tag not in self._data and tag in self._info:\n            self._data[tag] = self._fixup(self._info[tag])\n            if tag == 0x8825:\n                self._data[tag] = self.get_ifd(tag)\n            del self._info[tag]\n        return self._data[tag]\n\n    def __contains__(self, tag):\n        return tag in self._data or (self._info is not None and tag in self._info)\n\n    def __setitem__(self, tag, value):\n        if self._info is not None and tag in self._info:\n            del self._info[tag]\n        self._data[tag] = value\n\n    def __delitem__(self, tag):\n        if self._info is not None and tag in self._info:\n            del self._info[tag]\n        del self._data[tag]\n\n    def __iter__(self):\n        keys = set(self._data)\n        if self._info is not None:\n            keys.update(self._info)\n        return iter(keys)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 3240,
                            "end_lineno": 3445,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "794e9f0f0e85535e6bd1791e2ec127dec345f319^",
    "new_commit_hash": "794e9f0f0e85535e6bd1791e2ec127dec345f319",
    "commit_message": "Merge pull request #4637 from radarhere/v2\n\nUse ImageFileDirectory_v2 in Image.Exif",
    "commit_date": "2020-06-10T06:55:15+03:00",
    "metadata": {}
}
{
    "repo_name": "pillow",
    "new_commit_hash": "794e9f0f0e85535e6bd1791e2ec127dec345f319",
    "test_file_codes": [
        "import os\nimport re\nfrom io import BytesIO\n\nimport pytest\nfrom PIL import ExifTags, Image, ImageFile, JpegImagePlugin\n\nfrom .helper import (\n    assert_image,\n    assert_image_equal,\n    assert_image_similar,\n    cjpeg_available,\n    djpeg_available,\n    hopper,\n    is_win32,\n    skip_unless_feature,\n)\n\nTEST_FILE = \"Tests/images/hopper.jpg\"\n\n\n@skip_unless_feature(\"jpg\")\nclass TestFileJpeg:\n    def roundtrip(self, im, **options):\n        out = BytesIO()\n        im.save(out, \"JPEG\", **options)\n        test_bytes = out.tell()\n        out.seek(0)\n        im = Image.open(out)\n        im.bytes = test_bytes  # for testing only\n        return im\n\n    def gen_random_image(self, size, mode=\"RGB\"):\n        \"\"\" Generates a very hard to compress file\n        :param size: tuple\n        :param mode: optional image mode\n\n        \"\"\"\n        return Image.frombytes(mode, size, os.urandom(size[0] * size[1] * len(mode)))\n\n    def test_sanity(self):\n\n        # internal version number\n        assert re.search(r\"\\d+\\.\\d+$\", Image.core.jpeglib_version)\n\n        with Image.open(TEST_FILE) as im:\n            im.load()\n            assert im.mode == \"RGB\"\n            assert im.size == (128, 128)\n            assert im.format == \"JPEG\"\n            assert im.get_format_mimetype() == \"image/jpeg\"\n\n    def test_app(self):\n        # Test APP/COM reader (@PIL135)\n        with Image.open(TEST_FILE) as im:\n            assert im.applist[0] == (\"APP0\", b\"JFIF\\x00\\x01\\x01\\x01\\x00`\\x00`\\x00\\x00\")\n            assert im.applist[1] == (\n                \"COM\",\n                b\"File written by Adobe Photoshop\\xa8 4.0\\x00\",\n            )\n            assert len(im.applist) == 2\n\n            assert im.info[\"comment\"] == b\"File written by Adobe Photoshop\\xa8 4.0\\x00\"\n\n    def test_cmyk(self):\n        # Test CMYK handling.  Thanks to Tim and Charlie for test data,\n        # Michael for getting me to look one more time.\n        f = \"Tests/images/pil_sample_cmyk.jpg\"\n        with Image.open(f) as im:\n            # the source image has red pixels in the upper left corner.\n            c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))]\n            assert c == 0.0\n            assert m > 0.8\n            assert y > 0.8\n            assert k == 0.0\n            # the opposite corner is black\n            c, m, y, k = [\n                x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1))\n            ]\n            assert k > 0.9\n            # roundtrip, and check again\n            im = self.roundtrip(im)\n            c, m, y, k = [x / 255.0 for x in im.getpixel((0, 0))]\n            assert c == 0.0\n            assert m > 0.8\n            assert y > 0.8\n            assert k == 0.0\n            c, m, y, k = [\n                x / 255.0 for x in im.getpixel((im.size[0] - 1, im.size[1] - 1))\n            ]\n            assert k > 0.9\n\n    def test_dpi(self):\n        def test(xdpi, ydpi=None):\n            with Image.open(TEST_FILE) as im:\n                im = self.roundtrip(im, dpi=(xdpi, ydpi or xdpi))\n            return im.info.get(\"dpi\")\n\n        assert test(72) == (72, 72)\n        assert test(300) == (300, 300)\n        assert test(100, 200) == (100, 200)\n        assert test(0) is None  # square pixels\n\n    def test_icc(self, tmp_path):\n        # Test ICC support\n        with Image.open(\"Tests/images/rgb.jpg\") as im1:\n            icc_profile = im1.info[\"icc_profile\"]\n            assert len(icc_profile) == 3144\n            # Roundtrip via physical file.\n            f = str(tmp_path / \"temp.jpg\")\n            im1.save(f, icc_profile=icc_profile)\n        with Image.open(f) as im2:\n            assert im2.info.get(\"icc_profile\") == icc_profile\n            # Roundtrip via memory buffer.\n            im1 = self.roundtrip(hopper())\n            im2 = self.roundtrip(hopper(), icc_profile=icc_profile)\n            assert_image_equal(im1, im2)\n            assert not im1.info.get(\"icc_profile\")\n            assert im2.info.get(\"icc_profile\")\n\n    def test_icc_big(self):\n        # Make sure that the \"extra\" support handles large blocks\n        def test(n):\n            # The ICC APP marker can store 65519 bytes per marker, so\n            # using a 4-byte test code should allow us to detect out of\n            # order issues.\n            icc_profile = (b\"Test\" * int(n / 4 + 1))[:n]\n            assert len(icc_profile) == n  # sanity\n            im1 = self.roundtrip(hopper(), icc_profile=icc_profile)\n            assert im1.info.get(\"icc_profile\") == (icc_profile or None)\n\n        test(0)\n        test(1)\n        test(3)\n        test(4)\n        test(5)\n        test(65533 - 14)  # full JPEG marker block\n        test(65533 - 14 + 1)  # full block plus one byte\n        test(ImageFile.MAXBLOCK)  # full buffer block\n        test(ImageFile.MAXBLOCK + 1)  # full buffer block plus one byte\n        test(ImageFile.MAXBLOCK * 4 + 3)  # large block\n\n    def test_large_icc_meta(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        # Sometimes the meta data on the icc_profile block is bigger than\n        # Image.MAXBLOCK or the image size.\n        with Image.open(\"Tests/images/icc_profile_big.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            icc_profile = im.info[\"icc_profile\"]\n            # Should not raise OSError for image with icc larger than image size.\n            im.save(\n                f,\n                format=\"JPEG\",\n                progressive=True,\n                quality=95,\n                icc_profile=icc_profile,\n                optimize=True,\n            )\n\n    def test_optimize(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), optimize=0)\n        im3 = self.roundtrip(hopper(), optimize=1)\n        assert_image_equal(im1, im2)\n        assert_image_equal(im1, im3)\n        assert im1.bytes >= im2.bytes\n        assert im1.bytes >= im3.bytes\n\n    def test_optimize_large_buffer(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        f = str(tmp_path / \"temp.jpg\")\n        # this requires ~ 1.5x Image.MAXBLOCK\n        im = Image.new(\"RGB\", (4096, 4096), 0xFF3333)\n        im.save(f, format=\"JPEG\", optimize=True)\n\n    def test_progressive(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), progressive=False)\n        im3 = self.roundtrip(hopper(), progressive=True)\n        assert not im1.info.get(\"progressive\")\n        assert not im2.info.get(\"progressive\")\n        assert im3.info.get(\"progressive\")\n\n        assert_image_equal(im1, im3)\n        assert im1.bytes >= im3.bytes\n\n    def test_progressive_large_buffer(self, tmp_path):\n        f = str(tmp_path / \"temp.jpg\")\n        # this requires ~ 1.5x Image.MAXBLOCK\n        im = Image.new(\"RGB\", (4096, 4096), 0xFF3333)\n        im.save(f, format=\"JPEG\", progressive=True)\n\n    def test_progressive_large_buffer_highest_quality(self, tmp_path):\n        f = str(tmp_path / \"temp.jpg\")\n        im = self.gen_random_image((255, 255))\n        # this requires more bytes than pixels in the image\n        im.save(f, format=\"JPEG\", progressive=True, quality=100)\n\n    def test_progressive_cmyk_buffer(self):\n        # Issue 2272, quality 90 cmyk image is tripping the large buffer bug.\n        f = BytesIO()\n        im = self.gen_random_image((256, 256), \"CMYK\")\n        im.save(f, format=\"JPEG\", progressive=True, quality=94)\n\n    def test_large_exif(self, tmp_path):\n        # https://github.com/python-pillow/Pillow/issues/148\n        f = str(tmp_path / \"temp.jpg\")\n        im = hopper()\n        im.save(f, \"JPEG\", quality=90, exif=b\"1\" * 65532)\n\n    def test_exif_typeerror(self):\n        with Image.open(\"Tests/images/exif_typeerror.jpg\") as im:\n            # Should not raise a TypeError\n            im._getexif()\n\n    def test_exif_gps(self):\n        # Arrange\n        with Image.open(\"Tests/images/exif_gps.jpg\") as im:\n            gps_index = 34853\n            expected_exif_gps = {\n                0: b\"\\x00\\x00\\x00\\x01\",\n                2: 4294967295,\n                5: b\"\\x01\",\n                30: 65535,\n                29: \"1999:99:99 99:99:99\",\n            }\n\n            # Act\n            exif = im._getexif()\n\n        # Assert\n        assert exif[gps_index] == expected_exif_gps\n\n    def test_exif_rollback(self):\n        # rolling back exif support in 3.1 to pre-3.0 formatting.\n        # expected from 2.9, with b/u qualifiers switched for 3.2 compatibility\n        # this test passes on 2.9 and 3.1, but not 3.0\n        expected_exif = {\n            34867: 4294967295,\n            258: (24, 24, 24),\n            36867: \"2099:09:29 10:10:10\",\n            34853: {\n                0: b\"\\x00\\x00\\x00\\x01\",\n                2: 4294967295,\n                5: b\"\\x01\",\n                30: 65535,\n                29: \"1999:99:99 99:99:99\",\n            },\n            296: 65535,\n            34665: 185,\n            41994: 65535,\n            514: 4294967295,\n            271: \"Make\",\n            272: \"XXX-XXX\",\n            305: \"PIL\",\n            42034: (1, 1, 1, 1),\n            42035: \"LensMake\",\n            34856: b\"\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa\",\n            282: 4294967295,\n            33434: 4294967295,\n        }\n\n        with Image.open(\"Tests/images/exif_gps.jpg\") as im:\n            exif = im._getexif()\n\n        for tag, value in expected_exif.items():\n            assert value == exif[tag]\n\n    def test_exif_gps_typeerror(self):\n        with Image.open(\"Tests/images/exif_gps_typeerror.jpg\") as im:\n\n            # Should not raise a TypeError\n            im._getexif()\n\n    def test_progressive_compat(self):\n        im1 = self.roundtrip(hopper())\n        assert not im1.info.get(\"progressive\")\n        assert not im1.info.get(\"progression\")\n\n        im2 = self.roundtrip(hopper(), progressive=0)\n        im3 = self.roundtrip(hopper(), progression=0)  # compatibility\n        assert not im2.info.get(\"progressive\")\n        assert not im2.info.get(\"progression\")\n        assert not im3.info.get(\"progressive\")\n        assert not im3.info.get(\"progression\")\n\n        im2 = self.roundtrip(hopper(), progressive=1)\n        im3 = self.roundtrip(hopper(), progression=1)  # compatibility\n        assert_image_equal(im1, im2)\n        assert_image_equal(im1, im3)\n        assert im2.info.get(\"progressive\")\n        assert im2.info.get(\"progression\")\n        assert im3.info.get(\"progressive\")\n        assert im3.info.get(\"progression\")\n\n    def test_quality(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), quality=50)\n        assert_image(im1, im2.mode, im2.size)\n        assert im1.bytes >= im2.bytes\n\n        im3 = self.roundtrip(hopper(), quality=0)\n        assert_image(im1, im3.mode, im3.size)\n        assert im2.bytes > im3.bytes\n\n    def test_smooth(self):\n        im1 = self.roundtrip(hopper())\n        im2 = self.roundtrip(hopper(), smooth=100)\n        assert_image(im1, im2.mode, im2.size)\n\n    def test_subsampling(self):\n        def getsampling(im):\n            layer = im.layer\n            return layer[0][1:3] + layer[1][1:3] + layer[2][1:3]\n\n        # experimental API\n        im = self.roundtrip(hopper(), subsampling=-1)  # default\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=0)  # 4:4:4\n        assert getsampling(im) == (1, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=1)  # 4:2:2\n        assert getsampling(im) == (2, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=2)  # 4:2:0\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=3)  # default (undefined)\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n\n        im = self.roundtrip(hopper(), subsampling=\"4:4:4\")\n        assert getsampling(im) == (1, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:2:2\")\n        assert getsampling(im) == (2, 1, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:2:0\")\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n        im = self.roundtrip(hopper(), subsampling=\"4:1:1\")\n        assert getsampling(im) == (2, 2, 1, 1, 1, 1)\n\n        with pytest.raises(TypeError):\n            self.roundtrip(hopper(), subsampling=\"1:1:1\")\n\n    def test_exif(self):\n        with Image.open(\"Tests/images/pil_sample_rgb.jpg\") as im:\n            info = im._getexif()\n            assert info[305] == \"Adobe Photoshop CS Macintosh\"\n\n    def test_mp(self):\n        with Image.open(\"Tests/images/pil_sample_rgb.jpg\") as im:\n            assert im._getmp() is None\n\n    def test_quality_keep(self, tmp_path):\n        # RGB\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n        # Grayscale\n        with Image.open(\"Tests/images/hopper_gray.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n        # CMYK\n        with Image.open(\"Tests/images/pil_sample_cmyk.jpg\") as im:\n            f = str(tmp_path / \"temp.jpg\")\n            im.save(f, quality=\"keep\")\n\n    def test_junk_jpeg_header(self):\n        # https://github.com/python-pillow/Pillow/issues/630\n        filename = \"Tests/images/junk_jpeg_header.jpg\"\n        with Image.open(filename):\n            pass\n\n    def test_ff00_jpeg_header(self):\n        filename = \"Tests/images/jpeg_ff00_header.jpg\"\n        with Image.open(filename):\n            pass\n\n    def test_truncated_jpeg_should_read_all_the_data(self):\n        filename = \"Tests/images/truncated_jpeg.jpg\"\n        ImageFile.LOAD_TRUNCATED_IMAGES = True\n        with Image.open(filename) as im:\n            im.load()\n            ImageFile.LOAD_TRUNCATED_IMAGES = False\n            assert im.getbbox() is not None\n\n    def test_truncated_jpeg_throws_oserror(self):\n        filename = \"Tests/images/truncated_jpeg.jpg\"\n        with Image.open(filename) as im:\n            with pytest.raises(OSError):\n                im.load()\n\n            # Test that the error is raised if loaded a second time\n            with pytest.raises(OSError):\n                im.load()\n\n    def test_qtables(self, tmp_path):\n        def _n_qtables_helper(n, test_file):\n            with Image.open(test_file) as im:\n                f = str(tmp_path / \"temp.jpg\")\n                im.save(f, qtables=[[n] * 64] * n)\n            with Image.open(f) as im:\n                assert len(im.quantization) == n\n                reloaded = self.roundtrip(im, qtables=\"keep\")\n                assert im.quantization == reloaded.quantization\n\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            qtables = im.quantization\n            reloaded = self.roundtrip(im, qtables=qtables, subsampling=0)\n            assert im.quantization == reloaded.quantization\n            assert_image_similar(im, self.roundtrip(im, qtables=\"web_low\"), 30)\n            assert_image_similar(im, self.roundtrip(im, qtables=\"web_high\"), 30)\n            assert_image_similar(im, self.roundtrip(im, qtables=\"keep\"), 30)\n\n            # valid bounds for baseline qtable\n            bounds_qtable = [int(s) for s in (\"255 1 \" * 32).split(None)]\n            self.roundtrip(im, qtables=[bounds_qtable])\n\n            # values from wizard.txt in jpeg9-a src package.\n            standard_l_qtable = [\n                int(s)\n                for s in \"\"\"\n                16  11  10  16  24  40  51  61\n                12  12  14  19  26  58  60  55\n                14  13  16  24  40  57  69  56\n                14  17  22  29  51  87  80  62\n                18  22  37  56  68 109 103  77\n                24  35  55  64  81 104 113  92\n                49  64  78  87 103 121 120 101\n                72  92  95  98 112 100 103  99\n                \"\"\".split(\n                    None\n                )\n            ]\n\n            standard_chrominance_qtable = [\n                int(s)\n                for s in \"\"\"\n                17  18  24  47  99  99  99  99\n                18  21  26  66  99  99  99  99\n                24  26  56  99  99  99  99  99\n                47  66  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                99  99  99  99  99  99  99  99\n                \"\"\".split(\n                    None\n                )\n            ]\n            # list of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables=[standard_l_qtable, standard_chrominance_qtable]\n                ),\n                30,\n            )\n\n            # tuple of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables=(standard_l_qtable, standard_chrominance_qtable)\n                ),\n                30,\n            )\n\n            # dict of qtable lists\n            assert_image_similar(\n                im,\n                self.roundtrip(\n                    im, qtables={0: standard_l_qtable, 1: standard_chrominance_qtable}\n                ),\n                30,\n            )\n\n            _n_qtables_helper(1, \"Tests/images/hopper_gray.jpg\")\n            _n_qtables_helper(1, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(2, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(3, \"Tests/images/pil_sample_rgb.jpg\")\n            _n_qtables_helper(1, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(2, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(3, \"Tests/images/pil_sample_cmyk.jpg\")\n            _n_qtables_helper(4, \"Tests/images/pil_sample_cmyk.jpg\")\n\n            # not a sequence\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=\"a\")\n            # sequence wrong length\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[])\n            # sequence wrong length\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[1, 2, 3, 4, 5])\n\n            # qtable entry not a sequence\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[1])\n            # qtable entry has wrong number of items\n            with pytest.raises(ValueError):\n                self.roundtrip(im, qtables=[[1, 2, 3, 4]])\n\n    @pytest.mark.skipif(not djpeg_available(), reason=\"djpeg not available\")\n    def test_load_djpeg(self):\n        with Image.open(TEST_FILE) as img:\n            img.load_djpeg()\n            assert_image_similar(img, Image.open(TEST_FILE), 5)\n\n    @pytest.mark.skipif(not cjpeg_available(), reason=\"cjpeg not available\")\n    def test_save_cjpeg(self, tmp_path):\n        with Image.open(TEST_FILE) as img:\n            tempfile = str(tmp_path / \"temp.jpg\")\n            JpegImagePlugin._save_cjpeg(img, 0, tempfile)\n            # Default save quality is 75%, so a tiny bit of difference is alright\n            assert_image_similar(img, Image.open(tempfile), 17)\n\n    def test_no_duplicate_0x1001_tag(self):\n        # Arrange\n        tag_ids = {v: k for k, v in ExifTags.TAGS.items()}\n\n        # Assert\n        assert tag_ids[\"RelatedImageWidth\"] == 0x1001\n        assert tag_ids[\"RelatedImageLength\"] == 0x1002\n\n    def test_MAXBLOCK_scaling(self, tmp_path):\n        im = self.gen_random_image((512, 512))\n        f = str(tmp_path / \"temp.jpeg\")\n        im.save(f, quality=100, optimize=True)\n\n        with Image.open(f) as reloaded:\n            # none of these should crash\n            reloaded.save(f, quality=\"keep\")\n            reloaded.save(f, quality=\"keep\", progressive=True)\n            reloaded.save(f, quality=\"keep\", optimize=True)\n\n    def test_bad_mpo_header(self):\n        \"\"\" Treat unknown MPO as JPEG \"\"\"\n        # Arrange\n\n        # Act\n        # Shouldn't raise error\n        fn = \"Tests/images/sugarshack_bad_mpo_header.jpg\"\n        with pytest.warns(UserWarning, Image.open, fn) as im:\n\n            # Assert\n            assert im.format == \"JPEG\"\n\n    def test_save_correct_modes(self):\n        out = BytesIO()\n        for mode in [\"1\", \"L\", \"RGB\", \"RGBX\", \"CMYK\", \"YCbCr\"]:\n            img = Image.new(mode, (20, 20))\n            img.save(out, \"JPEG\")\n\n    def test_save_wrong_modes(self):\n        # ref https://github.com/python-pillow/Pillow/issues/2005\n        out = BytesIO()\n        for mode in [\"LA\", \"La\", \"RGBA\", \"RGBa\", \"P\"]:\n            img = Image.new(mode, (20, 20))\n            with pytest.raises(OSError):\n                img.save(out, \"JPEG\")\n\n    def test_save_tiff_with_dpi(self, tmp_path):\n        # Arrange\n        outfile = str(tmp_path / \"temp.tif\")\n        with Image.open(\"Tests/images/hopper.tif\") as im:\n\n            # Act\n            im.save(outfile, \"JPEG\", dpi=im.info[\"dpi\"])\n\n            # Assert\n            with Image.open(outfile) as reloaded:\n                reloaded.load()\n                assert im.info[\"dpi\"] == reloaded.info[\"dpi\"]\n\n    def test_load_dpi_rounding(self):\n        # Round up\n        with Image.open(\"Tests/images/iptc_roundUp.jpg\") as im:\n            assert im.info[\"dpi\"] == (44, 44)\n\n        # Round down\n        with Image.open(\"Tests/images/iptc_roundDown.jpg\") as im:\n            assert im.info[\"dpi\"] == (2, 2)\n\n    def test_save_dpi_rounding(self, tmp_path):\n        outfile = str(tmp_path / \"temp.jpg\")\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            im.save(outfile, dpi=(72.2, 72.2))\n\n            with Image.open(outfile) as reloaded:\n                assert reloaded.info[\"dpi\"] == (72, 72)\n\n            im.save(outfile, dpi=(72.8, 72.8))\n\n        with Image.open(outfile) as reloaded:\n            assert reloaded.info[\"dpi\"] == (73, 73)\n\n    def test_dpi_tuple_from_exif(self):\n        # Arrange\n        # This Photoshop CC 2017 image has DPI in EXIF not metadata\n        # EXIF XResolution is (2000000, 10000)\n        with Image.open(\"Tests/images/photoshop-200dpi.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (200, 200)\n\n    def test_dpi_int_from_exif(self):\n        # Arrange\n        # This image has DPI in EXIF not metadata\n        # EXIF XResolution is 72\n        with Image.open(\"Tests/images/exif-72dpi-int.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_dpi_from_dpcm_exif(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with EXIF resolution unit set to cm:\n        # exiftool -exif:ResolutionUnit=cm photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/exif-200dpcm.jpg\") as im:\n\n            # Act / Assert\n            assert im.info.get(\"dpi\") == (508, 508)\n\n    def test_dpi_exif_zero_division(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with EXIF resolution set to 0/0:\n        # exiftool -XResolution=0/0 -YResolution=0/0 photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/exif-dpi-zerodivision.jpg\") as im:\n\n            # Act / Assert\n            # This should return the default, and not raise a ZeroDivisionError\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_no_dpi_in_exif(self):\n        # Arrange\n        # This is photoshop-200dpi.jpg with resolution removed from EXIF:\n        # exiftool \"-*resolution*\"= photoshop-200dpi.jpg\n        with Image.open(\"Tests/images/no-dpi-in-exif.jpg\") as im:\n\n            # Act / Assert\n            # \"When the image resolution is unknown, 72 [dpi] is designated.\"\n            # http://www.exiv2.org/tags.html\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_invalid_exif(self):\n        # This is no-dpi-in-exif with the tiff header of the exif block\n        # hexedited from MM * to FF FF FF FF\n        with Image.open(\"Tests/images/invalid-exif.jpg\") as im:\n\n            # This should return the default, and not a SyntaxError or\n            # OSError for unidentified image.\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_exif_x_resolution(self, tmp_path):\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            exif = im.getexif()\n            assert exif[282] == 180\n\n            out = str(tmp_path / \"out.jpg\")\n            with pytest.warns(None) as record:\n                im.save(out, exif=exif)\n            assert len(record) == 0\n\n        with Image.open(out) as reloaded:\n            assert reloaded.getexif()[282] == 180\n\n    def test_invalid_exif_x_resolution(self):\n        # When no x or y resolution is defined in EXIF\n        with Image.open(\"Tests/images/invalid-exif-without-x-resolution.jpg\") as im:\n\n            # This should return the default, and not a ValueError or\n            # OSError for an unidentified image.\n            assert im.info.get(\"dpi\") == (72, 72)\n\n    def test_ifd_offset_exif(self):\n        # Arrange\n        # This image has been manually hexedited to have an IFD offset of 10,\n        # in contrast to normal 8\n        with Image.open(\"Tests/images/exif-ifd-offset.jpg\") as im:\n\n            # Act / Assert\n            assert im._getexif()[306] == \"2017:03:13 23:03:09\"\n\n    def test_photoshop(self):\n        with Image.open(\"Tests/images/photoshop-200dpi.jpg\") as im:\n            assert im.info[\"photoshop\"][0x03ED] == {\n                \"XResolution\": 200.0,\n                \"DisplayedUnitsX\": 1,\n                \"YResolution\": 200.0,\n                \"DisplayedUnitsY\": 1,\n            }\n\n            # Test that the image can still load, even with broken Photoshop data\n            # This image had the APP13 length hexedited to be smaller\n            with Image.open(\"Tests/images/photoshop-200dpi-broken.jpg\") as im_broken:\n                assert_image_equal(im_broken, im)\n\n        # This image does not contain a Photoshop header string\n        with Image.open(\"Tests/images/app13.jpg\") as im:\n            assert \"photoshop\" not in im.info\n\n    def test_photoshop_malformed_and_multiple(self):\n        with Image.open(\"Tests/images/app13-multiple.jpg\") as im:\n            assert \"photoshop\" in im.info\n            assert 24 == len(im.info[\"photoshop\"])\n            apps_13_lengths = [len(v) for k, v in im.applist if k == \"APP13\"]\n            assert [65504, 24] == apps_13_lengths\n\n    def test_icc_after_SOF(self):\n        with Image.open(\"Tests/images/icc-after-SOF.jpg\") as im:\n            assert im.info[\"icc_profile\"] == b\"profile\"\n\n\n@pytest.mark.skipif(not is_win32(), reason=\"Windows only\")\n@skip_unless_feature(\"jpg\")\nclass TestFileCloseW32:\n    def test_fd_leak(self, tmp_path):\n        tmpfile = str(tmp_path / \"temp.jpg\")\n\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            im.save(tmpfile)\n\n        im = Image.open(tmpfile)\n        fp = im.fp\n        assert not fp.closed\n        with pytest.raises(OSError):\n            os.remove(tmpfile)\n        im.load()\n        assert fp.closed\n        # this should not fail, as load should have closed the file.\n        os.remove(tmpfile)\n"
    ],
    "test_file_names": [
        "test_1.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 19ms\nInstalled 12 packages in 107ms\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 1 package in 713ms\nPrepared 1 package in 32.05s\nInstalled 1 package in 1ms\n + pillow==7.2.0.dev0 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/pillow_794e9f0f0e85535e6bd1791e2ec127dec345f319)\n",
    "new_commit_res_code": 1,
    "new_commit_res_stdout": "============================= test session starts ==============================\nplatform linux -- Python 3.9.21, pytest-8.3.4, pluggy-1.5.0\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/pillow_794e9f0f0e85535e6bd1791e2ec127dec345f319\nconfigfile: setup.cfg\nplugins: cov-6.0.0\ncollected 53 items\n\nr2e_tests/test_1.py ..............................ss..............F..... [ 98%]\ns                                                                        [100%]\n\n=================================== FAILURES ===================================\n_____________________ TestFileJpeg.test_exif_x_resolution ______________________\n\nself = <r2e_tests.test_1.TestFileJpeg object at 0x717b03a11730>\ntmp_path = PosixPath('/tmp/pytest-of-gcpuser/pytest-364/test_exif_x_resolution0')\n\n    def test_exif_x_resolution(self, tmp_path):\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            exif = im.getexif()\n            assert exif[282] == 180\n    \n            out = str(tmp_path / \"out.jpg\")\n>           with pytest.warns(None) as record:\n\nr2e_tests/test_1.py:656: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = WarningsChecker(record=True), expected_warning = None, match_expr = None\n\n    def __init__(\n        self,\n        expected_warning: type[Warning] | tuple[type[Warning], ...] = Warning,\n        match_expr: str | Pattern[str] | None = None,\n        *,\n        _ispytest: bool = False,\n    ) -> None:\n        check_ispytest(_ispytest)\n        super().__init__(_ispytest=True)\n    \n        msg = \"exceptions must be derived from Warning, not %s\"\n        if isinstance(expected_warning, tuple):\n            for exc in expected_warning:\n                if not issubclass(exc, Warning):\n                    raise TypeError(msg % type(exc))\n            expected_warning_tup = expected_warning\n        elif isinstance(expected_warning, type) and issubclass(\n            expected_warning, Warning\n        ):\n            expected_warning_tup = (expected_warning,)\n        else:\n>           raise TypeError(msg % type(expected_warning))\nE           TypeError: exceptions must be derived from Warning, not <class 'NoneType'>\n\n.venv/lib/python3.9/site-packages/_pytest/recwarn.py:279: TypeError\n==================================== PASSES ====================================\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_sanity\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_app\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_cmyk\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_dpi\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_icc\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_icc_big\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_large_icc_meta\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_optimize\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_optimize_large_buffer\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_progressive\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_progressive_large_buffer\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_progressive_large_buffer_highest_quality\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_progressive_cmyk_buffer\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_large_exif\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_exif_typeerror\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_exif_gps\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_exif_rollback\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_exif_gps_typeerror\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_progressive_compat\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_quality\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_smooth\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_subsampling\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_exif\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_mp\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_quality_keep\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_junk_jpeg_header\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_ff00_jpeg_header\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_truncated_jpeg_should_read_all_the_data\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_truncated_jpeg_throws_oserror\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_qtables\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_no_duplicate_0x1001_tag\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_MAXBLOCK_scaling\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_bad_mpo_header\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_save_correct_modes\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_save_wrong_modes\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_save_tiff_with_dpi\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_load_dpi_rounding\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_save_dpi_rounding\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_dpi_tuple_from_exif\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_dpi_int_from_exif\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_dpi_from_dpcm_exif\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_dpi_exif_zero_division\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_no_dpi_in_exif\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_invalid_exif\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_invalid_exif_x_resolution\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_ifd_offset_exif\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_photoshop\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_photoshop_malformed_and_multiple\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_icc_after_SOF\nSKIPPED [1] r2e_tests/test_1.py:499: djpeg not available\nSKIPPED [1] r2e_tests/test_1.py:505: cjpeg not available\nSKIPPED [1] r2e_tests/test_1.py:713: Windows only\nFAILED r2e_tests/test_1.py::TestFileJpeg::test_exif_x_resolution - TypeError:...\n=================== 1 failed, 49 passed, 3 skipped in 0.79s ====================\n",
    "new_commit_res_stderr": "",
    "old_commit_res_code": 1,
    "old_commit_res_stdout": "============================= test session starts ==============================\nplatform linux -- Python 3.9.21, pytest-8.3.4, pluggy-1.5.0\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/pillow_794e9f0f0e85535e6bd1791e2ec127dec345f319\nconfigfile: setup.cfg\nplugins: cov-6.0.0\ncollected 53 items\n\nr2e_tests/test_1.py ...............FF.............ss..............F..... [ 98%]\ns                                                                        [100%]\n\n=================================== FAILURES ===================================\n__________________________ TestFileJpeg.test_exif_gps __________________________\n\nself = <r2e_tests.test_1.TestFileJpeg object at 0x7dcf2d82b4c0>\n\n    def test_exif_gps(self):\n        # Arrange\n        with Image.open(\"Tests/images/exif_gps.jpg\") as im:\n            gps_index = 34853\n            expected_exif_gps = {\n                0: b\"\\x00\\x00\\x00\\x01\",\n                2: 4294967295,\n                5: b\"\\x01\",\n                30: 65535,\n                29: \"1999:99:99 99:99:99\",\n            }\n    \n            # Act\n            exif = im._getexif()\n    \n        # Assert\n>       assert exif[gps_index] == expected_exif_gps\nE       AssertionError: assert {0: b'\\x00\\x0...9:99:99', ...} == {0: b'\\x00\\x0...9:99:99', ...}\nE         \nE         Omitting 4 identical items, use -vv to show\nE         Differing items:\nE         {2: (4294967295, 1)} != {2: 4294967295}\nE         Use -v to get more diff\n\nr2e_tests/test_1.py:232: AssertionError\n_______________________ TestFileJpeg.test_exif_rollback ________________________\n\nself = <r2e_tests.test_1.TestFileJpeg object at 0x7dcf2d82b130>\n\n    def test_exif_rollback(self):\n        # rolling back exif support in 3.1 to pre-3.0 formatting.\n        # expected from 2.9, with b/u qualifiers switched for 3.2 compatibility\n        # this test passes on 2.9 and 3.1, but not 3.0\n        expected_exif = {\n            34867: 4294967295,\n            258: (24, 24, 24),\n            36867: \"2099:09:29 10:10:10\",\n            34853: {\n                0: b\"\\x00\\x00\\x00\\x01\",\n                2: 4294967295,\n                5: b\"\\x01\",\n                30: 65535,\n                29: \"1999:99:99 99:99:99\",\n            },\n            296: 65535,\n            34665: 185,\n            41994: 65535,\n            514: 4294967295,\n            271: \"Make\",\n            272: \"XXX-XXX\",\n            305: \"PIL\",\n            42034: (1, 1, 1, 1),\n            42035: \"LensMake\",\n            34856: b\"\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa\",\n            282: 4294967295,\n            33434: 4294967295,\n        }\n    \n        with Image.open(\"Tests/images/exif_gps.jpg\") as im:\n            exif = im._getexif()\n    \n        for tag, value in expected_exif.items():\n>           assert value == exif[tag]\nE           AssertionError: assert {0: b'\\x00\\x0...9:99:99', ...} == {0: b'\\x00\\x0...9:99:99', ...}\nE             \nE             Omitting 4 identical items, use -vv to show\nE             Differing items:\nE             {2: 4294967295} != {2: (4294967295, 1)}\nE             Use -v to get more diff\n\nr2e_tests/test_1.py:267: AssertionError\n_____________________ TestFileJpeg.test_exif_x_resolution ______________________\n\nself = <r2e_tests.test_1.TestFileJpeg object at 0x7dcf2d7bf9a0>\ntmp_path = PosixPath('/tmp/pytest-of-gcpuser/pytest-373/test_exif_x_resolution0')\n\n    def test_exif_x_resolution(self, tmp_path):\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            exif = im.getexif()\n>           assert exif[282] == 180\nE           assert (180, 1) == 180\n\nr2e_tests/test_1.py:653: AssertionError\n==================================== PASSES ====================================\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_sanity\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_app\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_cmyk\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_dpi\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_icc\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_icc_big\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_large_icc_meta\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_optimize\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_optimize_large_buffer\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_progressive\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_progressive_large_buffer\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_progressive_large_buffer_highest_quality\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_progressive_cmyk_buffer\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_large_exif\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_exif_typeerror\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_exif_gps_typeerror\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_progressive_compat\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_quality\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_smooth\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_subsampling\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_exif\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_mp\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_quality_keep\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_junk_jpeg_header\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_ff00_jpeg_header\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_truncated_jpeg_should_read_all_the_data\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_truncated_jpeg_throws_oserror\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_qtables\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_no_duplicate_0x1001_tag\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_MAXBLOCK_scaling\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_bad_mpo_header\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_save_correct_modes\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_save_wrong_modes\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_save_tiff_with_dpi\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_load_dpi_rounding\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_save_dpi_rounding\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_dpi_tuple_from_exif\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_dpi_int_from_exif\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_dpi_from_dpcm_exif\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_dpi_exif_zero_division\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_no_dpi_in_exif\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_invalid_exif\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_invalid_exif_x_resolution\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_ifd_offset_exif\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_photoshop\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_photoshop_malformed_and_multiple\nPASSED r2e_tests/test_1.py::TestFileJpeg::test_icc_after_SOF\nSKIPPED [1] r2e_tests/test_1.py:499: djpeg not available\nSKIPPED [1] r2e_tests/test_1.py:505: cjpeg not available\nSKIPPED [1] r2e_tests/test_1.py:713: Windows only\nFAILED r2e_tests/test_1.py::TestFileJpeg::test_exif_gps - AssertionError: ass...\nFAILED r2e_tests/test_1.py::TestFileJpeg::test_exif_rollback - AssertionError...\nFAILED r2e_tests/test_1.py::TestFileJpeg::test_exif_x_resolution - assert (18...\n=================== 3 failed, 47 passed, 3 skipped in 0.70s ====================\n",
    "old_commit_res_stderr": ""
}
Tests/test_file_jpeg.py src/PIL/Image.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** Setting EXIF X-Resolution Causes TypeError During Image Save

**Description:**
When attempting to set the EXIF `XResolution` to an integer value and save the image, a `TypeError` is raised unexpectedly. This issue occurs even though the `XResolution` should accept integer values and handle them correctly during the save operation.

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

def set_exif_x_resolution(image_path, output_path):
    with Image.open(image_path) as img:
        exif = img.getexif()
        exif[282] = 180  # Set XResolution to 180
        img.save(output_path, exif=exif)

set_exif_x_resolution("flower.jpg", "out.jpg")
```

**Expected Behavior:**
The image should be saved successfully with the `XResolution` EXIF tag set to `180`. The operation should complete without any errors, and the saved image should retain the specified resolution metadata.

**Actual Behavior:**
A `TypeError` is raised during the save operation, preventing the image from being saved with the updated EXIF data. This error suggests that the EXIF `XResolution` value is not being handled correctly when assigned an integer.

[/ISSUE]
--- END ISSUE ---

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

--- BEGIN FILE ---
```
### src/PIL/Image.py
#
# The Python Imaging Library.
# $Id$
#
# the Image class wrapper
#
# partial release history:
# 1995-09-09 fl   Created
# 1996-03-11 fl   PIL release 0.0 (proof of concept)
# 1996-04-30 fl   PIL release 0.1b1
# 1999-07-28 fl   PIL release 1.0 final
# 2000-06-07 fl   PIL release 1.1
# 2000-10-20 fl   PIL release 1.1.1
# 2001-05-07 fl   PIL release 1.1.2
# 2002-03-15 fl   PIL release 1.1.3
# 2003-05-10 fl   PIL release 1.1.4
# 2005-03-28 fl   PIL release 1.1.5
# 2006-12-02 fl   PIL release 1.1.6
# 2009-11-15 fl   PIL release 1.1.7
#
# Copyright (c) 1997-2009 by Secret Labs AB.  All rights reserved.
# Copyright (c) 1995-2009 by Fredrik Lundh.
#
# See the README file for information on usage and redistribution.
#

import atexit
import builtins
import io
import logging
import math
import numbers
import os
import struct
import sys
import tempfile
import warnings
import xml.etree.ElementTree
from collections.abc import Callable, MutableMapping
from pathlib import Path

# VERSION was removed in Pillow 6.0.0.
# PILLOW_VERSION is deprecated and will be removed in a future release.
# Use __version__ instead.
from . import (
    ImageMode,
    TiffTags,
    UnidentifiedImageError,
    __version__,
    _plugins,
    _raise_version_warning,
)
from ._binary import i8, i32le
from ._util import deferred_error, isPath

if sys.version_info >= (3, 7):

    def __getattr__(name):
        if name == "PILLOW_VERSION":
            _raise_version_warning()
            return __version__
        raise AttributeError("module '{}' has no attribute '{}'".format(__name__, name))


else:

    from . import PILLOW_VERSION

    # Silence warning
    assert PILLOW_VERSION


logger = logging.getLogger(__name__)


class DecompressionBombWarning(RuntimeWarning):
    pass


class DecompressionBombError(Exception):
    pass


# Limit to around a quarter gigabyte for a 24 bit (3 bpp) image
MAX_IMAGE_PIXELS = int(1024 * 1024 * 1024 // 4 // 3)


try:
    # If the _imaging C module is not present, Pillow will not load.
    # Note that other modules should not refer to _imaging directly;
    # import Image and use the Image.core variable instead.
    # Also note that Image.core is not a publicly documented interface,
    # and should be considered private and subject to change.
    from . import _imaging as core

    if __version__ != getattr(core, "PILLOW_VERSION", None):
        raise ImportError(
            "The _imaging extension was built for another version of Pillow or PIL:\n"
            "Core version: %s\n"
            "Pillow version: %s" % (getattr(core, "PILLOW_VERSION", None), __version__)
        )

except ImportError as v:
    core = deferred_error(ImportError("The _imaging C module is not installed."))
    # Explanations for ways that we know we might have an import error
    if str(v).startswith("Module use of python"):
        # The _imaging C module is present, but not compiled for
        # the right version (windows only).  Print a warning, if
        # possible.
        warnings.warn(
            "The _imaging extension was built for another version of Python.",
            RuntimeWarning,
        )
    elif str(v).startswith("The _imaging extension"):
        warnings.warn(str(v), RuntimeWarning)
    # Fail here anyway. Don't let people run with a mostly broken Pillow.
    # see docs/porting.rst
    raise


# works everywhere, win for pypy, not cpython
USE_CFFI_ACCESS = hasattr(sys, "pypy_version_info")
try:
    import cffi
except ImportError:
    cffi = None


def isImageType(t):
    """
    Checks if an object is an image object.

    .. warning::

       This function is for internal use only.

    :param t: object to check if it's an image
    :returns: True if the object is an image
    """
    return hasattr(t, "im")


#
# Constants

NONE = 0

# transpose
FLIP_LEFT_RIGHT = 0
FLIP_TOP_BOTTOM = 1
ROTATE_90 = 2
ROTATE_180 = 3
ROTATE_270 = 4
TRANSPOSE = 5
TRANSVERSE = 6

# transforms (also defined in Imaging.h)
AFFINE = 0
EXTENT = 1
PERSPECTIVE = 2
QUAD = 3
MESH = 4

# resampling filters (also defined in Imaging.h)
NEAREST = NONE = 0
BOX = 4
BILINEAR = LINEAR = 2
HAMMING = 5
BICUBIC = CUBIC = 3
LANCZOS = ANTIALIAS = 1

_filters_support = {BOX: 0.5, BILINEAR: 1.0, HAMMING: 1.0, BICUBIC: 2.0, LANCZOS: 3.0}


# dithers
NEAREST = NONE = 0
ORDERED = 1  # Not yet implemented
RASTERIZE = 2  # Not yet implemented
FLOYDSTEINBERG = 3  # default

# palettes/quantizers
WEB = 0
ADAPTIVE = 1

MEDIANCUT = 0
MAXCOVERAGE = 1
FASTOCTREE = 2
LIBIMAGEQUANT = 3

# categories
NORMAL = 0
SEQUENCE = 1
CONTAINER = 2

if hasattr(core, "DEFAULT_STRATEGY"):
    DEFAULT_STRATEGY = core.DEFAULT_STRATEGY
    FILTERED = core.FILTERED
    HUFFMAN_ONLY = core.HUFFMAN_ONLY
    RLE = core.RLE
    FIXED = core.FIXED


# --------------------------------------------------------------------
# Registries

ID = []
OPEN = {}
MIME = {}
SAVE = {}
SAVE_ALL = {}
EXTENSION = {}
DECODERS = {}
ENCODERS = {}

# --------------------------------------------------------------------
# Modes supported by this version

_MODEINFO = {
    # NOTE: this table will be removed in future versions.  use
    # getmode* functions or ImageMode descriptors instead.
    # official modes
    "1": ("L", "L", ("1",)),
    "L": ("L", "L", ("L",)),
    "I": ("L", "I", ("I",)),
    "F": ("L", "F", ("F",)),
    "P": ("P", "L", ("P",)),
    "RGB": ("RGB", "L", ("R", "G", "B")),
    "RGBX": ("RGB", "L", ("R", "G", "B", "X")),
    "RGBA": ("RGB", "L", ("R", "G", "B", "A")),
    "CMYK": ("RGB", "L", ("C", "M", "Y", "K")),
    "YCbCr": ("RGB", "L", ("Y", "Cb", "Cr")),
    "LAB": ("RGB", "L", ("L", "A", "B")),
    "HSV": ("RGB", "L", ("H", "S", "V")),
    # Experimental modes include I;16, I;16L, I;16B, RGBa, BGR;15, and
    # BGR;24.  Use these modes only if you know exactly what you're
    # doing...
}

if sys.byteorder == "little":
    _ENDIAN = "<"
else:
    _ENDIAN = ">"

_MODE_CONV = {
    # official modes
    "1": ("|b1", None),  # Bits need to be extended to bytes
    "L": ("|u1", None),
    "LA": ("|u1", 2),
    "I": (_ENDIAN + "i4", None),
    "F": (_ENDIAN + "f4", None),
    "P": ("|u1", None),
    "RGB": ("|u1", 3),
    "RGBX": ("|u1", 4),
    "RGBA": ("|u1", 4),
    "CMYK": ("|u1", 4),
    "YCbCr": ("|u1", 3),
    "LAB": ("|u1", 3),  # UNDONE - unsigned |u1i1i1
    "HSV": ("|u1", 3),
    # I;16 == I;16L, and I;32 == I;32L
    "I;16": ("<u2", None),
    "I;16B": (">u2", None),
    "I;16L": ("<u2", None),
    "I;16S": ("<i2", None),
    "I;16BS": (">i2", None),
    "I;16LS": ("<i2", None),
    "I;32": ("<u4", None),
    "I;32B": (">u4", None),
    "I;32L": ("<u4", None),
    "I;32S": ("<i4", None),
    "I;32BS": (">i4", None),
    "I;32LS": ("<i4", None),
}


def _conv_type_shape(im):
    typ, extra = _MODE_CONV[im.mode]
    if extra is None:
        return (im.size[1], im.size[0]), typ
    else:
        return (im.size[1], im.size[0], extra), typ


MODES = sorted(_MODEINFO)

# raw modes that may be memory mapped.  NOTE: if you change this, you
# may have to modify the stride calculation in map.c too!
_MAPMODES = ("L", "P", "RGBX", "RGBA", "CMYK", "I;16", "I;16L", "I;16B")


def getmodebase(mode):
    """
    Gets the "base" mode for given mode.  This function returns "L" for
    images that contain grayscale data, and "RGB" for images that
    contain color data.

    :param mode: Input mode.
    :returns: "L" or "RGB".
    :exception KeyError: If the input mode was not a standard mode.
    """
    return ImageMode.getmode(mode).basemode


def getmodetype(mode):
    """
    Gets the storage type mode.  Given a mode, this function returns a
    single-layer mode suitable for storing individual bands.

    :param mode: Input mode.
    :returns: "L", "I", or "F".
    :exception KeyError: If the input mode was not a standard mode.
    """
    return ImageMode.getmode(mode).basetype


def getmodebandnames(mode):
    """
    Gets a list of individual band names.  Given a mode, this function returns
    a tuple containing the names of individual bands (use
    :py:method:`~PIL.Image.getmodetype` to get the mode used to store each
    individual band.

    :param mode: Input mode.
    :returns: A tuple containing band names.  The length of the tuple
        gives the number of bands in an image of the given mode.
    :exception KeyError: If the input mode was not a standard mode.
    """
    return ImageMode.getmode(mode).bands


def getmodebands(mode):
    """
    Gets the number of individual bands for this mode.

    :param mode: Input mode.
    :returns: The number of bands in this mode.
    :exception KeyError: If the input mode was not a standard mode.
    """
    return len(ImageMode.getmode(mode).bands)


# --------------------------------------------------------------------
# Helpers

_initialized = 0


def preinit():
    """Explicitly load standard file format drivers."""

    global _initialized
    if _initialized >= 1:
        return

    try:
        from . import BmpImagePlugin

        assert BmpImagePlugin
    except ImportError:
        pass
    try:
        from . import GifImagePlugin

        assert GifImagePlugin
    except ImportError:
        pass
    try:
        from . import JpegImagePlugin

        assert JpegImagePlugin
    except ImportError:
        pass
    try:
        from . import PpmImagePlugin

        assert PpmImagePlugin
    except ImportError:
        pass
    try:
        from . import PngImagePlugin

        assert PngImagePlugin
    except ImportError:
        pass
    # try:
    #     import TiffImagePlugin
    #     assert TiffImagePlugin
    # except ImportError:
    #     pass

    _initialized = 1


def init():
    """
    Explicitly initializes the Python Imaging Library. This function
    loads all available file format drivers.
    """

    global _initialized
    if _initialized >= 2:
        return 0

    for plugin in _plugins:
        try:
            logger.debug("Importing %s", plugin)
            __import__("PIL.%s" % plugin, globals(), locals(), [])
        except ImportError as e:
            logger.debug("Image: failed to import %s: %s", plugin, e)

    if OPEN or SAVE:
        _initialized = 2
        return 1


# --------------------------------------------------------------------
# Codec factories (used by tobytes/frombytes and ImageFile.load)


def _getdecoder(mode, decoder_name, args, extra=()):

    # tweak arguments
    if args is None:
        args = ()
    elif not isinstance(args, tuple):
        args = (args,)

    try:
        decoder = DECODERS[decoder_name]
    except KeyError:
        pass
    else:
        return decoder(mode, *args + extra)

    try:
        # get decoder
        decoder = getattr(core, decoder_name + "_decoder")
    except AttributeError:
        raise OSError("decoder %s not available" % decoder_name)
    return decoder(mode, *args + extra)


def _getencoder(mode, encoder_name, args, extra=()):

    # tweak arguments
    if args is None:
        args = ()
    elif not isinstance(args, tuple):
        args = (args,)

    try:
        encoder = ENCODERS[encoder_name]
    except KeyError:
        pass
    else:
        return encoder(mode, *args + extra)

    try:
        # get encoder
        encoder = getattr(core, encoder_name + "_encoder")
    except AttributeError:
        raise OSError("encoder %s not available" % encoder_name)
    return encoder(mode, *args + extra)


# --------------------------------------------------------------------
# Simple expression analyzer


def coerce_e(value):
    return value if isinstance(value, _E) else _E(value)


class _E:
    def __init__(self, data):
        self.data = data

    def __add__(self, other):
        return _E((self.data, "__add__", coerce_e(other).data))

    def __mul__(self, other):
        return _E((self.data, "__mul__", coerce_e(other).data))


def _getscaleoffset(expr):
    stub = ["stub"]
    data = expr(_E(stub)).data
    try:
        (a, b, c) = data  # simplified syntax
        if a is stub and b == "__mul__" and isinstance(c, numbers.Number):
            return c, 0.0
        if a is stub and b == "__add__" and isinstance(c, numbers.Number):
            return 1.0, c
    except TypeError:
        pass
    try:
        ((a, b, c), d, e) = data  # full syntax
        if (
            a is stub
            and b == "__mul__"
            and isinstance(c, numbers.Number)
            and d == "__add__"
            and isinstance(e, numbers.Number)
        ):
            return c, e
    except TypeError:
        pass
    raise ValueError("illegal expression")


# --------------------------------------------------------------------
# Implementation wrapper


class Image:
    """
    This class represents an image object.  To create
    :py:class:`~PIL.Image.Image` objects, use the appropriate factory
    functions.  There's hardly ever any reason to call the Image constructor
    directly.

    * :py:func:`~PIL.Image.open`
    * :py:func:`~PIL.Image.new`
    * :py:func:`~PIL.Image.frombytes`
    """

    format = None
    format_description = None
    _close_exclusive_fp_after_loading = True

    def __init__(self):
        # FIXME: take "new" parameters / other image?
        # FIXME: turn mode and size into delegating properties?
        self.im = None
        self.mode = ""
        self._size = (0, 0)
        self.palette = None
        self.info = {}
        self.category = NORMAL
        self.readonly = 0
        self.pyaccess = None
        self._exif = None

    @property
    def width(self):
        return self.size[0]

    @property
    def height(self):
        return self.size[1]

    @property
    def size(self):
        return self._size

    def _new(self, im):
        new = Image()
        new.im = im
        new.mode = im.mode
        new._size = im.size
        if im.mode in ("P", "PA"):
            if self.palette:
                new.palette = self.palette.copy()
            else:
                from . import ImagePalette

                new.palette = ImagePalette.ImagePalette()
        new.info = self.info.copy()
        return new

    # Context manager support
    def __enter__(self):
        return self

    def __exit__(self, *args):
        if hasattr(self, "fp") and getattr(self, "_exclusive_fp", False):
            if hasattr(self, "_close__fp"):
                self._close__fp()
            if self.fp:
                self.fp.close()
        self.fp = None

    def close(self):
        """
        Closes the file pointer, if possible.

        This operation will destroy the image core and release its memory.
        The image data will be unusable afterward.

        This function is only required to close images that have not
        had their file read and closed by the
        :py:meth:`~PIL.Image.Image.load` method. See
        :ref:`file-handling` for more information.
        """
        try:
            if hasattr(self, "_close__fp"):
                self._close__fp()
            self.fp.close()
            self.fp = None
        except Exception as msg:
            logger.debug("Error closing: %s", msg)

        if getattr(self, "map", None):
            self.map = None

        # Instead of simply setting to None, we're setting up a
        # deferred error that will better explain that the core image
        # object is gone.
        self.im = deferred_error(ValueError("Operation on closed image"))

    def _copy(self):
        self.load()
        self.im = self.im.copy()
        self.pyaccess = None
        self.readonly = 0

    def _ensure_mutable(self):
        if self.readonly:
            self._copy()
        else:
            self.load()

    def _dump(self, file=None, format=None, **options):
        suffix = ""
        if format:
            suffix = "." + format

        if not file:
            f, filename = tempfile.mkstemp(suffix)
            os.close(f)
        else:
            filename = file
            if not filename.endswith(suffix):
                filename = filename + suffix

        self.load()

        if not format or format == "PPM":
            self.im.save_ppm(filename)
        else:
            self.save(filename, format, **options)

        return filename

    def __eq__(self, other):
        return (
            self.__class__ is other.__class__
            and self.mode == other.mode
            and self.size == other.size
            and self.info == other.info
            and self.category == other.category
            and self.readonly == other.readonly
            and self.getpalette() == other.getpalette()
            and self.tobytes() == other.tobytes()
        )

    def __repr__(self):
        return "<%s.%s image mode=%s size=%dx%d at 0x%X>" % (
            self.__class__.__module__,
            self.__class__.__name__,
            self.mode,
            self.size[0],
            self.size[1],
            id(self),
        )

    def _repr_png_(self):
        """ iPython display hook support

        :returns: png version of the image as bytes
        """
        b = io.BytesIO()
        self.save(b, "PNG")
        return b.getvalue()

    @property
    def __array_interface__(self):
        # numpy array interface support
        new = {}
        shape, typestr = _conv_type_shape(self)
        new["shape"] = shape
        new["typestr"] = typestr
        new["version"] = 3
        if self.mode == "1":
            # Binary images need to be extended from bits to bytes
            # See: https://github.com/python-pillow/Pillow/issues/350
            new["data"] = self.tobytes("raw", "L")
        else:
            new["data"] = self.tobytes()
        return new

    def __getstate__(self):
        return [self.info, self.mode, self.size, self.getpalette(), self.tobytes()]

    def __setstate__(self, state):
        Image.__init__(self)
        self.tile = []
        info, mode, size, palette, data = state
        self.info = info
        self.mode = mode
        self._size = size
        self.im = core.new(mode, size)
        if mode in ("L", "LA", "P", "PA") and palette:
            self.putpalette(palette)
        self.frombytes(data)

    def tobytes(self, encoder_name="raw", *args):
        """
        Return image as a bytes object.

        .. warning::

            This method returns the raw image data from the internal
            storage.  For compressed image data (e.g. PNG, JPEG) use
            :meth:`~.save`, with a BytesIO parameter for in-memory
            data.

        :param encoder_name: What encoder to use.  The default is to
                             use the standard "raw" encoder.
        :param args: Extra arguments to the encoder.
        :rtype: A bytes object.
        """

        # may pass tuple instead of argument list
        if len(args) == 1 and isinstance(args[0], tuple):
            args = args[0]

        if encoder_name == "raw" and args == ():
            args = self.mode

        self.load()

        # unpack data
        e = _getencoder(self.mode, encoder_name, args)
        e.setimage(self.im)

        bufsize = max(65536, self.size[0] * 4)  # see RawEncode.c

        data = []
        while True:
            l, s, d = e.encode(bufsize)
            data.append(d)
            if s:
                break
        if s < 0:
            raise RuntimeError("encoder error %d in tobytes" % s)

        return b"".join(data)

    def tostring(self, *args, **kw):
        raise NotImplementedError(
            "tostring() has been removed. Please call tobytes() instead."
        )

    def tobitmap(self, name="image"):
        """
        Returns the image converted to an X11 bitmap.

        .. note:: This method only works for mode "1" images.

        :param name: The name prefix to use for the bitmap variables.
        :returns: A string containing an X11 bitmap.
        :raises ValueError: If the mode is not "1"
        """

        self.load()
        if self.mode != "1":
            raise ValueError("not a bitmap")
        data = self.tobytes("xbm")
        return b"".join(
            [
                ("#define %s_width %d\n" % (name, self.size[0])).encode("ascii"),
                ("#define %s_height %d\n" % (name, self.size[1])).encode("ascii"),
                ("static char %s_bits[] = {\n" % name).encode("ascii"),
                data,
                b"};",
            ]
        )

    def frombytes(self, data, decoder_name="raw", *args):
        """
        Loads this image with pixel data from a bytes object.

        This method is similar to the :py:func:`~PIL.Image.frombytes` function,
        but loads data into this image instead of creating a new image object.
        """

        # may pass tuple instead of argument list
        if len(args) == 1 and isinstance(args[0], tuple):
            args = args[0]

        # default format
        if decoder_name == "raw" and args == ():
            args = self.mode

        # unpack data
        d = _getdecoder(self.mode, decoder_name, args)
        d.setimage(self.im)
        s = d.decode(data)

        if s[0] >= 0:
            raise ValueError("not enough image data")
        if s[1] != 0:
            raise ValueError("cannot decode image data")

    def fromstring(self, *args, **kw):
        raise NotImplementedError(
            "fromstring() has been removed. Please call frombytes() instead."
        )

    def load(self):
        """
        Allocates storage for the image and loads the pixel data.  In
        normal cases, you don't need to call this method, since the
        Image class automatically loads an opened image when it is
        accessed for the first time.

        If the file associated with the image was opened by Pillow, then this
        method will close it. The exception to this is if the image has
        multiple frames, in which case the file will be left open for seek
        operations. See :ref:`file-handling` for more information.

        :returns: An image access object.
        :rtype: :ref:`PixelAccess` or :py:class:`PIL.PyAccess`
        """
        if self.im and self.palette and self.palette.dirty:
            # realize palette
            self.im.putpalette(*self.palette.getdata())
            self.palette.dirty = 0
            self.palette.mode = "RGB"
            self.palette.rawmode = None
            if "transparency" in self.info:
                if isinstance(self.info["transparency"], int):
                    self.im.putpalettealpha(self.info["transparency"], 0)
                else:
                    self.im.putpalettealphas(self.info["transparency"])
                self.palette.mode = "RGBA"

        if self.im:
            if cffi and USE_CFFI_ACCESS:
                if self.pyaccess:
                    return self.pyaccess
                from . import PyAccess

                self.pyaccess = PyAccess.new(self, self.readonly)
                if self.pyaccess:
                    return self.pyaccess
            return self.im.pixel_access(self.readonly)

    def verify(self):
        """
        Verifies the contents of a file. For data read from a file, this
        method attempts to determine if the file is broken, without
        actually decoding the image data.  If this method finds any
        problems, it raises suitable exceptions.  If you need to load
        the image after using this method, you must reopen the image
        file.
        """
        pass

    def convert(self, mode=None, matrix=None, dither=None, palette=WEB, colors=256):
        """
        Returns a converted copy of this image. For the "P" mode, this
        method translates pixels through the palette.  If mode is
        omitted, a mode is chosen so that all information in the image
        and the palette can be represented without a palette.

        The current version supports all possible conversions between
        "L", "RGB" and "CMYK." The **matrix** argument only supports "L"
        and "RGB".

        When translating a color image to greyscale (mode "L"),
        the library uses the ITU-R 601-2 luma transform::

            L = R * 299/1000 + G * 587/1000 + B * 114/1000

        The default method of converting a greyscale ("L") or "RGB"
        image into a bilevel (mode "1") image uses Floyd-Steinberg
        dither to approximate the original image luminosity levels. If
        dither is NONE, all values larger than 128 are set to 255 (white),
        all other values to 0 (black). To use other thresholds, use the
        :py:meth:`~PIL.Image.Image.point` method.

        When converting from "RGBA" to "P" without a **matrix** argument,
        this passes the operation to :py:meth:`~PIL.Image.Image.quantize`,
        and **dither** and **palette** are ignored.

        :param mode: The requested mode. See: :ref:`concept-modes`.
        :param matrix: An optional conversion matrix.  If given, this
           should be 4- or 12-tuple containing floating point values.
        :param dither: Dithering method, used when converting from
           mode "RGB" to "P" or from "RGB" or "L" to "1".
           Available methods are NONE or FLOYDSTEINBERG (default).
           Note that this is not used when **matrix** is supplied.
        :param palette: Palette to use when converting from mode "RGB"
           to "P".  Available palettes are WEB or ADAPTIVE.
        :param colors: Number of colors to use for the ADAPTIVE palette.
           Defaults to 256.
        :rtype: :py:class:`~PIL.Image.Image`
        :returns: An :py:class:`~PIL.Image.Image` object.
        """

        self.load()

        if not mode and self.mode == "P":
            # determine default mode
            if self.palette:
                mode = self.palette.mode
            else:
                mode = "RGB"
        if not mode or (mode == self.mode and not matrix):
            return self.copy()

        has_transparency = self.info.get("transparency") is not None
        if matrix:
            # matrix conversion
            if mode not in ("L", "RGB"):
                raise ValueError("illegal conversion")
            im = self.im.convert_matrix(mode, matrix)
            new = self._new(im)
            if has_transparency and self.im.bands == 3:
                transparency = new.info["transparency"]

                def convert_transparency(m, v):
                    v = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * 0.5
                    return max(0, min(255, int(v)))

                if mode == "L":
                    transparency = convert_transparency(matrix, transparency)
                elif len(mode) == 3:
                    transparency = tuple(
                        [
                            convert_transparency(
                                matrix[i * 4 : i * 4 + 4], transparency
                            )
                            for i in range(0, len(transparency))
                        ]
                    )
                new.info["transparency"] = transparency
            return new

        if mode == "P" and self.mode == "RGBA":
            return self.quantize(colors)

        trns = None
        delete_trns = False
        # transparency handling
        if has_transparency:
            if self.mode in ("1", "L", "I", "RGB") and mode == "RGBA":
                # Use transparent conversion to promote from transparent
                # color to an alpha channel.
                new_im = self._new(
                    self.im.convert_transparent(mode, self.info["transparency"])
                )
                del new_im.info["transparency"]
                return new_im
            elif self.mode in ("L", "RGB", "P") and mode in ("L", "RGB", "P"):
                t = self.info["transparency"]
                if isinstance(t, bytes):
                    # Dragons. This can't be represented by a single color
                    warnings.warn(
                        "Palette images with Transparency expressed in bytes should be "
                        "converted to RGBA images"
                    )
                    delete_trns = True
                else:
                    # get the new transparency color.
                    # use existing conversions
                    trns_im = Image()._new(core.new(self.mode, (1, 1)))
                    if self.mode == "P":
                        trns_im.putpalette(self.palette)
                        if isinstance(t, tuple):
                            try:
                                t = trns_im.palette.getcolor(t)
                            except Exception:
                                raise ValueError(
                                    "Couldn't allocate a palette color for transparency"
                                )
                    trns_im.putpixel((0, 0), t)

                    if mode in ("L", "RGB"):
                        trns_im = trns_im.convert(mode)
                    else:
                        # can't just retrieve the palette number, got to do it
                        # after quantization.
                        trns_im = trns_im.convert("RGB")
                    trns = trns_im.getpixel((0, 0))

            elif self.mode == "P" and mode == "RGBA":
                t = self.info["transparency"]
                delete_trns = True

                if isinstance(t, bytes):
                    self.im.putpalettealphas(t)
                elif isinstance(t, int):
                    self.im.putpalettealpha(t, 0)
                else:
                    raise ValueError("Transparency for P mode should be bytes or int")

        if mode == "P" and palette == ADAPTIVE:
            im = self.im.quantize(colors)
            new = self._new(im)
            from . import ImagePalette

            new.palette = ImagePalette.raw("RGB", new.im.getpalette("RGB"))
            if delete_trns:
                # This could possibly happen if we requantize to fewer colors.
                # The transparency would be totally off in that case.
                del new.info["transparency"]
            if trns is not None:
                try:
                    new.info["transparency"] = new.palette.getcolor(trns)
                except Exception:
                    # if we can't make a transparent color, don't leave the old
                    # transparency hanging around to mess us up.
                    del new.info["transparency"]
                    warnings.warn("Couldn't allocate palette entry for transparency")
            return new

        # colorspace conversion
        if dither is None:
            dither = FLOYDSTEINBERG

        try:
            im = self.im.convert(mode, dither)
        except ValueError:
            try:
                # normalize source image and try again
                im = self.im.convert(getmodebase(self.mode))
                im = im.convert(mode, dither)
            except KeyError:
                raise ValueError("illegal conversion")

        new_im = self._new(im)
        if delete_trns:
            # crash fail if we leave a bytes transparency in an rgb/l mode.
            del new_im.info["transparency"]
        if trns is not None:
            if new_im.mode == "P":
                try:
                    new_im.info["transparency"] = new_im.palette.getcolor(trns)
                except Exception:
                    del new_im.info["transparency"]
                    warnings.warn("Couldn't allocate palette entry for transparency")
            else:
                new_im.info["transparency"] = trns
        return new_im

    def quantize(self, colors=256, method=None, kmeans=0, palette=None, dither=1):
        """
        Convert the image to 'P' mode with the specified number
        of colors.

        :param colors: The desired number of colors, <= 256
        :param method: 0 = median cut
                       1 = maximum coverage
                       2 = fast octree
                       3 = libimagequant
        :param kmeans: Integer
        :param palette: Quantize to the palette of given
                        :py:class:`PIL.Image.Image`.
        :param dither: Dithering method, used when converting from
           mode "RGB" to "P" or from "RGB" or "L" to "1".
           Available methods are NONE or FLOYDSTEINBERG (default).
           Default: 1 (legacy setting)
        :returns: A new image

        """

        self.load()

        if method is None:
            # defaults:
            method = 0
            if self.mode == "RGBA":
                method = 2

        if self.mode == "RGBA" and method not in (2, 3):
            # Caller specified an invalid mode.
            raise ValueError(
                "Fast Octree (method == 2) and libimagequant (method == 3) "
                "are the only valid methods for quantizing RGBA images"
            )

        if palette:
            # use palette from reference image
            palette.load()
            if palette.mode != "P":
                raise ValueError("bad mode for palette image")
            if self.mode != "RGB" and self.mode != "L":
                raise ValueError(
                    "only RGB or L mode images can be quantized to a palette"
                )
            im = self.im.convert("P", dither, palette.im)
            return self._new(im)

        im = self._new(self.im.quantize(colors, method, kmeans))

        from . import ImagePalette

        mode = im.im.getpalettemode()
        im.palette = ImagePalette.ImagePalette(mode, im.im.getpalette(mode, mode))

        return im

    def copy(self):
        """
        Copies this image. Use this method if you wish to paste things
        into an image, but still retain the original.

        :rtype: :py:class:`~PIL.Image.Image`
        :returns: An :py:class:`~PIL.Image.Image` object.
        """
        self.load()
        return self._new(self.im.copy())

    __copy__ = copy

    def crop(self, box=None):
        """
        Returns a rectangular region from this image. The box is a
        4-tuple defining the left, upper, right, and lower pixel
        coordinate. See :ref:`coordinate-system`.

        Note: Prior to Pillow 3.4.0, this was a lazy operation.

        :param box: The crop rectangle, as a (left, upper, right, lower)-tuple.
        :rtype: :py:class:`~PIL.Image.Image`
        :returns: An :py:class:`~PIL.Image.Image` object.
        """

        if box is None:
            return self.copy()

        self.load()
        return self._new(self._crop(self.im, box))

    def _crop(self, im, box):
        """
        Returns a rectangular region from the core image object im.

        This is equivalent to calling im.crop((x0, y0, x1, y1)), but
        includes additional sanity checks.

        :param im: a core image object
        :param box: The crop rectangle, as a (left, upper, right, lower)-tuple.
        :returns: A core image object.
        """

        x0, y0, x1, y1 = map(int, map(round, box))

        absolute_values = (abs(x1 - x0), abs(y1 - y0))

        _decompression_bomb_check(absolute_values)

        return im.crop((x0, y0, x1, y1))

    def draft(self, mode, size):
        """
        Configures the image file loader so it returns a version of the
        image that as closely as possible matches the given mode and
        size. For example, you can use this method to convert a color
        JPEG to greyscale while loading it.

        If any changes are made, returns a tuple with the chosen ``mode`` and
        ``box`` with coordinates of the original image within the altered one.

        Note that this method modifies the :py:class:`~PIL.Image.Image` object
        in place. If the image has already been loaded, this method has no
        effect.

        Note: This method is not implemented for most images. It is
        currently implemented only for JPEG and MPO images.

        :param mode: The requested mode.
        :param size: The requested size.
        """
        pass

    def _expand(self, xmargin, ymargin=None):
        if ymargin is None:
            ymargin = xmargin
        self.load()
        return self._new(self.im.expand(xmargin, ymargin, 0))

    def filter(self, filter):
        """
        Filters this image using the given filter.  For a list of
        available filters, see the :py:mod:`~PIL.ImageFilter` module.

        :param filter: Filter kernel.
        :returns: An :py:class:`~PIL.Image.Image` object.  """

        from . import ImageFilter

        self.load()

        if isinstance(filter, Callable):
            filter = filter()
        if not hasattr(filter, "filter"):
            raise TypeError(
                "filter argument should be ImageFilter.Filter instance or class"
            )

        multiband = isinstance(filter, ImageFilter.MultibandFilter)
        if self.im.bands == 1 or multiband:
            return self._new(filter.filter(self.im))

        ims = []
        for c in range(self.im.bands):
            ims.append(self._new(filter.filter(self.im.getband(c))))
        return merge(self.mode, ims)

    def getbands(self):
        """
        Returns a tuple containing the name of each band in this image.
        For example, **getbands** on an RGB image returns ("R", "G", "B").

        :returns: A tuple containing band names.
        :rtype: tuple
        """
        return ImageMode.getmode(self.mode).bands

    def getbbox(self):
        """
        Calculates the bounding box of the non-zero regions in the
        image.

        :returns: The bounding box is returned as a 4-tuple defining the
           left, upper, right, and lower pixel coordinate. See
           :ref:`coordinate-system`. If the image is completely empty, this
           method returns None.

        """

        self.load()
        return self.im.getbbox()

    def getcolors(self, maxcolors=256):
        """
        Returns a list of colors used in this image.

        :param maxcolors: Maximum number of colors.  If this number is
           exceeded, this method returns None.  The default limit is
           256 colors.
        :returns: An unsorted list of (count, pixel) values.
        """

        self.load()
        if self.mode in ("1", "L", "P"):
            h = self.im.histogram()
            out = []
            for i in range(256):
                if h[i]:
                    out.append((h[i], i))
            if len(out) > maxcolors:
                return None
            return out
        return self.im.getcolors(maxcolors)

    def getdata(self, band=None):
        """
        Returns the contents of this image as a sequence object
        containing pixel values.  The sequence object is flattened, so
        that values for line one follow directly after the values of
        line zero, and so on.

        Note that the sequence object returned by this method is an
        internal PIL data type, which only supports certain sequence
        operations.  To convert it to an ordinary sequence (e.g. for
        printing), use **list(im.getdata())**.

        :param band: What band to return.  The default is to return
           all bands.  To return a single band, pass in the index
           value (e.g. 0 to get the "R" band from an "RGB" image).
        :returns: A sequence-like object.
        """

        self.load()
        if band is not None:
            return self.im.getband(band)
        return self.im  # could be abused

    def getextrema(self):
        """
        Gets the the minimum and maximum pixel values for each band in
        the image.

        :returns: For a single-band image, a 2-tuple containing the
           minimum and maximum pixel value.  For a multi-band image,
           a tuple containing one 2-tuple for each band.
        """

        self.load()
        if self.im.bands > 1:
            extrema = []
            for i in range(self.im.bands):
                extrema.append(self.im.getband(i).getextrema())
            return tuple(extrema)
        return self.im.getextrema()

    def getexif(self):
        if self._exif is None:
            self._exif = Exif()

        exif_info = self.info.get("exif")
        if exif_info is None and "Raw profile type exif" in self.info:
            exif_info = bytes.fromhex(
                "".join(self.info["Raw profile type exif"].split("\n")[3:])
            )
        self._exif.load(exif_info)

        # XMP tags
        if 0x0112 not in self._exif:
            xmp_tags = self.info.get("XML:com.adobe.xmp")
            if xmp_tags:
                root = xml.etree.ElementTree.fromstring(xmp_tags)
                for elem in root.iter():
                    if elem.tag.endswith("}Description"):
                        orientation = elem.attrib.get(
                            "{http://ns.adobe.com/tiff/1.0/}Orientation"
                        )
                        if orientation:
                            self._exif[0x0112] = int(orientation)
                        break

        return self._exif

    def getim(self):
        """
        Returns a capsule that points to the internal image memory.

        :returns: A capsule object.
        """

        self.load()
        return self.im.ptr

    def getpalette(self):
        """
        Returns the image palette as a list.

        :returns: A list of color values [r, g, b, ...], or None if the
           image has no palette.
        """

        self.load()
        try:
            return list(self.im.getpalette())
        except ValueError:
            return None  # no palette

    def getpixel(self, xy):
        """
        Returns the pixel value at a given position.

        :param xy: The coordinate, given as (x, y). See
           :ref:`coordinate-system`.
        :returns: The pixel value.  If the image is a multi-layer image,
           this method returns a tuple.
        """

        self.load()
        if self.pyaccess:
            return self.pyaccess.getpixel(xy)
        return self.im.getpixel(xy)

    def getprojection(self):
        """
        Get projection to x and y axes

        :returns: Two sequences, indicating where there are non-zero
            pixels along the X-axis and the Y-axis, respectively.
        """

        self.load()
        x, y = self.im.getprojection()
        return [i8(c) for c in x], [i8(c) for c in y]

    def histogram(self, mask=None, extrema=None):
        """
        Returns a histogram for the image. The histogram is returned as
        a list of pixel counts, one for each pixel value in the source
        image. If the image has more than one band, the histograms for
        all bands are concatenated (for example, the histogram for an
        "RGB" image contains 768 values).

        A bilevel image (mode "1") is treated as a greyscale ("L") image
        by this method.

        If a mask is provided, the method returns a histogram for those
        parts of the image where the mask image is non-zero. The mask
        image must have the same size as the image, and be either a
        bi-level image (mode "1") or a greyscale image ("L").

        :param mask: An optional mask.
        :param extrema: An optional tuple of manually-specified extrema.
        :returns: A list containing pixel counts.
        """
        self.load()
        if mask:
            mask.load()
            return self.im.histogram((0, 0), mask.im)
        if self.mode in ("I", "F"):
            if extrema is None:
                extrema = self.getextrema()
            return self.im.histogram(extrema)
        return self.im.histogram()

    def entropy(self, mask=None, extrema=None):
        """
        Calculates and returns the entropy for the image.

        A bilevel image (mode "1") is treated as a greyscale ("L")
        image by this method.

        If a mask is provided, the method employs the histogram for
        those parts of the image where the mask image is non-zero.
        The mask image must have the same size as the image, and be
        either a bi-level image (mode "1") or a greyscale image ("L").

        :param mask: An optional mask.
        :param extrema: An optional tuple of manually-specified extrema.
        :returns: A float value representing the image entropy
        """
        self.load()
        if mask:
            mask.load()
            return self.im.entropy((0, 0), mask.im)
        if self.mode in ("I", "F"):
            if extrema is None:
                extrema = self.getextrema()
            return self.im.entropy(extrema)
        return self.im.entropy()

    def offset(self, xoffset, yoffset=None):
        raise NotImplementedError(
            "offset() has been removed. Please call ImageChops.offset() instead."
        )

    def paste(self, im, box=None, mask=None):
        """
        Pastes another image into this image. The box argument is either
        a 2-tuple giving the upper left corner, a 4-tuple defining the
        left, upper, right, and lower pixel coordinate, or None (same as
        (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size
        of the pasted image must match the size of the region.

        If the modes don't match, the pasted image is converted to the mode of
        this image (see the :py:meth:`~PIL.Image.Image.convert` method for
        details).

        Instead of an image, the source can be a integer or tuple
        containing pixel values.  The method then fills the region
        with the given color.  When creating RGB images, you can
        also use color strings as supported by the ImageColor module.

        If a mask is given, this method updates only the regions
        indicated by the mask.  You can use either "1", "L" or "RGBA"
        images (in the latter case, the alpha band is used as mask).
        Where the mask is 255, the given image is copied as is.  Where
        the mask is 0, the current value is preserved.  Intermediate
        values will mix the two images together, including their alpha
        channels if they have them.

        See :py:meth:`~PIL.Image.Image.alpha_composite` if you want to
        combine images with respect to their alpha channels.

        :param im: Source image or pixel value (integer or tuple).
        :param box: An optional 4-tuple giving the region to paste into.
           If a 2-tuple is used instead, it's treated as the upper left
           corner.  If omitted or None, the source is pasted into the
           upper left corner.

           If an image is given as the second argument and there is no
           third, the box defaults to (0, 0), and the second argument
           is interpreted as a mask image.
        :param mask: An optional mask image.
        """

        if isImageType(box) and mask is None:
            # abbreviated paste(im, mask) syntax
            mask = box
            box = None

        if box is None:
            box = (0, 0)

        if len(box) == 2:
            # upper left corner given; get size from image or mask
            if isImageType(im):
                size = im.size
            elif isImageType(mask):
                size = mask.size
            else:
                # FIXME: use self.size here?
                raise ValueError("cannot determine region size; use 4-item box")
            box += (box[0] + size[0], box[1] + size[1])

        if isinstance(im, str):
            from . import ImageColor

            im = ImageColor.getcolor(im, self.mode)

        elif isImageType(im):
            im.load()
            if self.mode != im.mode:
                if self.mode != "RGB" or im.mode not in ("RGBA", "RGBa"):
                    # should use an adapter for this!
                    im = im.convert(self.mode)
            im = im.im

        self._ensure_mutable()

        if mask:
            mask.load()
            self.im.paste(im, box, mask.im)
        else:
            self.im.paste(im, box)

    def alpha_composite(self, im, dest=(0, 0), source=(0, 0)):
        """ 'In-place' analog of Image.alpha_composite. Composites an image
        onto this image.

        :param im: image to composite over this one
        :param dest: Optional 2 tuple (left, top) specifying the upper
          left corner in this (destination) image.
        :param source: Optional 2 (left, top) tuple for the upper left
          corner in the overlay source image, or 4 tuple (left, top, right,
          bottom) for the bounds of the source rectangle

        Performance Note: Not currently implemented in-place in the core layer.
        """

        if not isinstance(source, (list, tuple)):
            raise ValueError("Source must be a tuple")
        if not isinstance(dest, (list, tuple)):
            raise ValueError("Destination must be a tuple")
        if not len(source) in (2, 4):
            raise ValueError("Source must be a 2 or 4-tuple")
        if not len(dest) == 2:
            raise ValueError("Destination must be a 2-tuple")
        if min(source) < 0:
            raise ValueError("Source must be non-negative")
        if min(dest) < 0:
            raise ValueError("Destination must be non-negative")

        if len(source) == 2:
            source = source + im.size

        # over image, crop if it's not the whole thing.
        if source == (0, 0) + im.size:
            overlay = im
        else:
            overlay = im.crop(source)

        # target for the paste
        box = dest + (dest[0] + overlay.width, dest[1] + overlay.height)

        # destination image. don't copy if we're using the whole image.
        if box == (0, 0) + self.size:
            background = self
        else:
            background = self.crop(box)

        result = alpha_composite(background, overlay)
        self.paste(result, box)

    def point(self, lut, mode=None):
        """
        Maps this image through a lookup table or function.

        :param lut: A lookup table, containing 256 (or 65536 if
           self.mode=="I" and mode == "L") values per band in the
           image.  A function can be used instead, it should take a
           single argument. The function is called once for each
           possible pixel value, and the resulting table is applied to
           all bands of the image.
        :param mode: Output mode (default is same as input).  In the
           current version, this can only be used if the source image
           has mode "L" or "P", and the output has mode "1" or the
           source image mode is "I" and the output mode is "L".
        :returns: An :py:class:`~PIL.Image.Image` object.
        """

        self.load()

        if isinstance(lut, ImagePointHandler):
            return lut.point(self)

        if callable(lut):
            # if it isn't a list, it should be a function
            if self.mode in ("I", "I;16", "F"):
                # check if the function can be used with point_transform
                # UNDONE wiredfool -- I think this prevents us from ever doing
                # a gamma function point transform on > 8bit images.
                scale, offset = _getscaleoffset(lut)
                return self._new(self.im.point_transform(scale, offset))
            # for other modes, convert the function to a table
            lut = [lut(i) for i in range(256)] * self.im.bands

        if self.mode == "F":
            # FIXME: _imaging returns a confusing error message for this case
            raise ValueError("point operation not supported for this mode")

        return self._new(self.im.point(lut, mode))

    def putalpha(self, alpha):
        """
        Adds or replaces the alpha layer in this image.  If the image
        does not have an alpha layer, it's converted to "LA" or "RGBA".
        The new layer must be either "L" or "1".

        :param alpha: The new alpha layer.  This can either be an "L" or "1"
           image having the same size as this image, or an integer or
           other color value.
        """

        self._ensure_mutable()

        if self.mode not in ("LA", "PA", "RGBA"):
            # attempt to promote self to a matching alpha mode
            try:
                mode = getmodebase(self.mode) + "A"
                try:
                    self.im.setmode(mode)
                except (AttributeError, ValueError):
                    # do things the hard way
                    im = self.im.convert(mode)
                    if im.mode not in ("LA", "PA", "RGBA"):
                        raise ValueError  # sanity check
                    self.im = im
                self.pyaccess = None
                self.mode = self.im.mode
            except (KeyError, ValueError):
                raise ValueError("illegal image mode")

        if self.mode in ("LA", "PA"):
            band = 1
        else:
            band = 3

        if isImageType(alpha):
            # alpha layer
            if alpha.mode not in ("1", "L"):
                raise ValueError("illegal image mode")
            alpha.load()
            if alpha.mode == "1":
                alpha = alpha.convert("L")
        else:
            # constant alpha
            try:
                self.im.fillband(band, alpha)
            except (AttributeError, ValueError):
                # do things the hard way
                alpha = new("L", self.size, alpha)
            else:
                return

        self.im.putband(alpha.im, band)

    def putdata(self, data, scale=1.0, offset=0.0):
        """
        Copies pixel data to this image.  This method copies data from a
        sequence object into the image, starting at the upper left
        corner (0, 0), and continuing until either the image or the
        sequence ends.  The scale and offset values are used to adjust
        the sequence values: **pixel = value*scale + offset**.

        :param data: A sequence object.
        :param scale: An optional scale value.  The default is 1.0.
        :param offset: An optional offset value.  The default is 0.0.
        """

        self._ensure_mutable()

        self.im.putdata(data, scale, offset)

    def putpalette(self, data, rawmode="RGB"):
        """
        Attaches a palette to this image.  The image must be a "P",
        "PA", "L" or "LA" image, and the palette sequence must contain
        768 integer values, where each group of three values represent
        the red, green, and blue values for the corresponding pixel
        index. Instead of an integer sequence, you can use an 8-bit
        string.

        :param data: A palette sequence (either a list or a string).
        :param rawmode: The raw mode of the palette.
        """
        from . import ImagePalette

        if self.mode not in ("L", "LA", "P", "PA"):
            raise ValueError("illegal image mode")
        self.load()
        if isinstance(data, ImagePalette.ImagePalette):
            palette = ImagePalette.raw(data.rawmode, data.palette)
        else:
            if not isinstance(data, bytes):
                data = bytes(data)
            palette = ImagePalette.raw(rawmode, data)
        self.mode = "PA" if "A" in self.mode else "P"
        self.palette = palette
        self.palette.mode = "RGB"
        self.load()  # install new palette

    def putpixel(self, xy, value):
        """
        Modifies the pixel at the given position. The color is given as
        a single numerical value for single-band images, and a tuple for
        multi-band images. In addition to this, RGB and RGBA tuples are
        accepted for P images.

        Note that this method is relatively slow.  For more extensive changes,
        use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw`
        module instead.

        See:

        * :py:meth:`~PIL.Image.Image.paste`
        * :py:meth:`~PIL.Image.Image.putdata`
        * :py:mod:`~PIL.ImageDraw`

        :param xy: The pixel coordinate, given as (x, y). See
           :ref:`coordinate-system`.
        :param value: The pixel value.
        """

        if self.readonly:
            self._copy()
        self.load()

        if self.pyaccess:
            return self.pyaccess.putpixel(xy, value)

        if (
            self.mode == "P"
            and isinstance(value, (list, tuple))
            and len(value) in [3, 4]
        ):
            # RGB or RGBA value for a P image
            value = self.palette.getcolor(value)
        return self.im.putpixel(xy, value)

    def remap_palette(self, dest_map, source_palette=None):
        """
        Rewrites the image to reorder the palette.

        :param dest_map: A list of indexes into the original palette.
           e.g. [1,0] would swap a two item palette, and list(range(256))
           is the identity transform.
        :param source_palette: Bytes or None.
        :returns:  An :py:class:`~PIL.Image.Image` object.

        """
        from . import ImagePalette

        if self.mode not in ("L", "P"):
            raise ValueError("illegal image mode")

        if source_palette is None:
            if self.mode == "P":
                real_source_palette = self.im.getpalette("RGB")[:768]
            else:  # L-mode
                real_source_palette = bytearray(i // 3 for i in range(768))
        else:
            real_source_palette = source_palette

        palette_bytes = b""
        new_positions = [0] * 256

        # pick only the used colors from the palette
        for i, oldPosition in enumerate(dest_map):
            palette_bytes += real_source_palette[oldPosition * 3 : oldPosition * 3 + 3]
            new_positions[oldPosition] = i

        # replace the palette color id of all pixel with the new id

        # Palette images are [0..255], mapped through a 1 or 3
        # byte/color map.  We need to remap the whole image
        # from palette 1 to palette 2. New_positions is
        # an array of indexes into palette 1.  Palette 2 is
        # palette 1 with any holes removed.

        # We're going to leverage the convert mechanism to use the
        # C code to remap the image from palette 1 to palette 2,
        # by forcing the source image into 'L' mode and adding a
        # mapping 'L' mode palette, then converting back to 'L'
        # sans palette thus converting the image bytes, then
        # assigning the optimized RGB palette.

        # perf reference, 9500x4000 gif, w/~135 colors
        # 14 sec prepatch, 1 sec postpatch with optimization forced.

        mapping_palette = bytearray(new_positions)

        m_im = self.copy()
        m_im.mode = "P"

        m_im.palette = ImagePalette.ImagePalette(
            "RGB", palette=mapping_palette * 3, size=768
        )
        # possibly set palette dirty, then
        # m_im.putpalette(mapping_palette, 'L')  # converts to 'P'
        # or just force it.
        # UNDONE -- this is part of the general issue with palettes
        m_im.im.putpalette(*m_im.palette.getdata())

        m_im = m_im.convert("L")

        # Internally, we require 768 bytes for a palette.
        new_palette_bytes = palette_bytes + (768 - len(palette_bytes)) * b"\x00"
        m_im.putpalette(new_palette_bytes)
        m_im.palette = ImagePalette.ImagePalette(
            "RGB", palette=palette_bytes, size=len(palette_bytes)
        )

        return m_im

    def _get_safe_box(self, size, resample, box):
        """Expands the box so it includes adjacent pixels
        that may be used by resampling with the given resampling filter.
        """
        filter_support = _filters_support[resample] - 0.5
        scale_x = (box[2] - box[0]) / size[0]
        scale_y = (box[3] - box[1]) / size[1]
        support_x = filter_support * scale_x
        support_y = filter_support * scale_y

        return (
            max(0, int(box[0] - support_x)),
            max(0, int(box[1] - support_y)),
            min(self.size[0], math.ceil(box[2] + support_x)),
            min(self.size[1], math.ceil(box[3] + support_y)),
        )

    def resize(self, size, resample=BICUBIC, box=None, reducing_gap=None):
        """
        Returns a resized copy of this image.

        :param size: The requested size in pixels, as a 2-tuple:
           (width, height).
        :param resample: An optional resampling filter.  This can be
           one of :py:attr:`PIL.Image.NEAREST`, :py:attr:`PIL.Image.BOX`,
           :py:attr:`PIL.Image.BILINEAR`, :py:attr:`PIL.Image.HAMMING`,
           :py:attr:`PIL.Image.BICUBIC` or :py:attr:`PIL.Image.LANCZOS`.
           Default filter is :py:attr:`PIL.Image.BICUBIC`.
           If the image has mode "1" or "P", it is
           always set to :py:attr:`PIL.Image.NEAREST`.
           See: :ref:`concept-filters`.
        :param box: An optional 4-tuple of floats providing
           the source image region to be scaled.
           The values must be within (0, 0, width, height) rectangle.
           If omitted or None, the entire source is used.
        :param reducing_gap: Apply optimization by resizing the image
           in two steps. First, reducing the image by integer times
           using :py:meth:`~PIL.Image.Image.reduce`.
           Second, resizing using regular resampling. The last step
           changes size no less than by ``reducing_gap`` times.
           ``reducing_gap`` may be None (no first step is performed)
           or should be greater than 1.0. The bigger ``reducing_gap``,
           the closer the result to the fair resampling.
           The smaller ``reducing_gap``, the faster resizing.
           With ``reducing_gap`` greater or equal to 3.0, the result is
           indistinguishable from fair resampling in most cases.
           The default value is None (no optimization).
        :returns: An :py:class:`~PIL.Image.Image` object.
        """

        if resample not in (NEAREST, BILINEAR, BICUBIC, LANCZOS, BOX, HAMMING):
            message = "Unknown resampling filter ({}).".format(resample)

            filters = [
                "{} ({})".format(filter[1], filter[0])
                for filter in (
                    (NEAREST, "Image.NEAREST"),
                    (LANCZOS, "Image.LANCZOS"),
                    (BILINEAR, "Image.BILINEAR"),
                    (BICUBIC, "Image.BICUBIC"),
                    (BOX, "Image.BOX"),
                    (HAMMING, "Image.HAMMING"),
                )
            ]
            raise ValueError(
                message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1]
            )

        if reducing_gap is not None and reducing_gap < 1.0:
            raise ValueError("reducing_gap must be 1.0 or greater")

        size = tuple(size)

        if box is None:
            box = (0, 0) + self.size
        else:
            box = tuple(box)

        if self.size == size and box == (0, 0) + self.size:
            return self.copy()

        if self.mode in ("1", "P"):
            resample = NEAREST

        if self.mode in ["LA", "RGBA"]:
            im = self.convert(self.mode[:-1] + "a")
            im = im.resize(size, resample, box)
            return im.convert(self.mode)

        self.load()

        if reducing_gap is not None and resample != NEAREST:
            factor_x = int((box[2] - box[0]) / size[0] / reducing_gap) or 1
            factor_y = int((box[3] - box[1]) / size[1] / reducing_gap) or 1
            if factor_x > 1 or factor_y > 1:
                reduce_box = self._get_safe_box(size, resample, box)
                factor = (factor_x, factor_y)
                if callable(self.reduce):
                    self = self.reduce(factor, box=reduce_box)
                else:
                    self = Image.reduce(self, factor, box=reduce_box)
                box = (
                    (box[0] - reduce_box[0]) / factor_x,
                    (box[1] - reduce_box[1]) / factor_y,
                    (box[2] - reduce_box[0]) / factor_x,
                    (box[3] - reduce_box[1]) / factor_y,
                )

        return self._new(self.im.resize(size, resample, box))

    def reduce(self, factor, box=None):
        """
        Returns a copy of the image reduced by `factor` times.
        If the size of the image is not dividable by the `factor`,
        the resulting size will be rounded up.

        :param factor: A greater than 0 integer or tuple of two integers
           for width and height separately.
        :param box: An optional 4-tuple of ints providing
           the source image region to be reduced.
           The values must be within (0, 0, width, height) rectangle.
           If omitted or None, the entire source is used.
        """
        if not isinstance(factor, (list, tuple)):
            factor = (factor, factor)

        if box is None:
            box = (0, 0) + self.size
        else:
            box = tuple(box)

        if factor == (1, 1) and box == (0, 0) + self.size:
            return self.copy()

        if self.mode in ["LA", "RGBA"]:
            im = self.convert(self.mode[:-1] + "a")
            im = im.reduce(factor, box)
            return im.convert(self.mode)

        self.load()

        return self._new(self.im.reduce(factor, box))

    def rotate(
        self,
        angle,
        resample=NEAREST,
        expand=0,
        center=None,
        translate=None,
        fillcolor=None,
    ):
        """
        Returns a rotated copy of this image.  This method returns a
        copy of this image, rotated the given number of degrees counter
        clockwise around its centre.

        :param angle: In degrees counter clockwise.
        :param resample: An optional resampling filter.  This can be
           one of :py:attr:`PIL.Image.NEAREST` (use nearest neighbour),
           :py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2
           environment), or :py:attr:`PIL.Image.BICUBIC`
           (cubic spline interpolation in a 4x4 environment).
           If omitted, or if the image has mode "1" or "P", it is
           set to :py:attr:`PIL.Image.NEAREST`. See :ref:`concept-filters`.
        :param expand: Optional expansion flag.  If true, expands the output
           image to make it large enough to hold the entire rotated image.
           If false or omitted, make the output image the same size as the
           input image.  Note that the expand flag assumes rotation around
           the center and no translation.
        :param center: Optional center of rotation (a 2-tuple).  Origin is
           the upper left corner.  Default is the center of the image.
        :param translate: An optional post-rotate translation (a 2-tuple).
        :param fillcolor: An optional color for area outside the rotated image.
        :returns: An :py:class:`~PIL.Image.Image` object.
        """

        angle = angle % 360.0

        # Fast paths regardless of filter, as long as we're not
        # translating or changing the center.
        if not (center or translate):
            if angle == 0:
                return self.copy()
            if angle == 180:
                return self.transpose(ROTATE_180)
            if angle == 90 and expand:
                return self.transpose(ROTATE_90)
            if angle == 270 and expand:
                return self.transpose(ROTATE_270)

        # Calculate the affine matrix.  Note that this is the reverse
        # transformation (from destination image to source) because we
        # want to interpolate the (discrete) destination pixel from
        # the local area around the (floating) source pixel.

        # The matrix we actually want (note that it operates from the right):
        # (1, 0, tx)   (1, 0, cx)   ( cos a, sin a, 0)   (1, 0, -cx)
        # (0, 1, ty) * (0, 1, cy) * (-sin a, cos a, 0) * (0, 1, -cy)
        # (0, 0,  1)   (0, 0,  1)   (     0,     0, 1)   (0, 0,   1)

        # The reverse matrix is thus:
        # (1, 0, cx)   ( cos -a, sin -a, 0)   (1, 0, -cx)   (1, 0, -tx)
        # (0, 1, cy) * (-sin -a, cos -a, 0) * (0, 1, -cy) * (0, 1, -ty)
        # (0, 0,  1)   (      0,      0, 1)   (0, 0,   1)   (0, 0,   1)

        # In any case, the final translation may be updated at the end to
        # compensate for the expand flag.

        w, h = self.size

        if translate is None:
            post_trans = (0, 0)
        else:
            post_trans = translate
        if center is None:
            # FIXME These should be rounded to ints?
            rotn_center = (w / 2.0, h / 2.0)
        else:
            rotn_center = center

        angle = -math.radians(angle)
        matrix = [
            round(math.cos(angle), 15),
            round(math.sin(angle), 15),
            0.0,
            round(-math.sin(angle), 15),
            round(math.cos(angle), 15),
            0.0,
        ]

        def transform(x, y, matrix):
            (a, b, c, d, e, f) = matrix
            return a * x + b * y + c, d * x + e * y + f

        matrix[2], matrix[5] = transform(
            -rotn_center[0] - post_trans[0], -rotn_center[1] - post_trans[1], matrix
        )
        matrix[2] += rotn_center[0]
        matrix[5] += rotn_center[1]

        if expand:
            # calculate output size
            xx = []
            yy = []
            for x, y in ((0, 0), (w, 0), (w, h), (0, h)):
                x, y = transform(x, y, matrix)
                xx.append(x)
                yy.append(y)
            nw = math.ceil(max(xx)) - math.floor(min(xx))
            nh = math.ceil(max(yy)) - math.floor(min(yy))

            # We multiply a translation matrix from the right.  Because of its
            # special form, this is the same as taking the image of the
            # translation vector as new translation vector.
            matrix[2], matrix[5] = transform(-(nw - w) / 2.0, -(nh - h) / 2.0, matrix)
            w, h = nw, nh

        return self.transform((w, h), AFFINE, matrix, resample, fillcolor=fillcolor)

    def save(self, fp, format=None, **params):
        """
        Saves this image under the given filename.  If no format is
        specified, the format to use is determined from the filename
        extension, if possible.

        Keyword options can be used to provide additional instructions
        to the writer. If a writer doesn't recognise an option, it is
        silently ignored. The available options are described in the
        :doc:`image format documentation
        <../handbook/image-file-formats>` for each writer.

        You can use a file object instead of a filename. In this case,
        you must always specify the format. The file object must
        implement the ``seek``, ``tell``, and ``write``
        methods, and be opened in binary mode.

        :param fp: A filename (string), pathlib.Path object or file object.
        :param format: Optional format override.  If omitted, the
           format to use is determined from the filename extension.
           If a file object was used instead of a filename, this
           parameter should always be used.
        :param params: Extra parameters to the image writer.
        :returns: None
        :exception ValueError: If the output format could not be determined
           from the file name.  Use the format option to solve this.
        :exception OSError: If the file could not be written.  The file
           may have been created, and may contain partial data.
        """

        filename = ""
        open_fp = False
        if isPath(fp):
            filename = fp
            open_fp = True
        elif isinstance(fp, Path):
            filename = str(fp)
            open_fp = True
        if not filename and hasattr(fp, "name") and isPath(fp.name):
            # only set the name for metadata purposes
            filename = fp.name

        # may mutate self!
        self._ensure_mutable()

        save_all = params.pop("save_all", False)
        self.encoderinfo = params
        self.encoderconfig = ()

        preinit()

        ext = os.path.splitext(filename)[1].lower()

        if not format:
            if ext not in EXTENSION:
                init()
            try:
                format = EXTENSION[ext]
            except KeyError:
                raise ValueError("unknown file extension: {}".format(ext))

        if format.upper() not in SAVE:
            init()
        if save_all:
            save_handler = SAVE_ALL[format.upper()]
        else:
            save_handler = SAVE[format.upper()]

        if open_fp:
            if params.get("append", False):
                # Open also for reading ("+"), because TIFF save_all
                # writer needs to go back and edit the written data.
                fp = builtins.open(filename, "r+b")
            else:
                fp = builtins.open(filename, "w+b")

        try:
            save_handler(self, fp, filename)
        finally:
            # do what we can to clean up
            if open_fp:
                fp.close()

    def seek(self, frame):
        """
        Seeks to the given frame in this sequence file. If you seek
        beyond the end of the sequence, the method raises an
        **EOFError** exception. When a sequence file is opened, the
        library automatically seeks to frame 0.

        See :py:meth:`~PIL.Image.Image.tell`.

        :param frame: Frame number, starting at 0.
        :exception EOFError: If the call attempts to seek beyond the end
            of the sequence.
        """

        # overridden by file handlers
        if frame != 0:
            raise EOFError

    def show(self, title=None, command=None):
        """
        Displays this image. This method is mainly intended for
        debugging purposes.

        The image is first saved to a temporary file. By default, it will be in
        PNG format.

        On Unix, the image is then opened using the **display**, **eog** or
        **xv** utility, depending on which one can be found.

        On macOS, the image is opened with the native Preview application.

        On Windows, the image is opened with the standard PNG display utility.

        :param title: Optional title to use for the image window,
           where possible.
        :param command: command used to show the image
        """

        _show(self, title=title, command=command)

    def split(self):
        """
        Split this image into individual bands. This method returns a
        tuple of individual image bands from an image. For example,
        splitting an "RGB" image creates three new images each
        containing a copy of one of the original bands (red, green,
        blue).

        If you need only one band, :py:meth:`~PIL.Image.Image.getchannel`
        method can be more convenient and faster.

        :returns: A tuple containing bands.
        """

        self.load()
        if self.im.bands == 1:
            ims = [self.copy()]
        else:
            ims = map(self._new, self.im.split())
        return tuple(ims)

    def getchannel(self, channel):
        """
        Returns an image containing a single channel of the source image.

        :param channel: What channel to return. Could be index
          (0 for "R" channel of "RGB") or channel name
          ("A" for alpha channel of "RGBA").
        :returns: An image in "L" mode.

        .. versionadded:: 4.3.0
        """
        self.load()

        if isinstance(channel, str):
            try:
                channel = self.getbands().index(channel)
            except ValueError:
                raise ValueError('The image has no channel "{}"'.format(channel))

        return self._new(self.im.getband(channel))

    def tell(self):
        """
        Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`.

        :returns: Frame number, starting with 0.
        """
        return 0

    def thumbnail(self, size, resample=BICUBIC, reducing_gap=2.0):
        """
        Make this image into a thumbnail.  This method modifies the
        image to contain a thumbnail version of itself, no larger than
        the given size.  This method calculates an appropriate thumbnail
        size to preserve the aspect of the image, calls the
        :py:meth:`~PIL.Image.Image.draft` method to configure the file reader
        (where applicable), and finally resizes the image.

        Note that this function modifies the :py:class:`~PIL.Image.Image`
        object in place.  If you need to use the full resolution image as well,
        apply this method to a :py:meth:`~PIL.Image.Image.copy` of the original
        image.

        :param size: Requested size.
        :param resample: Optional resampling filter.  This can be one
           of :py:attr:`PIL.Image.NEAREST`, :py:attr:`PIL.Image.BILINEAR`,
           :py:attr:`PIL.Image.BICUBIC`, or :py:attr:`PIL.Image.LANCZOS`.
           If omitted, it defaults to :py:attr:`PIL.Image.BICUBIC`.
           (was :py:attr:`PIL.Image.NEAREST` prior to version 2.5.0).
           See: :ref:`concept-filters`.
        :param reducing_gap: Apply optimization by resizing the image
           in two steps. First, reducing the image by integer times
           using :py:meth:`~PIL.Image.Image.reduce` or
           :py:meth:`~PIL.Image.Image.draft` for JPEG images.
           Second, resizing using regular resampling. The last step
           changes size no less than by ``reducing_gap`` times.
           ``reducing_gap`` may be None (no first step is performed)
           or should be greater than 1.0. The bigger ``reducing_gap``,
           the closer the result to the fair resampling.
           The smaller ``reducing_gap``, the faster resizing.
           With ``reducing_gap`` greater or equal to 3.0, the result is
           indistinguishable from fair resampling in most cases.
           The default value is 2.0 (very close to fair resampling
           while still being faster in many cases).
        :returns: None
        """

        x, y = map(math.floor, size)
        if x >= self.width and y >= self.height:
            return

        def round_aspect(number, key):
            return max(min(math.floor(number), math.ceil(number), key=key), 1)

        # preserve aspect ratio
        aspect = self.width / self.height
        if x / y >= aspect:
            x = round_aspect(y * aspect, key=lambda n: abs(aspect - n / y))
        else:
            y = round_aspect(
                x / aspect, key=lambda n: 0 if n == 0 else abs(aspect - x / n)
            )
        size = (x, y)

        box = None
        if reducing_gap is not None:
            res = self.draft(None, (size[0] * reducing_gap, size[1] * reducing_gap))
            if res is not None:
                box = res[1]

        if self.size != size:
            im = self.resize(size, resample, box=box, reducing_gap=reducing_gap)

            self.im = im.im
            self._size = size
            self.mode = self.im.mode

        self.readonly = 0
        self.pyaccess = None

    # FIXME: the different transform methods need further explanation
    # instead of bloating the method docs, add a separate chapter.
    def transform(
        self, size, method, data=None, resample=NEAREST, fill=1, fillcolor=None
    ):
        """
        Transforms this image.  This method creates a new image with the
        given size, and the same mode as the original, and copies data
        to the new image using the given transform.

        :param size: The output size.
        :param method: The transformation method.  This is one of
          :py:attr:`PIL.Image.EXTENT` (cut out a rectangular subregion),
          :py:attr:`PIL.Image.AFFINE` (affine transform),
          :py:attr:`PIL.Image.PERSPECTIVE` (perspective transform),
          :py:attr:`PIL.Image.QUAD` (map a quadrilateral to a rectangle), or
          :py:attr:`PIL.Image.MESH` (map a number of source quadrilaterals
          in one operation).

          It may also be an :py:class:`~PIL.Image.ImageTransformHandler`
          object::

            class Example(Image.ImageTransformHandler):
                def transform(size, method, data, resample, fill=1):
                    # Return result

          It may also be an object with a :py:meth:`~method.getdata` method
          that returns a tuple supplying new **method** and **data** values::

            class Example:
                def getdata(self):
                    method = Image.EXTENT
                    data = (0, 0, 100, 100)
                    return method, data
        :param data: Extra data to the transformation method.
        :param resample: Optional resampling filter.  It can be one of
           :py:attr:`PIL.Image.NEAREST` (use nearest neighbour),
           :py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2
           environment), or :py:attr:`PIL.Image.BICUBIC` (cubic spline
           interpolation in a 4x4 environment). If omitted, or if the image
           has mode "1" or "P", it is set to :py:attr:`PIL.Image.NEAREST`.
           See: :ref:`concept-filters`.
        :param fill: If **method** is an
          :py:class:`~PIL.Image.ImageTransformHandler` object, this is one of
          the arguments passed to it. Otherwise, it is unused.
        :param fillcolor: Optional fill color for the area outside the
           transform in the output image.
        :returns: An :py:class:`~PIL.Image.Image` object.
        """

        if self.mode == "LA":
            return (
                self.convert("La")
                .transform(size, method, data, resample, fill, fillcolor)
                .convert("LA")
            )

        if self.mode == "RGBA":
            return (
                self.convert("RGBa")
                .transform(size, method, data, resample, fill, fillcolor)
                .convert("RGBA")
            )

        if isinstance(method, ImageTransformHandler):
            return method.transform(size, self, resample=resample, fill=fill)

        if hasattr(method, "getdata"):
            # compatibility w. old-style transform objects
            method, data = method.getdata()

        if data is None:
            raise ValueError("missing method data")

        im = new(self.mode, size, fillcolor)
        im.info = self.info.copy()
        if method == MESH:
            # list of quads
            for box, quad in data:
                im.__transformer(box, self, QUAD, quad, resample, fillcolor is None)
        else:
            im.__transformer(
                (0, 0) + size, self, method, data, resample, fillcolor is None
            )

        return im

    def __transformer(self, box, image, method, data, resample=NEAREST, fill=1):
        w = box[2] - box[0]
        h = box[3] - box[1]

        if method == AFFINE:
            data = data[0:6]

        elif method == EXTENT:
            # convert extent to an affine transform
            x0, y0, x1, y1 = data
            xs = (x1 - x0) / w
            ys = (y1 - y0) / h
            method = AFFINE
            data = (xs, 0, x0, 0, ys, y0)

        elif method == PERSPECTIVE:
            data = data[0:8]

        elif method == QUAD:
            # quadrilateral warp.  data specifies the four corners
            # given as NW, SW, SE, and NE.
            nw = data[0:2]
            sw = data[2:4]
            se = data[4:6]
            ne = data[6:8]
            x0, y0 = nw
            As = 1.0 / w
            At = 1.0 / h
            data = (
                x0,
                (ne[0] - x0) * As,
                (sw[0] - x0) * At,
                (se[0] - sw[0] - ne[0] + x0) * As * At,
                y0,
                (ne[1] - y0) * As,
                (sw[1] - y0) * At,
                (se[1] - sw[1] - ne[1] + y0) * As * At,
            )

        else:
            raise ValueError("unknown transformation method")

        if resample not in (NEAREST, BILINEAR, BICUBIC):
            if resample in (BOX, HAMMING, LANCZOS):
                message = {
                    BOX: "Image.BOX",
                    HAMMING: "Image.HAMMING",
                    LANCZOS: "Image.LANCZOS/Image.ANTIALIAS",
                }[resample] + " ({}) cannot be used.".format(resample)
            else:
                message = "Unknown resampling filter ({}).".format(resample)

            filters = [
                "{} ({})".format(filter[1], filter[0])
                for filter in (
                    (NEAREST, "Image.NEAREST"),
                    (BILINEAR, "Image.BILINEAR"),
                    (BICUBIC, "Image.BICUBIC"),
                )
            ]
            raise ValueError(
                message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1]
            )

        image.load()

        self.load()

        if image.mode in ("1", "P"):
            resample = NEAREST

        self.im.transform2(box, image.im, method, data, resample, fill)

    def transpose(self, method):
        """
        Transpose image (flip or rotate in 90 degree steps)

        :param method: One of :py:attr:`PIL.Image.FLIP_LEFT_RIGHT`,
          :py:attr:`PIL.Image.FLIP_TOP_BOTTOM`, :py:attr:`PIL.Image.ROTATE_90`,
          :py:attr:`PIL.Image.ROTATE_180`, :py:attr:`PIL.Image.ROTATE_270`,
          :py:attr:`PIL.Image.TRANSPOSE` or :py:attr:`PIL.Image.TRANSVERSE`.
        :returns: Returns a flipped or rotated copy of this image.
        """

        self.load()
        return self._new(self.im.transpose(method))

    def effect_spread(self, distance):
        """
        Randomly spread pixels in an image.

        :param distance: Distance to spread pixels.
        """
        self.load()
        return self._new(self.im.effect_spread(distance))

    def toqimage(self):
        """Returns a QImage copy of this image"""
        from . import ImageQt

        if not ImageQt.qt_is_installed:
            raise ImportError("Qt bindings are not installed")
        return ImageQt.toqimage(self)

    def toqpixmap(self):
        """Returns a QPixmap copy of this image"""
        from . import ImageQt

        if not ImageQt.qt_is_installed:
            raise ImportError("Qt bindings are not installed")
        return ImageQt.toqpixmap(self)


# --------------------------------------------------------------------
# Abstract handlers.


class ImagePointHandler:
    # used as a mixin by point transforms (for use with im.point)
    pass


class ImageTransformHandler:
    # used as a mixin by geometry transforms (for use with im.transform)
    pass


# --------------------------------------------------------------------
# Factories

#
# Debugging


def _wedge():
    """Create greyscale wedge (for debugging only)"""

    return Image()._new(core.wedge("L"))


def _check_size(size):
    """
    Common check to enforce type and sanity check on size tuples

    :param size: Should be a 2 tuple of (width, height)
    :returns: True, or raises a ValueError
    """

    if not isinstance(size, (list, tuple)):
        raise ValueError("Size must be a tuple")
    if len(size) != 2:
        raise ValueError("Size must be a tuple of length 2")
    if size[0] < 0 or size[1] < 0:
        raise ValueError("Width and height must be >= 0")

    return True


def new(mode, size, color=0):
    """
    Creates a new image with the given mode and size.

    :param mode: The mode to use for the new image. See:
       :ref:`concept-modes`.
    :param size: A 2-tuple, containing (width, height) in pixels.
    :param color: What color to use for the image.  Default is black.
       If given, this should be a single integer or floating point value
       for single-band modes, and a tuple for multi-band modes (one value
       per band).  When creating RGB images, you can also use color
       strings as supported by the ImageColor module.  If the color is
       None, the image is not initialised.
    :returns: An :py:class:`~PIL.Image.Image` object.
    """

    _check_size(size)

    if color is None:
        # don't initialize
        return Image()._new(core.new(mode, size))

    if isinstance(color, str):
        # css3-style specifier

        from . import ImageColor

        color = ImageColor.getcolor(color, mode)

    im = Image()
    if mode == "P" and isinstance(color, (list, tuple)) and len(color) in [3, 4]:
        # RGB or RGBA value for a P image
        from . import ImagePalette

        im.palette = ImagePalette.ImagePalette()
        color = im.palette.getcolor(color)
    return im._new(core.fill(mode, size, color))


def frombytes(mode, size, data, decoder_name="raw", *args):
    """
    Creates a copy of an image memory from pixel data in a buffer.

    In its simplest form, this function takes three arguments
    (mode, size, and unpacked pixel data).

    You can also use any pixel decoder supported by PIL.  For more
    information on available decoders, see the section
    :ref:`Writing Your Own File Decoder <file-decoders>`.

    Note that this function decodes pixel data only, not entire images.
    If you have an entire image in a string, wrap it in a
    :py:class:`~io.BytesIO` object, and use :py:func:`~PIL.Image.open` to load
    it.

    :param mode: The image mode. See: :ref:`concept-modes`.
    :param size: The image size.
    :param data: A byte buffer containing raw data for the given mode.
    :param decoder_name: What decoder to use.
    :param args: Additional parameters for the given decoder.
    :returns: An :py:class:`~PIL.Image.Image` object.
    """

    _check_size(size)

    # may pass tuple instead of argument list
    if len(args) == 1 and isinstance(args[0], tuple):
        args = args[0]

    if decoder_name == "raw" and args == ():
        args = mode

    im = new(mode, size)
    im.frombytes(data, decoder_name, args)
    return im


def fromstring(*args, **kw):
    raise NotImplementedError(
        "fromstring() has been removed. Please call frombytes() instead."
    )


def frombuffer(mode, size, data, decoder_name="raw", *args):
    """
    Creates an image memory referencing pixel data in a byte buffer.

    This function is similar to :py:func:`~PIL.Image.frombytes`, but uses data
    in the byte buffer, where possible.  This means that changes to the
    original buffer object are reflected in this image).  Not all modes can
    share memory; supported modes include "L", "RGBX", "RGBA", and "CMYK".

    Note that this function decodes pixel data only, not entire images.
    If you have an entire image file in a string, wrap it in a
    **BytesIO** object, and use :py:func:`~PIL.Image.open` to load it.

    In the current version, the default parameters used for the "raw" decoder
    differs from that used for :py:func:`~PIL.Image.frombytes`.  This is a
    bug, and will probably be fixed in a future release.  The current release
    issues a warning if you do this; to disable the warning, you should provide
    the full set of parameters.  See below for details.

    :param mode: The image mode. See: :ref:`concept-modes`.
    :param size: The image size.
    :param data: A bytes or other buffer object containing raw
        data for the given mode.
    :param decoder_name: What decoder to use.
    :param args: Additional parameters for the given decoder.  For the
        default encoder ("raw"), it's recommended that you provide the
        full set of parameters::

            frombuffer(mode, size, data, "raw", mode, 0, 1)

    :returns: An :py:class:`~PIL.Image.Image` object.

    .. versionadded:: 1.1.4
    """

    _check_size(size)

    # may pass tuple instead of argument list
    if len(args) == 1 and isinstance(args[0], tuple):
        args = args[0]

    if decoder_name == "raw":
        if args == ():
            args = mode, 0, 1
        if args[0] in _MAPMODES:
            im = new(mode, (1, 1))
            im = im._new(core.map_buffer(data, size, decoder_name, 0, args))
            im.readonly = 1
            return im

    return frombytes(mode, size, data, decoder_name, args)


def fromarray(obj, mode=None):
    """
    Creates an image memory from an object exporting the array interface
    (using the buffer protocol).

    If **obj** is not contiguous, then the tobytes method is called
    and :py:func:`~PIL.Image.frombuffer` is used.

    If you have an image in NumPy::

      from PIL import Image
      import numpy as np
      im = Image.open('hopper.jpg')
      a = np.asarray(im)

    Then this can be used to convert it to a Pillow image::

      im = Image.fromarray(a)

    :param obj: Object with array interface
    :param mode: Mode to use (will be determined from type if None)
      See: :ref:`concept-modes`.
    :returns: An image object.

    .. versionadded:: 1.1.6
    """
    arr = obj.__array_interface__
    shape = arr["shape"]
    ndim = len(shape)
    strides = arr.get("strides", None)
    if mode is None:
        try:
            typekey = (1, 1) + shape[2:], arr["typestr"]
        except KeyError:
            raise TypeError("Cannot handle this data type")
        try:
            mode, rawmode = _fromarray_typemap[typekey]
        except KeyError:
            raise TypeError("Cannot handle this data type: %s, %s" % typekey)
    else:
        rawmode = mode
    if mode in ["1", "L", "I", "P", "F"]:
        ndmax = 2
    elif mode == "RGB":
        ndmax = 3
    else:
        ndmax = 4
    if ndim > ndmax:
        raise ValueError("Too many dimensions: %d > %d." % (ndim, ndmax))

    size = 1 if ndim == 1 else shape[1], shape[0]
    if strides is not None:
        if hasattr(obj, "tobytes"):
            obj = obj.tobytes()
        else:
            obj = obj.tostring()

    return frombuffer(mode, size, obj, "raw", rawmode, 0, 1)


def fromqimage(im):
    """Creates an image instance from a QImage image"""
    from . import ImageQt

    if not ImageQt.qt_is_installed:
        raise ImportError("Qt bindings are not installed")
    return ImageQt.fromqimage(im)


def fromqpixmap(im):
    """Creates an image instance from a QPixmap image"""
    from . import ImageQt

    if not ImageQt.qt_is_installed:
        raise ImportError("Qt bindings are not installed")
    return ImageQt.fromqpixmap(im)


_fromarray_typemap = {
    # (shape, typestr) => mode, rawmode
    # first two members of shape are set to one
    ((1, 1), "|b1"): ("1", "1;8"),
    ((1, 1), "|u1"): ("L", "L"),
    ((1, 1), "|i1"): ("I", "I;8"),
    ((1, 1), "<u2"): ("I", "I;16"),
    ((1, 1), ">u2"): ("I", "I;16B"),
    ((1, 1), "<i2"): ("I", "I;16S"),
    ((1, 1), ">i2"): ("I", "I;16BS"),
    ((1, 1), "<u4"): ("I", "I;32"),
    ((1, 1), ">u4"): ("I", "I;32B"),
    ((1, 1), "<i4"): ("I", "I;32S"),
    ((1, 1), ">i4"): ("I", "I;32BS"),
    ((1, 1), "<f4"): ("F", "F;32F"),
    ((1, 1), ">f4"): ("F", "F;32BF"),
    ((1, 1), "<f8"): ("F", "F;64F"),
    ((1, 1), ">f8"): ("F", "F;64BF"),
    ((1, 1, 2), "|u1"): ("LA", "LA"),
    ((1, 1, 3), "|u1"): ("RGB", "RGB"),
    ((1, 1, 4), "|u1"): ("RGBA", "RGBA"),
}

# shortcuts
_fromarray_typemap[((1, 1), _ENDIAN + "i4")] = ("I", "I")
_fromarray_typemap[((1, 1), _ENDIAN + "f4")] = ("F", "F")


def _decompression_bomb_check(size):
    if MAX_IMAGE_PIXELS is None:
        return

    pixels = size[0] * size[1]

    if pixels > 2 * MAX_IMAGE_PIXELS:
        raise DecompressionBombError(
            "Image size (%d pixels) exceeds limit of %d pixels, "
            "could be decompression bomb DOS attack." % (pixels, 2 * MAX_IMAGE_PIXELS)
        )

    if pixels > MAX_IMAGE_PIXELS:
        warnings.warn(
            "Image size (%d pixels) exceeds limit of %d pixels, "
            "could be decompression bomb DOS attack." % (pixels, MAX_IMAGE_PIXELS),
            DecompressionBombWarning,
        )


def open(fp, mode="r"):
    """
    Opens and identifies the given image file.

    This is a lazy operation; this function identifies the file, but
    the file remains open and the actual image data is not read from
    the file until you try to process the data (or call the
    :py:meth:`~PIL.Image.Image.load` method).  See
    :py:func:`~PIL.Image.new`. See :ref:`file-handling`.

    :param fp: A filename (string), pathlib.Path object or a file object.
       The file object must implement :py:meth:`~file.read`,
       :py:meth:`~file.seek`, and :py:meth:`~file.tell` methods,
       and be opened in binary mode.
    :param mode: The mode.  If given, this argument must be "r".
    :returns: An :py:class:`~PIL.Image.Image` object.
    :exception FileNotFoundError: If the file cannot be found.
    :exception PIL.UnidentifiedImageError: If the image cannot be opened and
       identified.
    :exception ValueError: If the ``mode`` is not "r", or if a ``StringIO``
       instance is used for ``fp``.
    """

    if mode != "r":
        raise ValueError("bad mode %r" % mode)
    elif isinstance(fp, io.StringIO):
        raise ValueError(
            "StringIO cannot be used to open an image. "
            "Binary data must be used instead."
        )

    exclusive_fp = False
    filename = ""
    if isinstance(fp, Path):
        filename = str(fp.resolve())
    elif isPath(fp):
        filename = fp

    if filename:
        fp = builtins.open(filename, "rb")
        exclusive_fp = True

    try:
        fp.seek(0)
    except (AttributeError, io.UnsupportedOperation):
        fp = io.BytesIO(fp.read())
        exclusive_fp = True

    prefix = fp.read(16)

    preinit()

    accept_warnings = []

    def _open_core(fp, filename, prefix):
        for i in ID:
            try:
                factory, accept = OPEN[i]
                result = not accept or accept(prefix)
                if type(result) in [str, bytes]:
                    accept_warnings.append(result)
                elif result:
                    fp.seek(0)
                    im = factory(fp, filename)
                    _decompression_bomb_check(im.size)
                    return im
            except (SyntaxError, IndexError, TypeError, struct.error):
                # Leave disabled by default, spams the logs with image
                # opening failures that are entirely expected.
                # logger.debug("", exc_info=True)
                continue
            except BaseException:
                if exclusive_fp:
                    fp.close()
                raise
        return None

    im = _open_core(fp, filename, prefix)

    if im is None:
        if init():
            im = _open_core(fp, filename, prefix)

    if im:
        im._exclusive_fp = exclusive_fp
        return im

    if exclusive_fp:
        fp.close()
    for message in accept_warnings:
        warnings.warn(message)
    raise UnidentifiedImageError(
        "cannot identify image file %r" % (filename if filename else fp)
    )


#
# Image processing.


def alpha_composite(im1, im2):
    """
    Alpha composite im2 over im1.

    :param im1: The first image. Must have mode RGBA.
    :param im2: The second image.  Must have mode RGBA, and the same size as
       the first image.
    :returns: An :py:class:`~PIL.Image.Image` object.
    """

    im1.load()
    im2.load()
    return im1._new(core.alpha_composite(im1.im, im2.im))


def blend(im1, im2, alpha):
    """
    Creates a new image by interpolating between two input images, using
    a constant alpha.::

        out = image1 * (1.0 - alpha) + image2 * alpha

    :param im1: The first image.
    :param im2: The second image.  Must have the same mode and size as
       the first image.
    :param alpha: The interpolation alpha factor.  If alpha is 0.0, a
       copy of the first image is returned. If alpha is 1.0, a copy of
       the second image is returned. There are no restrictions on the
       alpha value. If necessary, the result is clipped to fit into
       the allowed output range.
    :returns: An :py:class:`~PIL.Image.Image` object.
    """

    im1.load()
    im2.load()
    return im1._new(core.blend(im1.im, im2.im, alpha))


def composite(image1, image2, mask):
    """
    Create composite image by blending images using a transparency mask.

    :param image1: The first image.
    :param image2: The second image.  Must have the same mode and
       size as the first image.
    :param mask: A mask image.  This image can have mode
       "1", "L", or "RGBA", and must have the same size as the
       other two images.
    """

    image = image2.copy()
    image.paste(image1, None, mask)
    return image


def eval(image, *args):
    """
    Applies the function (which should take one argument) to each pixel
    in the given image. If the image has more than one band, the same
    function is applied to each band. Note that the function is
    evaluated once for each possible pixel value, so you cannot use
    random components or other generators.

    :param image: The input image.
    :param function: A function object, taking one integer argument.
    :returns: An :py:class:`~PIL.Image.Image` object.
    """

    return image.point(args[0])


def merge(mode, bands):
    """
    Merge a set of single band images into a new multiband image.

    :param mode: The mode to use for the output image. See:
        :ref:`concept-modes`.
    :param bands: A sequence containing one single-band image for
        each band in the output image.  All bands must have the
        same size.
    :returns: An :py:class:`~PIL.Image.Image` object.
    """

    if getmodebands(mode) != len(bands) or "*" in mode:
        raise ValueError("wrong number of bands")
    for band in bands[1:]:
        if band.mode != getmodetype(mode):
            raise ValueError("mode mismatch")
        if band.size != bands[0].size:
            raise ValueError("size mismatch")
    for band in bands:
        band.load()
    return bands[0]._new(core.merge(mode, *[b.im for b in bands]))


# --------------------------------------------------------------------
# Plugin registry


def register_open(id, factory, accept=None):
    """
    Register an image file plugin.  This function should not be used
    in application code.

    :param id: An image format identifier.
    :param factory: An image file factory method.
    :param accept: An optional function that can be used to quickly
       reject images having another format.
    """
    id = id.upper()
    ID.append(id)
    OPEN[id] = factory, accept


def register_mime(id, mimetype):
    """
    Registers an image MIME type.  This function should not be used
    in application code.

    :param id: An image format identifier.
    :param mimetype: The image MIME type for this format.
    """
    MIME[id.upper()] = mimetype


def register_save(id, driver):
    """
    Registers an image save function.  This function should not be
    used in application code.

    :param id: An image format identifier.
    :param driver: A function to save images in this format.
    """
    SAVE[id.upper()] = driver


def register_save_all(id, driver):
    """
    Registers an image function to save all the frames
    of a multiframe format.  This function should not be
    used in application code.

    :param id: An image format identifier.
    :param driver: A function to save images in this format.
    """
    SAVE_ALL[id.upper()] = driver


def register_extension(id, extension):
    """
    Registers an image extension.  This function should not be
    used in application code.

    :param id: An image format identifier.
    :param extension: An extension used for this format.
    """
    EXTENSION[extension.lower()] = id.upper()


def register_extensions(id, extensions):
    """
    Registers image extensions.  This function should not be
    used in application code.

    :param id: An image format identifier.
    :param extensions: A list of extensions used for this format.
    """
    for extension in extensions:
        register_extension(id, extension)


def registered_extensions():
    """
    Returns a dictionary containing all file extensions belonging
    to registered plugins
    """
    if not EXTENSION:
        init()
    return EXTENSION


def register_decoder(name, decoder):
    """
    Registers an image decoder.  This function should not be
    used in application code.

    :param name: The name of the decoder
    :param decoder: A callable(mode, args) that returns an
                    ImageFile.PyDecoder object

    .. versionadded:: 4.1.0
    """
    DECODERS[name] = decoder


def register_encoder(name, encoder):
    """
    Registers an image encoder.  This function should not be
    used in application code.

    :param name: The name of the encoder
    :param encoder: A callable(mode, args) that returns an
                    ImageFile.PyEncoder object

    .. versionadded:: 4.1.0
    """
    ENCODERS[name] = encoder


# --------------------------------------------------------------------
# Simple display support.  User code may override this.


def _show(image, **options):
    # override me, as necessary
    _showxv(image, **options)


def _showxv(image, title=None, **options):
    from . import ImageShow

    ImageShow.show(image, title, **options)


# --------------------------------------------------------------------
# Effects


def effect_mandelbrot(size, extent, quality):
    """
    Generate a Mandelbrot set covering the given extent.

    :param size: The requested size in pixels, as a 2-tuple:
       (width, height).
    :param extent: The extent to cover, as a 4-tuple:
       (x0, y0, x1, y2).
    :param quality: Quality.
    """
    return Image()._new(core.effect_mandelbrot(size, extent, quality))


def effect_noise(size, sigma):
    """
    Generate Gaussian noise centered around 128.

    :param size: The requested size in pixels, as a 2-tuple:
       (width, height).
    :param sigma: Standard deviation of noise.
    """
    return Image()._new(core.effect_noise(size, sigma))


def linear_gradient(mode):
    """
    Generate 256x256 linear gradient from black to white, top to bottom.

    :param mode: Input mode.
    """
    return Image()._new(core.linear_gradient(mode))


def radial_gradient(mode):
    """
    Generate 256x256 radial gradient from black to white, centre to edge.

    :param mode: Input mode.
    """
    return Image()._new(core.radial_gradient(mode))


# --------------------------------------------------------------------
# Resources


def _apply_env_variables(env=None):
    if env is None:
        env = os.environ

    for var_name, setter in [
        ("PILLOW_ALIGNMENT", core.set_alignment),
        ("PILLOW_BLOCK_SIZE", core.set_block_size),
        ("PILLOW_BLOCKS_MAX", core.set_blocks_max),
    ]:
        if var_name not in env:
            continue

        var = env[var_name].lower()

        units = 1
        for postfix, mul in [("k", 1024), ("m", 1024 * 1024)]:
            if var.endswith(postfix):
                units = mul
                var = var[: -len(postfix)]

        try:
            var = int(var) * units
        except ValueError:
            warnings.warn("{} is not int".format(var_name))
            continue

        try:
            setter(var)
        except ValueError as e:
            warnings.warn("{}: {}".format(var_name, e))


_apply_env_variables()
atexit.register(core.clear_cache)


class Exif(MutableMapping):
    endian = "<"

    def __init__(self):
        self._data = {}
        self._ifds = {}
        self._info = None
        self._loaded_exif = None

    def _fixup(self, value):
        try:
            if len(value) == 1 and not isinstance(value, dict):
                return value[0]
        except Exception:
            pass
        return value

    def _fixup_dict(self, src_dict):
        # Helper function for _getexif()
        # returns a dict with any single item tuples/lists as individual values
        return {k: self._fixup(v) for k, v in src_dict.items()}

    def _get_ifd_dict(self, tag):
        try:
            # an offset pointer to the location of the nested embedded IFD.
            # It should be a long, but may be corrupted.
            self.fp.seek(self[tag])
        except (KeyError, TypeError):
            pass
        else:
            from . import TiffImagePlugin

            info = TiffImagePlugin.ImageFileDirectory_v1(self.head)
            info.load(self.fp)
            return self._fixup_dict(info)

    def load(self, data):
        # Extract EXIF information.  This is highly experimental,
        # and is likely to be replaced with something better in a future
        # version.

        # The EXIF record consists of a TIFF file embedded in a JPEG
        # application marker (!).
        if data == self._loaded_exif:
            return
        self._loaded_exif = data
        self._data.clear()
        self._ifds.clear()
        self._info = None
        if not data:
            return

        if data.startswith(b"Exif\x00\x00"):
            data = data[6:]
        self.fp = io.BytesIO(data)
        self.head = self.fp.read(8)
        # process dictionary
        from . import TiffImagePlugin

        self._info = TiffImagePlugin.ImageFileDirectory_v1(self.head)
        self.endian = self._info._endian
        self.fp.seek(self._info.next)
        self._info.load(self.fp)

        # get EXIF extension
        ifd = self._get_ifd_dict(0x8769)
        if ifd:
            self._data.update(ifd)
            self._ifds[0x8769] = ifd

    def tobytes(self, offset=8):
        from . import TiffImagePlugin

        if self.endian == "<":
            head = b"II\x2A\x00\x08\x00\x00\x00"
        else:
            head = b"MM\x00\x2A\x00\x00\x00\x08"
        ifd = TiffImagePlugin.ImageFileDirectory_v2(ifh=head)
        for tag, value in self.items():
            ifd[tag] = value
        return b"Exif\x00\x00" + head + ifd.tobytes(offset)

    def get_ifd(self, tag):
        if tag not in self._ifds and tag in self:
            if tag in [0x8825, 0xA005]:
                # gpsinfo, interop
                self._ifds[tag] = self._get_ifd_dict(tag)
            elif tag == 0x927C:  # makernote
                from .TiffImagePlugin import ImageFileDirectory_v2

                if self[0x927C][:8] == b"FUJIFILM":
                    exif_data = self[0x927C]
                    ifd_offset = i32le(exif_data[8:12])
                    ifd_data = exif_data[ifd_offset:]

                    makernote = {}
                    for i in range(0, struct.unpack("<H", ifd_data[:2])[0]):
                        ifd_tag, typ, count, data = struct.unpack(
                            "<HHL4s", ifd_data[i * 12 + 2 : (i + 1) * 12 + 2]
                        )
                        try:
                            unit_size, handler = ImageFileDirectory_v2._load_dispatch[
                                typ
                            ]
                        except KeyError:
                            continue
                        size = count * unit_size
                        if size > 4:
                            (offset,) = struct.unpack("<L", data)
                            data = ifd_data[offset - 12 : offset + size - 12]
                        else:
                            data = data[:size]

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

                        if not data:
                            continue

                        makernote[ifd_tag] = handler(
                            ImageFileDirectory_v2(), data, False
                        )
                    self._ifds[0x927C] = dict(self._fixup_dict(makernote))
                elif self.get(0x010F) == "Nintendo":
                    ifd_data = self[0x927C]

                    makernote = {}
                    for i in range(0, struct.unpack(">H", ifd_data[:2])[0]):
                        ifd_tag, typ, count, data = struct.unpack(
                            ">HHL4s", ifd_data[i * 12 + 2 : (i + 1) * 12 + 2]
                        )
                        if ifd_tag == 0x1101:
                            # CameraInfo
                            (offset,) = struct.unpack(">L", data)
                            self.fp.seek(offset)

                            camerainfo = {"ModelID": self.fp.read(4)}

                            self.fp.read(4)
                            # Seconds since 2000
                            camerainfo["TimeStamp"] = i32le(self.fp.read(12))

                            self.fp.read(4)
                            camerainfo["InternalSerialNumber"] = self.fp.read(4)

                            self.fp.read(12)
                            parallax = self.fp.read(4)
                            handler = ImageFileDirectory_v2._load_dispatch[
                                TiffTags.FLOAT
                            ][1]
                            camerainfo["Parallax"] = handler(
                                ImageFileDirectory_v2(), parallax, False
                            )

                            self.fp.read(4)
                            camerainfo["Category"] = self.fp.read(2)

                            makernote = {0x1101: dict(self._fixup_dict(camerainfo))}
                    self._ifds[0x927C] = makernote
        return self._ifds.get(tag, {})

    def __str__(self):
        if self._info is not None:
            # Load all keys into self._data
            for tag in self._info.keys():
                self[tag]

        return str(self._data)

    def __len__(self):
        keys = set(self._data)
        if self._info is not None:
            keys.update(self._info)
        return len(keys)

    def __getitem__(self, tag):
        if self._info is not None and tag not in self._data and tag in self._info:
            self._data[tag] = self._fixup(self._info[tag])
            if tag == 0x8825:
                self._data[tag] = self.get_ifd(tag)
            del self._info[tag]
        return self._data[tag]

    def __contains__(self, tag):
        return tag in self._data or (self._info is not None and tag in self._info)

    def __setitem__(self, tag, value):
        if self._info is not None and tag in self._info:
            del self._info[tag]
        self._data[tag] = value

    def __delitem__(self, tag):
        if self._info is not None and tag in self._info:
            del self._info[tag]
        del self._data[tag]

    def __iter__(self):
        keys = set(self._data)
        if self._info is not None:
            keys.update(self._info)
        return iter(keys)

```
--- 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:** Setting EXIF X-Resolution Causes TypeError During Image Save

**Description:**
When attempting to set the EXIF `XResolution` to an integer value and save the image, a `TypeError` is raised unexpectedly. This issue occurs even though the `XResolution` should accept integer values and handle them correctly during the save operation.

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

def set_exif_x_resolution(image_path, output_path):
    with Image.open(image_path) as img:
        exif = img.getexif()
        exif[282] = 180  # Set XResolution to 180
        img.save(output_path, exif=exif)

set_exif_x_resolution("flower.jpg", "out.jpg")
```

**Expected Behavior:**
The image should be saved successfully with the `XResolution` EXIF tag set to `180`. The operation should complete without any errors, and the saved image should retain the specified resolution metadata.

**Actual Behavior:**
A `TypeError` is raised during the save operation, preventing the image from being saved with the updated EXIF data. This error suggests that the EXIF `XResolution` value is not being handled correctly when assigned an integer.

[/ISSUE]
{
    "TestFileJpeg.test_sanity": "PASSED",
    "TestFileJpeg.test_app": "PASSED",
    "TestFileJpeg.test_cmyk": "PASSED",
    "TestFileJpeg.test_dpi": "PASSED",
    "TestFileJpeg.test_icc": "PASSED",
    "TestFileJpeg.test_icc_big": "PASSED",
    "TestFileJpeg.test_large_icc_meta": "PASSED",
    "TestFileJpeg.test_optimize": "PASSED",
    "TestFileJpeg.test_optimize_large_buffer": "PASSED",
    "TestFileJpeg.test_progressive": "PASSED",
    "TestFileJpeg.test_progressive_large_buffer": "PASSED",
    "TestFileJpeg.test_progressive_large_buffer_highest_quality": "PASSED",
    "TestFileJpeg.test_progressive_cmyk_buffer": "PASSED",
    "TestFileJpeg.test_large_exif": "PASSED",
    "TestFileJpeg.test_exif_typeerror": "PASSED",
    "TestFileJpeg.test_exif_gps": "PASSED",
    "TestFileJpeg.test_exif_rollback": "PASSED",
    "TestFileJpeg.test_exif_gps_typeerror": "PASSED",
    "TestFileJpeg.test_progressive_compat": "PASSED",
    "TestFileJpeg.test_quality": "PASSED",
    "TestFileJpeg.test_smooth": "PASSED",
    "TestFileJpeg.test_subsampling": "PASSED",
    "TestFileJpeg.test_exif": "PASSED",
    "TestFileJpeg.test_mp": "PASSED",
    "TestFileJpeg.test_quality_keep": "PASSED",
    "TestFileJpeg.test_junk_jpeg_header": "PASSED",
    "TestFileJpeg.test_ff00_jpeg_header": "PASSED",
    "TestFileJpeg.test_truncated_jpeg_should_read_all_the_data": "PASSED",
    "TestFileJpeg.test_truncated_jpeg_throws_oserror": "PASSED",
    "TestFileJpeg.test_qtables": "PASSED",
    "TestFileJpeg.test_no_duplicate_0x1001_tag": "PASSED",
    "TestFileJpeg.test_MAXBLOCK_scaling": "PASSED",
    "TestFileJpeg.test_bad_mpo_header": "PASSED",
    "TestFileJpeg.test_save_correct_modes": "PASSED",
    "TestFileJpeg.test_save_wrong_modes": "PASSED",
    "TestFileJpeg.test_save_tiff_with_dpi": "PASSED",
    "TestFileJpeg.test_load_dpi_rounding": "PASSED",
    "TestFileJpeg.test_save_dpi_rounding": "PASSED",
    "TestFileJpeg.test_dpi_tuple_from_exif": "PASSED",
    "TestFileJpeg.test_dpi_int_from_exif": "PASSED",
    "TestFileJpeg.test_dpi_from_dpcm_exif": "PASSED",
    "TestFileJpeg.test_dpi_exif_zero_division": "PASSED",
    "TestFileJpeg.test_no_dpi_in_exif": "PASSED",
    "TestFileJpeg.test_invalid_exif": "PASSED",
    "TestFileJpeg.test_invalid_exif_x_resolution": "PASSED",
    "TestFileJpeg.test_ifd_offset_exif": "PASSED",
    "TestFileJpeg.test_photoshop": "PASSED",
    "TestFileJpeg.test_photoshop_malformed_and_multiple": "PASSED",
    "TestFileJpeg.test_icc_after_SOF": "PASSED",
    "TestFileJpeg.test_exif_x_resolution": "FAILED"
}
diff --git a/src/PIL/Image.py b/src/PIL/Image.py
index 038829213..bb81750e6 100644
--- a/src/PIL/Image.py
+++ b/src/PIL/Image.py
@@ -3248,7 +3248,7 @@ class Exif(MutableMapping):
 
     def _fixup(self, value):
         try:
-            if len(value) == 1 and not isinstance(value, dict):
+            if len(value) == 1 and isinstance(value, tuple):
                 return value[0]
         except Exception:
             pass
@@ -3269,7 +3269,7 @@ class Exif(MutableMapping):
         else:
             from . import TiffImagePlugin
 
-            info = TiffImagePlugin.ImageFileDirectory_v1(self.head)
+            info = TiffImagePlugin.ImageFileDirectory_v2(self.head)
             info.load(self.fp)
             return self._fixup_dict(info)
 
@@ -3296,7 +3296,7 @@ class Exif(MutableMapping):
         # process dictionary
         from . import TiffImagePlugin
 
-        self._info = TiffImagePlugin.ImageFileDirectory_v1(self.head)
+        self._info = TiffImagePlugin.ImageFileDirectory_v2(self.head)
         self.endian = self._info._endian
         self.fp.seek(self._info.next)
         self._info.load(self.fp)
 

{"src/PIL/Image.py": "#\n# The Python Imaging Library.\n# $Id$\n#\n# the Image class wrapper\n#\n# partial release history:\n# 1995-09-09 fl   Created\n# 1996-03-11 fl   PIL release 0.0 (proof of concept)\n# 1996-04-30 fl   PIL release 0.1b1\n# 1999-07-28 fl   PIL release 1.0 final\n# 2000-06-07 fl   PIL release 1.1\n# 2000-10-20 fl   PIL release 1.1.1\n# 2001-05-07 fl   PIL release 1.1.2\n# 2002-03-15 fl   PIL release 1.1.3\n# 2003-05-10 fl   PIL release 1.1.4\n# 2005-03-28 fl   PIL release 1.1.5\n# 2006-12-02 fl   PIL release 1.1.6\n# 2009-11-15 fl   PIL release 1.1.7\n#\n# Copyright (c) 1997-2009 by Secret Labs AB.  All rights reserved.\n# Copyright (c) 1995-2009 by Fredrik Lundh.\n#\n# See the README file for information on usage and redistribution.\n#\n\nimport atexit\nimport builtins\nimport io\nimport logging\nimport math\nimport numbers\nimport os\nimport struct\nimport sys\nimport tempfile\nimport warnings\nimport xml.etree.ElementTree\nfrom collections.abc import Callable, MutableMapping\nfrom pathlib import Path\n\n# VERSION was removed in Pillow 6.0.0.\n# PILLOW_VERSION is deprecated and will be removed in a future release.\n# Use __version__ instead.\nfrom . import (\n    ImageMode,\n    TiffTags,\n    UnidentifiedImageError,\n    __version__,\n    _plugins,\n    _raise_version_warning,\n)\nfrom ._binary import i8, i32le\nfrom ._util import deferred_error, isPath\n\nif sys.version_info >= (3, 7):\n\n    def __getattr__(name):\n        if name == \"PILLOW_VERSION\":\n            _raise_version_warning()\n            return __version__\n        raise AttributeError(\"module '{}' has no attribute '{}'\".format(__name__, name))\n\n\nelse:\n\n    from . import PILLOW_VERSION\n\n    # Silence warning\n    assert PILLOW_VERSION\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass DecompressionBombWarning(RuntimeWarning):\n    pass\n\n\nclass DecompressionBombError(Exception):\n    pass\n\n\n# Limit to around a quarter gigabyte for a 24 bit (3 bpp) image\nMAX_IMAGE_PIXELS = int(1024 * 1024 * 1024 // 4 // 3)\n\n\ntry:\n    # If the _imaging C module is not present, Pillow will not load.\n    # Note that other modules should not refer to _imaging directly;\n    # import Image and use the Image.core variable instead.\n    # Also note that Image.core is not a publicly documented interface,\n    # and should be considered private and subject to change.\n    from . import _imaging as core\n\n    if __version__ != getattr(core, \"PILLOW_VERSION\", None):\n        raise ImportError(\n            \"The _imaging extension was built for another version of Pillow or PIL:\\n\"\n            \"Core version: %s\\n\"\n            \"Pillow version: %s\" % (getattr(core, \"PILLOW_VERSION\", None), __version__)\n        )\n\nexcept ImportError as v:\n    core = deferred_error(ImportError(\"The _imaging C module is not installed.\"))\n    # Explanations for ways that we know we might have an import error\n    if str(v).startswith(\"Module use of python\"):\n        # The _imaging C module is present, but not compiled for\n        # the right version (windows only).  Print a warning, if\n        # possible.\n        warnings.warn(\n            \"The _imaging extension was built for another version of Python.\",\n            RuntimeWarning,\n        )\n    elif str(v).startswith(\"The _imaging extension\"):\n        warnings.warn(str(v), RuntimeWarning)\n    # Fail here anyway. Don't let people run with a mostly broken Pillow.\n    # see docs/porting.rst\n    raise\n\n\n# works everywhere, win for pypy, not cpython\nUSE_CFFI_ACCESS = hasattr(sys, \"pypy_version_info\")\ntry:\n    import cffi\nexcept ImportError:\n    cffi = None\n\n\ndef isImageType(t):\n    \"\"\"\n    Checks if an object is an image object.\n\n    .. warning::\n\n       This function is for internal use only.\n\n    :param t: object to check if it's an image\n    :returns: True if the object is an image\n    \"\"\"\n    return hasattr(t, \"im\")\n\n\n#\n# Constants\n\nNONE = 0\n\n# transpose\nFLIP_LEFT_RIGHT = 0\nFLIP_TOP_BOTTOM = 1\nROTATE_90 = 2\nROTATE_180 = 3\nROTATE_270 = 4\nTRANSPOSE = 5\nTRANSVERSE = 6\n\n# transforms (also defined in Imaging.h)\nAFFINE = 0\nEXTENT = 1\nPERSPECTIVE = 2\nQUAD = 3\nMESH = 4\n\n# resampling filters (also defined in Imaging.h)\nNEAREST = NONE = 0\nBOX = 4\nBILINEAR = LINEAR = 2\nHAMMING = 5\nBICUBIC = CUBIC = 3\nLANCZOS = ANTIALIAS = 1\n\n_filters_support = {BOX: 0.5, BILINEAR: 1.0, HAMMING: 1.0, BICUBIC: 2.0, LANCZOS: 3.0}\n\n\n# dithers\nNEAREST = NONE = 0\nORDERED = 1  # Not yet implemented\nRASTERIZE = 2  # Not yet implemented\nFLOYDSTEINBERG = 3  # default\n\n# palettes/quantizers\nWEB = 0\nADAPTIVE = 1\n\nMEDIANCUT = 0\nMAXCOVERAGE = 1\nFASTOCTREE = 2\nLIBIMAGEQUANT = 3\n\n# categories\nNORMAL = 0\nSEQUENCE = 1\nCONTAINER = 2\n\nif hasattr(core, \"DEFAULT_STRATEGY\"):\n    DEFAULT_STRATEGY = core.DEFAULT_STRATEGY\n    FILTERED = core.FILTERED\n    HUFFMAN_ONLY = core.HUFFMAN_ONLY\n    RLE = core.RLE\n    FIXED = core.FIXED\n\n\n# --------------------------------------------------------------------\n# Registries\n\nID = []\nOPEN = {}\nMIME = {}\nSAVE = {}\nSAVE_ALL = {}\nEXTENSION = {}\nDECODERS = {}\nENCODERS = {}\n\n# --------------------------------------------------------------------\n# Modes supported by this version\n\n_MODEINFO = {\n    # NOTE: this table will be removed in future versions.  use\n    # getmode* functions or ImageMode descriptors instead.\n    # official modes\n    \"1\": (\"L\", \"L\", (\"1\",)),\n    \"L\": (\"L\", \"L\", (\"L\",)),\n    \"I\": (\"L\", \"I\", (\"I\",)),\n    \"F\": (\"L\", \"F\", (\"F\",)),\n    \"P\": (\"P\", \"L\", (\"P\",)),\n    \"RGB\": (\"RGB\", \"L\", (\"R\", \"G\", \"B\")),\n    \"RGBX\": (\"RGB\", \"L\", (\"R\", \"G\", \"B\", \"X\")),\n    \"RGBA\": (\"RGB\", \"L\", (\"R\", \"G\", \"B\", \"A\")),\n    \"CMYK\": (\"RGB\", \"L\", (\"C\", \"M\", \"Y\", \"K\")),\n    \"YCbCr\": (\"RGB\", \"L\", (\"Y\", \"Cb\", \"Cr\")),\n    \"LAB\": (\"RGB\", \"L\", (\"L\", \"A\", \"B\")),\n    \"HSV\": (\"RGB\", \"L\", (\"H\", \"S\", \"V\")),\n    # Experimental modes include I;16, I;16L, I;16B, RGBa, BGR;15, and\n    # BGR;24.  Use these modes only if you know exactly what you're\n    # doing...\n}\n\nif sys.byteorder == \"little\":\n    _ENDIAN = \"<\"\nelse:\n    _ENDIAN = \">\"\n\n_MODE_CONV = {\n    # official modes\n    \"1\": (\"|b1\", None),  # Bits need to be extended to bytes\n    \"L\": (\"|u1\", None),\n    \"LA\": (\"|u1\", 2),\n    \"I\": (_ENDIAN + \"i4\", None),\n    \"F\": (_ENDIAN + \"f4\", None),\n    \"P\": (\"|u1\", None),\n    \"RGB\": (\"|u1\", 3),\n    \"RGBX\": (\"|u1\", 4),\n    \"RGBA\": (\"|u1\", 4),\n    \"CMYK\": (\"|u1\", 4),\n    \"YCbCr\": (\"|u1\", 3),\n    \"LAB\": (\"|u1\", 3),  # UNDONE - unsigned |u1i1i1\n    \"HSV\": (\"|u1\", 3),\n    # I;16 == I;16L, and I;32 == I;32L\n    \"I;16\": (\"<u2\", None),\n    \"I;16B\": (\">u2\", None),\n    \"I;16L\": (\"<u2\", None),\n    \"I;16S\": (\"<i2\", None),\n    \"I;16BS\": (\">i2\", None),\n    \"I;16LS\": (\"<i2\", None),\n    \"I;32\": (\"<u4\", None),\n    \"I;32B\": (\">u4\", None),\n    \"I;32L\": (\"<u4\", None),\n    \"I;32S\": (\"<i4\", None),\n    \"I;32BS\": (\">i4\", None),\n    \"I;32LS\": (\"<i4\", None),\n}\n\n\ndef _conv_type_shape(im):\n    typ, extra = _MODE_CONV[im.mode]\n    if extra is None:\n        return (im.size[1], im.size[0]), typ\n    else:\n        return (im.size[1], im.size[0], extra), typ\n\n\nMODES = sorted(_MODEINFO)\n\n# raw modes that may be memory mapped.  NOTE: if you change this, you\n# may have to modify the stride calculation in map.c too!\n_MAPMODES = (\"L\", \"P\", \"RGBX\", \"RGBA\", \"CMYK\", \"I;16\", \"I;16L\", \"I;16B\")\n\n\ndef getmodebase(mode):\n    \"\"\"\n    Gets the \"base\" mode for given mode.  This function returns \"L\" for\n    images that contain grayscale data, and \"RGB\" for images that\n    contain color data.\n\n    :param mode: Input mode.\n    :returns: \"L\" or \"RGB\".\n    :exception KeyError: If the input mode was not a standard mode.\n    \"\"\"\n    return ImageMode.getmode(mode).basemode\n\n\ndef getmodetype(mode):\n    \"\"\"\n    Gets the storage type mode.  Given a mode, this function returns a\n    single-layer mode suitable for storing individual bands.\n\n    :param mode: Input mode.\n    :returns: \"L\", \"I\", or \"F\".\n    :exception KeyError: If the input mode was not a standard mode.\n    \"\"\"\n    return ImageMode.getmode(mode).basetype\n\n\ndef getmodebandnames(mode):\n    \"\"\"\n    Gets a list of individual band names.  Given a mode, this function returns\n    a tuple containing the names of individual bands (use\n    :py:method:`~PIL.Image.getmodetype` to get the mode used to store each\n    individual band.\n\n    :param mode: Input mode.\n    :returns: A tuple containing band names.  The length of the tuple\n        gives the number of bands in an image of the given mode.\n    :exception KeyError: If the input mode was not a standard mode.\n    \"\"\"\n    return ImageMode.getmode(mode).bands\n\n\ndef getmodebands(mode):\n    \"\"\"\n    Gets the number of individual bands for this mode.\n\n    :param mode: Input mode.\n    :returns: The number of bands in this mode.\n    :exception KeyError: If the input mode was not a standard mode.\n    \"\"\"\n    return len(ImageMode.getmode(mode).bands)\n\n\n# --------------------------------------------------------------------\n# Helpers\n\n_initialized = 0\n\n\ndef preinit():\n    \"\"\"Explicitly load standard file format drivers.\"\"\"\n\n    global _initialized\n    if _initialized >= 1:\n        return\n\n    try:\n        from . import BmpImagePlugin\n\n        assert BmpImagePlugin\n    except ImportError:\n        pass\n    try:\n        from . import GifImagePlugin\n\n        assert GifImagePlugin\n    except ImportError:\n        pass\n    try:\n        from . import JpegImagePlugin\n\n        assert JpegImagePlugin\n    except ImportError:\n        pass\n    try:\n        from . import PpmImagePlugin\n\n        assert PpmImagePlugin\n    except ImportError:\n        pass\n    try:\n        from . import PngImagePlugin\n\n        assert PngImagePlugin\n    except ImportError:\n        pass\n    # try:\n    #     import TiffImagePlugin\n    #     assert TiffImagePlugin\n    # except ImportError:\n    #     pass\n\n    _initialized = 1\n\n\ndef init():\n    \"\"\"\n    Explicitly initializes the Python Imaging Library. This function\n    loads all available file format drivers.\n    \"\"\"\n\n    global _initialized\n    if _initialized >= 2:\n        return 0\n\n    for plugin in _plugins:\n        try:\n            logger.debug(\"Importing %s\", plugin)\n            __import__(\"PIL.%s\" % plugin, globals(), locals(), [])\n        except ImportError as e:\n            logger.debug(\"Image: failed to import %s: %s\", plugin, e)\n\n    if OPEN or SAVE:\n        _initialized = 2\n        return 1\n\n\n# --------------------------------------------------------------------\n# Codec factories (used by tobytes/frombytes and ImageFile.load)\n\n\ndef _getdecoder(mode, decoder_name, args, extra=()):\n\n    # tweak arguments\n    if args is None:\n        args = ()\n    elif not isinstance(args, tuple):\n        args = (args,)\n\n    try:\n        decoder = DECODERS[decoder_name]\n    except KeyError:\n        pass\n    else:\n        return decoder(mode, *args + extra)\n\n    try:\n        # get decoder\n        decoder = getattr(core, decoder_name + \"_decoder\")\n    except AttributeError:\n        raise OSError(\"decoder %s not available\" % decoder_name)\n    return decoder(mode, *args + extra)\n\n\ndef _getencoder(mode, encoder_name, args, extra=()):\n\n    # tweak arguments\n    if args is None:\n        args = ()\n    elif not isinstance(args, tuple):\n        args = (args,)\n\n    try:\n        encoder = ENCODERS[encoder_name]\n    except KeyError:\n        pass\n    else:\n        return encoder(mode, *args + extra)\n\n    try:\n        # get encoder\n        encoder = getattr(core, encoder_name + \"_encoder\")\n    except AttributeError:\n        raise OSError(\"encoder %s not available\" % encoder_name)\n    return encoder(mode, *args + extra)\n\n\n# --------------------------------------------------------------------\n# Simple expression analyzer\n\n\ndef coerce_e(value):\n    return value if isinstance(value, _E) else _E(value)\n\n\nclass _E:\n    def __init__(self, data):\n        self.data = data\n\n    def __add__(self, other):\n        return _E((self.data, \"__add__\", coerce_e(other).data))\n\n    def __mul__(self, other):\n        return _E((self.data, \"__mul__\", coerce_e(other).data))\n\n\ndef _getscaleoffset(expr):\n    stub = [\"stub\"]\n    data = expr(_E(stub)).data\n    try:\n        (a, b, c) = data  # simplified syntax\n        if a is stub and b == \"__mul__\" and isinstance(c, numbers.Number):\n            return c, 0.0\n        if a is stub and b == \"__add__\" and isinstance(c, numbers.Number):\n            return 1.0, c\n    except TypeError:\n        pass\n    try:\n        ((a, b, c), d, e) = data  # full syntax\n        if (\n            a is stub\n            and b == \"__mul__\"\n            and isinstance(c, numbers.Number)\n            and d == \"__add__\"\n            and isinstance(e, numbers.Number)\n        ):\n            return c, e\n    except TypeError:\n        pass\n    raise ValueError(\"illegal expression\")\n\n\n# --------------------------------------------------------------------\n# Implementation wrapper\n\n\nclass Image:\n    \"\"\"\n    This class represents an image object.  To create\n    :py:class:`~PIL.Image.Image` objects, use the appropriate factory\n    functions.  There's hardly ever any reason to call the Image constructor\n    directly.\n\n    * :py:func:`~PIL.Image.open`\n    * :py:func:`~PIL.Image.new`\n    * :py:func:`~PIL.Image.frombytes`\n    \"\"\"\n\n    format = None\n    format_description = None\n    _close_exclusive_fp_after_loading = True\n\n    def __init__(self):\n        # FIXME: take \"new\" parameters / other image?\n        # FIXME: turn mode and size into delegating properties?\n        self.im = None\n        self.mode = \"\"\n        self._size = (0, 0)\n        self.palette = None\n        self.info = {}\n        self.category = NORMAL\n        self.readonly = 0\n        self.pyaccess = None\n        self._exif = None\n\n    @property\n    def width(self):\n        return self.size[0]\n\n    @property\n    def height(self):\n        return self.size[1]\n\n    @property\n    def size(self):\n        return self._size\n\n    def _new(self, im):\n        new = Image()\n        new.im = im\n        new.mode = im.mode\n        new._size = im.size\n        if im.mode in (\"P\", \"PA\"):\n            if self.palette:\n                new.palette = self.palette.copy()\n            else:\n                from . import ImagePalette\n\n                new.palette = ImagePalette.ImagePalette()\n        new.info = self.info.copy()\n        return new\n\n    # Context manager support\n    def __enter__(self):\n        return self\n\n    def __exit__(self, *args):\n        if hasattr(self, \"fp\") and getattr(self, \"_exclusive_fp\", False):\n            if hasattr(self, \"_close__fp\"):\n                self._close__fp()\n            if self.fp:\n                self.fp.close()\n        self.fp = None\n\n    def close(self):\n        \"\"\"\n        Closes the file pointer, if possible.\n\n        This operation will destroy the image core and release its memory.\n        The image data will be unusable afterward.\n\n        This function is only required to close images that have not\n        had their file read and closed by the\n        :py:meth:`~PIL.Image.Image.load` method. See\n        :ref:`file-handling` for more information.\n        \"\"\"\n        try:\n            if hasattr(self, \"_close__fp\"):\n                self._close__fp()\n            self.fp.close()\n            self.fp = None\n        except Exception as msg:\n            logger.debug(\"Error closing: %s\", msg)\n\n        if getattr(self, \"map\", None):\n            self.map = None\n\n        # Instead of simply setting to None, we're setting up a\n        # deferred error that will better explain that the core image\n        # object is gone.\n        self.im = deferred_error(ValueError(\"Operation on closed image\"))\n\n    def _copy(self):\n        self.load()\n        self.im = self.im.copy()\n        self.pyaccess = None\n        self.readonly = 0\n\n    def _ensure_mutable(self):\n        if self.readonly:\n            self._copy()\n        else:\n            self.load()\n\n    def _dump(self, file=None, format=None, **options):\n        suffix = \"\"\n        if format:\n            suffix = \".\" + format\n\n        if not file:\n            f, filename = tempfile.mkstemp(suffix)\n            os.close(f)\n        else:\n            filename = file\n            if not filename.endswith(suffix):\n                filename = filename + suffix\n\n        self.load()\n\n        if not format or format == \"PPM\":\n            self.im.save_ppm(filename)\n        else:\n            self.save(filename, format, **options)\n\n        return filename\n\n    def __eq__(self, other):\n        return (\n            self.__class__ is other.__class__\n            and self.mode == other.mode\n            and self.size == other.size\n            and self.info == other.info\n            and self.category == other.category\n            and self.readonly == other.readonly\n            and self.getpalette() == other.getpalette()\n            and self.tobytes() == other.tobytes()\n        )\n\n    def __repr__(self):\n        return \"<%s.%s image mode=%s size=%dx%d at 0x%X>\" % (\n            self.__class__.__module__,\n            self.__class__.__name__,\n            self.mode,\n            self.size[0],\n            self.size[1],\n            id(self),\n        )\n\n    def _repr_png_(self):\n        \"\"\" iPython display hook support\n\n        :returns: png version of the image as bytes\n        \"\"\"\n        b = io.BytesIO()\n        self.save(b, \"PNG\")\n        return b.getvalue()\n\n    @property\n    def __array_interface__(self):\n        # numpy array interface support\n        new = {}\n        shape, typestr = _conv_type_shape(self)\n        new[\"shape\"] = shape\n        new[\"typestr\"] = typestr\n        new[\"version\"] = 3\n        if self.mode == \"1\":\n            # Binary images need to be extended from bits to bytes\n            # See: https://github.com/python-pillow/Pillow/issues/350\n            new[\"data\"] = self.tobytes(\"raw\", \"L\")\n        else:\n            new[\"data\"] = self.tobytes()\n        return new\n\n    def __getstate__(self):\n        return [self.info, self.mode, self.size, self.getpalette(), self.tobytes()]\n\n    def __setstate__(self, state):\n        Image.__init__(self)\n        self.tile = []\n        info, mode, size, palette, data = state\n        self.info = info\n        self.mode = mode\n        self._size = size\n        self.im = core.new(mode, size)\n        if mode in (\"L\", \"LA\", \"P\", \"PA\") and palette:\n            self.putpalette(palette)\n        self.frombytes(data)\n\n    def tobytes(self, encoder_name=\"raw\", *args):\n        \"\"\"\n        Return image as a bytes object.\n\n        .. warning::\n\n            This method returns the raw image data from the internal\n            storage.  For compressed image data (e.g. PNG, JPEG) use\n            :meth:`~.save`, with a BytesIO parameter for in-memory\n            data.\n\n        :param encoder_name: What encoder to use.  The default is to\n                             use the standard \"raw\" encoder.\n        :param args: Extra arguments to the encoder.\n        :rtype: A bytes object.\n        \"\"\"\n\n        # may pass tuple instead of argument list\n        if len(args) == 1 and isinstance(args[0], tuple):\n            args = args[0]\n\n        if encoder_name == \"raw\" and args == ():\n            args = self.mode\n\n        self.load()\n\n        # unpack data\n        e = _getencoder(self.mode, encoder_name, args)\n        e.setimage(self.im)\n\n        bufsize = max(65536, self.size[0] * 4)  # see RawEncode.c\n\n        data = []\n        while True:\n            l, s, d = e.encode(bufsize)\n            data.append(d)\n            if s:\n                break\n        if s < 0:\n            raise RuntimeError(\"encoder error %d in tobytes\" % s)\n\n        return b\"\".join(data)\n\n    def tostring(self, *args, **kw):\n        raise NotImplementedError(\n            \"tostring() has been removed. Please call tobytes() instead.\"\n        )\n\n    def tobitmap(self, name=\"image\"):\n        \"\"\"\n        Returns the image converted to an X11 bitmap.\n\n        .. note:: This method only works for mode \"1\" images.\n\n        :param name: The name prefix to use for the bitmap variables.\n        :returns: A string containing an X11 bitmap.\n        :raises ValueError: If the mode is not \"1\"\n        \"\"\"\n\n        self.load()\n        if self.mode != \"1\":\n            raise ValueError(\"not a bitmap\")\n        data = self.tobytes(\"xbm\")\n        return b\"\".join(\n            [\n                (\"#define %s_width %d\\n\" % (name, self.size[0])).encode(\"ascii\"),\n                (\"#define %s_height %d\\n\" % (name, self.size[1])).encode(\"ascii\"),\n                (\"static char %s_bits[] = {\\n\" % name).encode(\"ascii\"),\n                data,\n                b\"};\",\n            ]\n        )\n\n    def frombytes(self, data, decoder_name=\"raw\", *args):\n        \"\"\"\n        Loads this image with pixel data from a bytes object.\n\n        This method is similar to the :py:func:`~PIL.Image.frombytes` function,\n        but loads data into this image instead of creating a new image object.\n        \"\"\"\n\n        # may pass tuple instead of argument list\n        if len(args) == 1 and isinstance(args[0], tuple):\n            args = args[0]\n\n        # default format\n        if decoder_name == \"raw\" and args == ():\n            args = self.mode\n\n        # unpack data\n        d = _getdecoder(self.mode, decoder_name, args)\n        d.setimage(self.im)\n        s = d.decode(data)\n\n        if s[0] >= 0:\n            raise ValueError(\"not enough image data\")\n        if s[1] != 0:\n            raise ValueError(\"cannot decode image data\")\n\n    def fromstring(self, *args, **kw):\n        raise NotImplementedError(\n            \"fromstring() has been removed. Please call frombytes() instead.\"\n        )\n\n    def load(self):\n        \"\"\"\n        Allocates storage for the image and loads the pixel data.  In\n        normal cases, you don't need to call this method, since the\n        Image class automatically loads an opened image when it is\n        accessed for the first time.\n\n        If the file associated with the image was opened by Pillow, then this\n        method will close it. The exception to this is if the image has\n        multiple frames, in which case the file will be left open for seek\n        operations. See :ref:`file-handling` for more information.\n\n        :returns: An image access object.\n        :rtype: :ref:`PixelAccess` or :py:class:`PIL.PyAccess`\n        \"\"\"\n        if self.im and self.palette and self.palette.dirty:\n            # realize palette\n            self.im.putpalette(*self.palette.getdata())\n            self.palette.dirty = 0\n            self.palette.mode = \"RGB\"\n            self.palette.rawmode = None\n            if \"transparency\" in self.info:\n                if isinstance(self.info[\"transparency\"], int):\n                    self.im.putpalettealpha(self.info[\"transparency\"], 0)\n                else:\n                    self.im.putpalettealphas(self.info[\"transparency\"])\n                self.palette.mode = \"RGBA\"\n\n        if self.im:\n            if cffi and USE_CFFI_ACCESS:\n                if self.pyaccess:\n                    return self.pyaccess\n                from . import PyAccess\n\n                self.pyaccess = PyAccess.new(self, self.readonly)\n                if self.pyaccess:\n                    return self.pyaccess\n            return self.im.pixel_access(self.readonly)\n\n    def verify(self):\n        \"\"\"\n        Verifies the contents of a file. For data read from a file, this\n        method attempts to determine if the file is broken, without\n        actually decoding the image data.  If this method finds any\n        problems, it raises suitable exceptions.  If you need to load\n        the image after using this method, you must reopen the image\n        file.\n        \"\"\"\n        pass\n\n    def convert(self, mode=None, matrix=None, dither=None, palette=WEB, colors=256):\n        \"\"\"\n        Returns a converted copy of this image. For the \"P\" mode, this\n        method translates pixels through the palette.  If mode is\n        omitted, a mode is chosen so that all information in the image\n        and the palette can be represented without a palette.\n\n        The current version supports all possible conversions between\n        \"L\", \"RGB\" and \"CMYK.\" The **matrix** argument only supports \"L\"\n        and \"RGB\".\n\n        When translating a color image to greyscale (mode \"L\"),\n        the library uses the ITU-R 601-2 luma transform::\n\n            L = R * 299/1000 + G * 587/1000 + B * 114/1000\n\n        The default method of converting a greyscale (\"L\") or \"RGB\"\n        image into a bilevel (mode \"1\") image uses Floyd-Steinberg\n        dither to approximate the original image luminosity levels. If\n        dither is NONE, all values larger than 128 are set to 255 (white),\n        all other values to 0 (black). To use other thresholds, use the\n        :py:meth:`~PIL.Image.Image.point` method.\n\n        When converting from \"RGBA\" to \"P\" without a **matrix** argument,\n        this passes the operation to :py:meth:`~PIL.Image.Image.quantize`,\n        and **dither** and **palette** are ignored.\n\n        :param mode: The requested mode. See: :ref:`concept-modes`.\n        :param matrix: An optional conversion matrix.  If given, this\n           should be 4- or 12-tuple containing floating point values.\n        :param dither: Dithering method, used when converting from\n           mode \"RGB\" to \"P\" or from \"RGB\" or \"L\" to \"1\".\n           Available methods are NONE or FLOYDSTEINBERG (default).\n           Note that this is not used when **matrix** is supplied.\n        :param palette: Palette to use when converting from mode \"RGB\"\n           to \"P\".  Available palettes are WEB or ADAPTIVE.\n        :param colors: Number of colors to use for the ADAPTIVE palette.\n           Defaults to 256.\n        :rtype: :py:class:`~PIL.Image.Image`\n        :returns: An :py:class:`~PIL.Image.Image` object.\n        \"\"\"\n\n        self.load()\n\n        if not mode and self.mode == \"P\":\n            # determine default mode\n            if self.palette:\n                mode = self.palette.mode\n            else:\n                mode = \"RGB\"\n        if not mode or (mode == self.mode and not matrix):\n            return self.copy()\n\n        has_transparency = self.info.get(\"transparency\") is not None\n        if matrix:\n            # matrix conversion\n            if mode not in (\"L\", \"RGB\"):\n                raise ValueError(\"illegal conversion\")\n            im = self.im.convert_matrix(mode, matrix)\n            new = self._new(im)\n            if has_transparency and self.im.bands == 3:\n                transparency = new.info[\"transparency\"]\n\n                def convert_transparency(m, v):\n                    v = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * 0.5\n                    return max(0, min(255, int(v)))\n\n                if mode == \"L\":\n                    transparency = convert_transparency(matrix, transparency)\n                elif len(mode) == 3:\n                    transparency = tuple(\n                        [\n                            convert_transparency(\n                                matrix[i * 4 : i * 4 + 4], transparency\n                            )\n                            for i in range(0, len(transparency))\n                        ]\n                    )\n                new.info[\"transparency\"] = transparency\n            return new\n\n        if mode == \"P\" and self.mode == \"RGBA\":\n            return self.quantize(colors)\n\n        trns = None\n        delete_trns = False\n        # transparency handling\n        if has_transparency:\n            if self.mode in (\"1\", \"L\", \"I\", \"RGB\") and mode == \"RGBA\":\n                # Use transparent conversion to promote from transparent\n                # color to an alpha channel.\n                new_im = self._new(\n                    self.im.convert_transparent(mode, self.info[\"transparency\"])\n                )\n                del new_im.info[\"transparency\"]\n                return new_im\n            elif self.mode in (\"L\", \"RGB\", \"P\") and mode in (\"L\", \"RGB\", \"P\"):\n                t = self.info[\"transparency\"]\n                if isinstance(t, bytes):\n                    # Dragons. This can't be represented by a single color\n                    warnings.warn(\n                        \"Palette images with Transparency expressed in bytes should be \"\n                        \"converted to RGBA images\"\n                    )\n                    delete_trns = True\n                else:\n                    # get the new transparency color.\n                    # use existing conversions\n                    trns_im = Image()._new(core.new(self.mode, (1, 1)))\n                    if self.mode == \"P\":\n                        trns_im.putpalette(self.palette)\n                        if isinstance(t, tuple):\n                            try:\n                                t = trns_im.palette.getcolor(t)\n                            except Exception:\n                                raise ValueError(\n                                    \"Couldn't allocate a palette color for transparency\"\n                                )\n                    trns_im.putpixel((0, 0), t)\n\n                    if mode in (\"L\", \"RGB\"):\n                        trns_im = trns_im.convert(mode)\n                    else:\n                        # can't just retrieve the palette number, got to do it\n                        # after quantization.\n                        trns_im = trns_im.convert(\"RGB\")\n                    trns = trns_im.getpixel((0, 0))\n\n            elif self.mode == \"P\" and mode == \"RGBA\":\n                t = self.info[\"transparency\"]\n                delete_trns = True\n\n                if isinstance(t, bytes):\n                    self.im.putpalettealphas(t)\n                elif isinstance(t, int):\n                    self.im.putpalettealpha(t, 0)\n                else:\n                    raise ValueError(\"Transparency for P mode should be bytes or int\")\n\n        if mode == \"P\" and palette == ADAPTIVE:\n            im = self.im.quantize(colors)\n            new = self._new(im)\n            from . import ImagePalette\n\n            new.palette = ImagePalette.raw(\"RGB\", new.im.getpalette(\"RGB\"))\n            if delete_trns:\n                # This could possibly happen if we requantize to fewer colors.\n                # The transparency would be totally off in that case.\n                del new.info[\"transparency\"]\n            if trns is not None:\n                try:\n                    new.info[\"transparency\"] = new.palette.getcolor(trns)\n                except Exception:\n                    # if we can't make a transparent color, don't leave the old\n                    # transparency hanging around to mess us up.\n                    del new.info[\"transparency\"]\n                    warnings.warn(\"Couldn't allocate palette entry for transparency\")\n            return new\n\n        # colorspace conversion\n        if dither is None:\n            dither = FLOYDSTEINBERG\n\n        try:\n            im = self.im.convert(mode, dither)\n        except ValueError:\n            try:\n                # normalize source image and try again\n                im = self.im.convert(getmodebase(self.mode))\n                im = im.convert(mode, dither)\n            except KeyError:\n                raise ValueError(\"illegal conversion\")\n\n        new_im = self._new(im)\n        if delete_trns:\n            # crash fail if we leave a bytes transparency in an rgb/l mode.\n            del new_im.info[\"transparency\"]\n        if trns is not None:\n            if new_im.mode == \"P\":\n                try:\n                    new_im.info[\"transparency\"] = new_im.palette.getcolor(trns)\n                except Exception:\n                    del new_im.info[\"transparency\"]\n                    warnings.warn(\"Couldn't allocate palette entry for transparency\")\n            else:\n                new_im.info[\"transparency\"] = trns\n        return new_im\n\n    def quantize(self, colors=256, method=None, kmeans=0, palette=None, dither=1):\n        \"\"\"\n        Convert the image to 'P' mode with the specified number\n        of colors.\n\n        :param colors: The desired number of colors, <= 256\n        :param method: 0 = median cut\n                       1 = maximum coverage\n                       2 = fast octree\n                       3 = libimagequant\n        :param kmeans: Integer\n        :param palette: Quantize to the palette of given\n                        :py:class:`PIL.Image.Image`.\n        :param dither: Dithering method, used when converting from\n           mode \"RGB\" to \"P\" or from \"RGB\" or \"L\" to \"1\".\n           Available methods are NONE or FLOYDSTEINBERG (default).\n           Default: 1 (legacy setting)\n        :returns: A new image\n\n        \"\"\"\n\n        self.load()\n\n        if method is None:\n            # defaults:\n            method = 0\n            if self.mode == \"RGBA\":\n                method = 2\n\n        if self.mode == \"RGBA\" and method not in (2, 3):\n            # Caller specified an invalid mode.\n            raise ValueError(\n                \"Fast Octree (method == 2) and libimagequant (method == 3) \"\n                \"are the only valid methods for quantizing RGBA images\"\n            )\n\n        if palette:\n            # use palette from reference image\n            palette.load()\n            if palette.mode != \"P\":\n                raise ValueError(\"bad mode for palette image\")\n            if self.mode != \"RGB\" and self.mode != \"L\":\n                raise ValueError(\n                    \"only RGB or L mode images can be quantized to a palette\"\n                )\n            im = self.im.convert(\"P\", dither, palette.im)\n            return self._new(im)\n\n        im = self._new(self.im.quantize(colors, method, kmeans))\n\n        from . import ImagePalette\n\n        mode = im.im.getpalettemode()\n        im.palette = ImagePalette.ImagePalette(mode, im.im.getpalette(mode, mode))\n\n        return im\n\n    def copy(self):\n        \"\"\"\n        Copies this image. Use this method if you wish to paste things\n        into an image, but still retain the original.\n\n        :rtype: :py:class:`~PIL.Image.Image`\n        :returns: An :py:class:`~PIL.Image.Image` object.\n        \"\"\"\n        self.load()\n        return self._new(self.im.copy())\n\n    __copy__ = copy\n\n    def crop(self, box=None):\n        \"\"\"\n        Returns a rectangular region from this image. The box is a\n        4-tuple defining the left, upper, right, and lower pixel\n        coordinate. See :ref:`coordinate-system`.\n\n        Note: Prior to Pillow 3.4.0, this was a lazy operation.\n\n        :param box: The crop rectangle, as a (left, upper, right, lower)-tuple.\n        :rtype: :py:class:`~PIL.Image.Image`\n        :returns: An :py:class:`~PIL.Image.Image` object.\n        \"\"\"\n\n        if box is None:\n            return self.copy()\n\n        self.load()\n        return self._new(self._crop(self.im, box))\n\n    def _crop(self, im, box):\n        \"\"\"\n        Returns a rectangular region from the core image object im.\n\n        This is equivalent to calling im.crop((x0, y0, x1, y1)), but\n        includes additional sanity checks.\n\n        :param im: a core image object\n        :param box: The crop rectangle, as a (left, upper, right, lower)-tuple.\n        :returns: A core image object.\n        \"\"\"\n\n        x0, y0, x1, y1 = map(int, map(round, box))\n\n        absolute_values = (abs(x1 - x0), abs(y1 - y0))\n\n        _decompression_bomb_check(absolute_values)\n\n        return im.crop((x0, y0, x1, y1))\n\n    def draft(self, mode, size):\n        \"\"\"\n        Configures the image file loader so it returns a version of the\n        image that as closely as possible matches the given mode and\n        size. For example, you can use this method to convert a color\n        JPEG to greyscale while loading it.\n\n        If any changes are made, returns a tuple with the chosen ``mode`` and\n        ``box`` with coordinates of the original image within the altered one.\n\n        Note that this method modifies the :py:class:`~PIL.Image.Image` object\n        in place. If the image has already been loaded, this method has no\n        effect.\n\n        Note: This method is not implemented for most images. It is\n        currently implemented only for JPEG and MPO images.\n\n        :param mode: The requested mode.\n        :param size: The requested size.\n        \"\"\"\n        pass\n\n    def _expand(self, xmargin, ymargin=None):\n        if ymargin is None:\n            ymargin = xmargin\n        self.load()\n        return self._new(self.im.expand(xmargin, ymargin, 0))\n\n    def filter(self, filter):\n        \"\"\"\n        Filters this image using the given filter.  For a list of\n        available filters, see the :py:mod:`~PIL.ImageFilter` module.\n\n        :param filter: Filter kernel.\n        :returns: An :py:class:`~PIL.Image.Image` object.  \"\"\"\n\n        from . import ImageFilter\n\n        self.load()\n\n        if isinstance(filter, Callable):\n            filter = filter()\n        if not hasattr(filter, \"filter\"):\n            raise TypeError(\n                \"filter argument should be ImageFilter.Filter instance or class\"\n            )\n\n        multiband = isinstance(filter, ImageFilter.MultibandFilter)\n        if self.im.bands == 1 or multiband:\n            return self._new(filter.filter(self.im))\n\n        ims = []\n        for c in range(self.im.bands):\n            ims.append(self._new(filter.filter(self.im.getband(c))))\n        return merge(self.mode, ims)\n\n    def getbands(self):\n        \"\"\"\n        Returns a tuple containing the name of each band in this image.\n        For example, **getbands** on an RGB image returns (\"R\", \"G\", \"B\").\n\n        :returns: A tuple containing band names.\n        :rtype: tuple\n        \"\"\"\n        return ImageMode.getmode(self.mode).bands\n\n    def getbbox(self):\n        \"\"\"\n        Calculates the bounding box of the non-zero regions in the\n        image.\n\n        :returns: The bounding box is returned as a 4-tuple defining the\n           left, upper, right, and lower pixel coordinate. See\n           :ref:`coordinate-system`. If the image is completely empty, this\n           method returns None.\n\n        \"\"\"\n\n        self.load()\n        return self.im.getbbox()\n\n    def getcolors(self, maxcolors=256):\n        \"\"\"\n        Returns a list of colors used in this image.\n\n        :param maxcolors: Maximum number of colors.  If this number is\n           exceeded, this method returns None.  The default limit is\n           256 colors.\n        :returns: An unsorted list of (count, pixel) values.\n        \"\"\"\n\n        self.load()\n        if self.mode in (\"1\", \"L\", \"P\"):\n            h = self.im.histogram()\n            out = []\n            for i in range(256):\n                if h[i]:\n                    out.append((h[i], i))\n            if len(out) > maxcolors:\n                return None\n            return out\n        return self.im.getcolors(maxcolors)\n\n    def getdata(self, band=None):\n        \"\"\"\n        Returns the contents of this image as a sequence object\n        containing pixel values.  The sequence object is flattened, so\n        that values for line one follow directly after the values of\n        line zero, and so on.\n\n        Note that the sequence object returned by this method is an\n        internal PIL data type, which only supports certain sequence\n        operations.  To convert it to an ordinary sequence (e.g. for\n        printing), use **list(im.getdata())**.\n\n        :param band: What band to return.  The default is to return\n           all bands.  To return a single band, pass in the index\n           value (e.g. 0 to get the \"R\" band from an \"RGB\" image).\n        :returns: A sequence-like object.\n        \"\"\"\n\n        self.load()\n        if band is not None:\n            return self.im.getband(band)\n        return self.im  # could be abused\n\n    def getextrema(self):\n        \"\"\"\n        Gets the the minimum and maximum pixel values for each band in\n        the image.\n\n        :returns: For a single-band image, a 2-tuple containing the\n           minimum and maximum pixel value.  For a multi-band image,\n           a tuple containing one 2-tuple for each band.\n        \"\"\"\n\n        self.load()\n        if self.im.bands > 1:\n            extrema = []\n            for i in range(self.im.bands):\n                extrema.append(self.im.getband(i).getextrema())\n            return tuple(extrema)\n        return self.im.getextrema()\n\n    def getexif(self):\n        if self._exif is None:\n            self._exif = Exif()\n\n        exif_info = self.info.get(\"exif\")\n        if exif_info is None and \"Raw profile type exif\" in self.info:\n            exif_info = bytes.fromhex(\n                \"\".join(self.info[\"Raw profile type exif\"].split(\"\\n\")[3:])\n            )\n        self._exif.load(exif_info)\n\n        # XMP tags\n        if 0x0112 not in self._exif:\n            xmp_tags = self.info.get(\"XML:com.adobe.xmp\")\n            if xmp_tags:\n                root = xml.etree.ElementTree.fromstring(xmp_tags)\n                for elem in root.iter():\n                    if elem.tag.endswith(\"}Description\"):\n                        orientation = elem.attrib.get(\n                            \"{http://ns.adobe.com/tiff/1.0/}Orientation\"\n                        )\n                        if orientation:\n                            self._exif[0x0112] = int(orientation)\n                        break\n\n        return self._exif\n\n    def getim(self):\n        \"\"\"\n        Returns a capsule that points to the internal image memory.\n\n        :returns: A capsule object.\n        \"\"\"\n\n        self.load()\n        return self.im.ptr\n\n    def getpalette(self):\n        \"\"\"\n        Returns the image palette as a list.\n\n        :returns: A list of color values [r, g, b, ...], or None if the\n           image has no palette.\n        \"\"\"\n\n        self.load()\n        try:\n            return list(self.im.getpalette())\n        except ValueError:\n            return None  # no palette\n\n    def getpixel(self, xy):\n        \"\"\"\n        Returns the pixel value at a given position.\n\n        :param xy: The coordinate, given as (x, y). See\n           :ref:`coordinate-system`.\n        :returns: The pixel value.  If the image is a multi-layer image,\n           this method returns a tuple.\n        \"\"\"\n\n        self.load()\n        if self.pyaccess:\n            return self.pyaccess.getpixel(xy)\n        return self.im.getpixel(xy)\n\n    def getprojection(self):\n        \"\"\"\n        Get projection to x and y axes\n\n        :returns: Two sequences, indicating where there are non-zero\n            pixels along the X-axis and the Y-axis, respectively.\n        \"\"\"\n\n        self.load()\n        x, y = self.im.getprojection()\n        return [i8(c) for c in x], [i8(c) for c in y]\n\n    def histogram(self, mask=None, extrema=None):\n        \"\"\"\n        Returns a histogram for the image. The histogram is returned as\n        a list of pixel counts, one for each pixel value in the source\n        image. If the image has more than one band, the histograms for\n        all bands are concatenated (for example, the histogram for an\n        \"RGB\" image contains 768 values).\n\n        A bilevel image (mode \"1\") is treated as a greyscale (\"L\") image\n        by this method.\n\n        If a mask is provided, the method returns a histogram for those\n        parts of the image where the mask image is non-zero. The mask\n        image must have the same size as the image, and be either a\n        bi-level image (mode \"1\") or a greyscale image (\"L\").\n\n        :param mask: An optional mask.\n        :param extrema: An optional tuple of manually-specified extrema.\n        :returns: A list containing pixel counts.\n        \"\"\"\n        self.load()\n        if mask:\n            mask.load()\n            return self.im.histogram((0, 0), mask.im)\n        if self.mode in (\"I\", \"F\"):\n            if extrema is None:\n                extrema = self.getextrema()\n            return self.im.histogram(extrema)\n        return self.im.histogram()\n\n    def entropy(self, mask=None, extrema=None):\n        \"\"\"\n        Calculates and returns the entropy for the image.\n\n        A bilevel image (mode \"1\") is treated as a greyscale (\"L\")\n        image by this method.\n\n        If a mask is provided, the method employs the histogram for\n        those parts of the image where the mask image is non-zero.\n        The mask image must have the same size as the image, and be\n        either a bi-level image (mode \"1\") or a greyscale image (\"L\").\n\n        :param mask: An optional mask.\n        :param extrema: An optional tuple of manually-specified extrema.\n        :returns: A float value representing the image entropy\n        \"\"\"\n        self.load()\n        if mask:\n            mask.load()\n            return self.im.entropy((0, 0), mask.im)\n        if self.mode in (\"I\", \"F\"):\n            if extrema is None:\n                extrema = self.getextrema()\n            return self.im.entropy(extrema)\n        return self.im.entropy()\n\n    def offset(self, xoffset, yoffset=None):\n        raise NotImplementedError(\n            \"offset() has been removed. Please call ImageChops.offset() instead.\"\n        )\n\n    def paste(self, im, box=None, mask=None):\n        \"\"\"\n        Pastes another image into this image. The box argument is either\n        a 2-tuple giving the upper left corner, a 4-tuple defining the\n        left, upper, right, and lower pixel coordinate, or None (same as\n        (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size\n        of the pasted image must match the size of the region.\n\n        If the modes don't match, the pasted image is converted to the mode of\n        this image (see the :py:meth:`~PIL.Image.Image.convert` method for\n        details).\n\n        Instead of an image, the source can be a integer or tuple\n        containing pixel values.  The method then fills the region\n        with the given color.  When creating RGB images, you can\n        also use color strings as supported by the ImageColor module.\n\n        If a mask is given, this method updates only the regions\n        indicated by the mask.  You can use either \"1\", \"L\" or \"RGBA\"\n        images (in the latter case, the alpha band is used as mask).\n        Where the mask is 255, the given image is copied as is.  Where\n        the mask is 0, the current value is preserved.  Intermediate\n        values will mix the two images together, including their alpha\n        channels if they have them.\n\n        See :py:meth:`~PIL.Image.Image.alpha_composite` if you want to\n        combine images with respect to their alpha channels.\n\n        :param im: Source image or pixel value (integer or tuple).\n        :param box: An optional 4-tuple giving the region to paste into.\n           If a 2-tuple is used instead, it's treated as the upper left\n           corner.  If omitted or None, the source is pasted into the\n           upper left corner.\n\n           If an image is given as the second argument and there is no\n           third, the box defaults to (0, 0), and the second argument\n           is interpreted as a mask image.\n        :param mask: An optional mask image.\n        \"\"\"\n\n        if isImageType(box) and mask is None:\n            # abbreviated paste(im, mask) syntax\n            mask = box\n            box = None\n\n        if box is None:\n            box = (0, 0)\n\n        if len(box) == 2:\n            # upper left corner given; get size from image or mask\n            if isImageType(im):\n                size = im.size\n            elif isImageType(mask):\n                size = mask.size\n            else:\n                # FIXME: use self.size here?\n                raise ValueError(\"cannot determine region size; use 4-item box\")\n            box += (box[0] + size[0], box[1] + size[1])\n\n        if isinstance(im, str):\n            from . import ImageColor\n\n            im = ImageColor.getcolor(im, self.mode)\n\n        elif isImageType(im):\n            im.load()\n            if self.mode != im.mode:\n                if self.mode != \"RGB\" or im.mode not in (\"RGBA\", \"RGBa\"):\n                    # should use an adapter for this!\n                    im = im.convert(self.mode)\n            im = im.im\n\n        self._ensure_mutable()\n\n        if mask:\n            mask.load()\n            self.im.paste(im, box, mask.im)\n        else:\n            self.im.paste(im, box)\n\n    def alpha_composite(self, im, dest=(0, 0), source=(0, 0)):\n        \"\"\" 'In-place' analog of Image.alpha_composite. Composites an image\n        onto this image.\n\n        :param im: image to composite over this one\n        :param dest: Optional 2 tuple (left, top) specifying the upper\n          left corner in this (destination) image.\n        :param source: Optional 2 (left, top) tuple for the upper left\n          corner in the overlay source image, or 4 tuple (left, top, right,\n          bottom) for the bounds of the source rectangle\n\n        Performance Note: Not currently implemented in-place in the core layer.\n        \"\"\"\n\n        if not isinstance(source, (list, tuple)):\n            raise ValueError(\"Source must be a tuple\")\n        if not isinstance(dest, (list, tuple)):\n            raise ValueError(\"Destination must be a tuple\")\n        if not len(source) in (2, 4):\n            raise ValueError(\"Source must be a 2 or 4-tuple\")\n        if not len(dest) == 2:\n            raise ValueError(\"Destination must be a 2-tuple\")\n        if min(source) < 0:\n            raise ValueError(\"Source must be non-negative\")\n        if min(dest) < 0:\n            raise ValueError(\"Destination must be non-negative\")\n\n        if len(source) == 2:\n            source = source + im.size\n\n        # over image, crop if it's not the whole thing.\n        if source == (0, 0) + im.size:\n            overlay = im\n        else:\n            overlay = im.crop(source)\n\n        # target for the paste\n        box = dest + (dest[0] + overlay.width, dest[1] + overlay.height)\n\n        # destination image. don't copy if we're using the whole image.\n        if box == (0, 0) + self.size:\n            background = self\n        else:\n            background = self.crop(box)\n\n        result = alpha_composite(background, overlay)\n        self.paste(result, box)\n\n    def point(self, lut, mode=None):\n        \"\"\"\n        Maps this image through a lookup table or function.\n\n        :param lut: A lookup table, containing 256 (or 65536 if\n           self.mode==\"I\" and mode == \"L\") values per band in the\n           image.  A function can be used instead, it should take a\n           single argument. The function is called once for each\n           possible pixel value, and the resulting table is applied to\n           all bands of the image.\n        :param mode: Output mode (default is same as input).  In the\n           current version, this can only be used if the source image\n           has mode \"L\" or \"P\", and the output has mode \"1\" or the\n           source image mode is \"I\" and the output mode is \"L\".\n        :returns: An :py:class:`~PIL.Image.Image` object.\n        \"\"\"\n\n        self.load()\n\n        if isinstance(lut, ImagePointHandler):\n            return lut.point(self)\n\n        if callable(lut):\n            # if it isn't a list, it should be a function\n            if self.mode in (\"I\", \"I;16\", \"F\"):\n                # check if the function can be used with point_transform\n                # UNDONE wiredfool -- I think this prevents us from ever doing\n                # a gamma function point transform on > 8bit images.\n                scale, offset = _getscaleoffset(lut)\n                return self._new(self.im.point_transform(scale, offset))\n            # for other modes, convert the function to a table\n            lut = [lut(i) for i in range(256)] * self.im.bands\n\n        if self.mode == \"F\":\n            # FIXME: _imaging returns a confusing error message for this case\n            raise ValueError(\"point operation not supported for this mode\")\n\n        return self._new(self.im.point(lut, mode))\n\n    def putalpha(self, alpha):\n        \"\"\"\n        Adds or replaces the alpha layer in this image.  If the image\n        does not have an alpha layer, it's converted to \"LA\" or \"RGBA\".\n        The new layer must be either \"L\" or \"1\".\n\n        :param alpha: The new alpha layer.  This can either be an \"L\" or \"1\"\n           image having the same size as this image, or an integer or\n           other color value.\n        \"\"\"\n\n        self._ensure_mutable()\n\n        if self.mode not in (\"LA\", \"PA\", \"RGBA\"):\n            # attempt to promote self to a matching alpha mode\n            try:\n                mode = getmodebase(self.mode) + \"A\"\n                try:\n                    self.im.setmode(mode)\n                except (AttributeError, ValueError):\n                    # do things the hard way\n                    im = self.im.convert(mode)\n                    if im.mode not in (\"LA\", \"PA\", \"RGBA\"):\n                        raise ValueError  # sanity check\n                    self.im = im\n                self.pyaccess = None\n                self.mode = self.im.mode\n            except (KeyError, ValueError):\n                raise ValueError(\"illegal image mode\")\n\n        if self.mode in (\"LA\", \"PA\"):\n            band = 1\n        else:\n            band = 3\n\n        if isImageType(alpha):\n            # alpha layer\n            if alpha.mode not in (\"1\", \"L\"):\n                raise ValueError(\"illegal image mode\")\n            alpha.load()\n            if alpha.mode == \"1\":\n                alpha = alpha.convert(\"L\")\n        else:\n            # constant alpha\n            try:\n                self.im.fillband(band, alpha)\n            except (AttributeError, ValueError):\n                # do things the hard way\n                alpha = new(\"L\", self.size, alpha)\n            else:\n                return\n\n        self.im.putband(alpha.im, band)\n\n    def putdata(self, data, scale=1.0, offset=0.0):\n        \"\"\"\n        Copies pixel data to this image.  This method copies data from a\n        sequence object into the image, starting at the upper left\n        corner (0, 0), and continuing until either the image or the\n        sequence ends.  The scale and offset values are used to adjust\n        the sequence values: **pixel = value*scale + offset**.\n\n        :param data: A sequence object.\n        :param scale: An optional scale value.  The default is 1.0.\n        :param offset: An optional offset value.  The default is 0.0.\n        \"\"\"\n\n        self._ensure_mutable()\n\n        self.im.putdata(data, scale, offset)\n\n    def putpalette(self, data, rawmode=\"RGB\"):\n        \"\"\"\n        Attaches a palette to this image.  The image must be a \"P\",\n        \"PA\", \"L\" or \"LA\" image, and the palette sequence must contain\n        768 integer values, where each group of three values represent\n        the red, green, and blue values for the corresponding pixel\n        index. Instead of an integer sequence, you can use an 8-bit\n        string.\n\n        :param data: A palette sequence (either a list or a string).\n        :param rawmode: The raw mode of the palette.\n        \"\"\"\n        from . import ImagePalette\n\n        if self.mode not in (\"L\", \"LA\", \"P\", \"PA\"):\n            raise ValueError(\"illegal image mode\")\n        self.load()\n        if isinstance(data, ImagePalette.ImagePalette):\n            palette = ImagePalette.raw(data.rawmode, data.palette)\n        else:\n            if not isinstance(data, bytes):\n                data = bytes(data)\n            palette = ImagePalette.raw(rawmode, data)\n        self.mode = \"PA\" if \"A\" in self.mode else \"P\"\n        self.palette = palette\n        self.palette.mode = \"RGB\"\n        self.load()  # install new palette\n\n    def putpixel(self, xy, value):\n        \"\"\"\n        Modifies the pixel at the given position. The color is given as\n        a single numerical value for single-band images, and a tuple for\n        multi-band images. In addition to this, RGB and RGBA tuples are\n        accepted for P images.\n\n        Note that this method is relatively slow.  For more extensive changes,\n        use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw`\n        module instead.\n\n        See:\n\n        * :py:meth:`~PIL.Image.Image.paste`\n        * :py:meth:`~PIL.Image.Image.putdata`\n        * :py:mod:`~PIL.ImageDraw`\n\n        :param xy: The pixel coordinate, given as (x, y). See\n           :ref:`coordinate-system`.\n        :param value: The pixel value.\n        \"\"\"\n\n        if self.readonly:\n            self._copy()\n        self.load()\n\n        if self.pyaccess:\n            return self.pyaccess.putpixel(xy, value)\n\n        if (\n            self.mode == \"P\"\n            and isinstance(value, (list, tuple))\n            and len(value) in [3, 4]\n        ):\n            # RGB or RGBA value for a P image\n            value = self.palette.getcolor(value)\n        return self.im.putpixel(xy, value)\n\n    def remap_palette(self, dest_map, source_palette=None):\n        \"\"\"\n        Rewrites the image to reorder the palette.\n\n        :param dest_map: A list of indexes into the original palette.\n           e.g. [1,0] would swap a two item palette, and list(range(256))\n           is the identity transform.\n        :param source_palette: Bytes or None.\n        :returns:  An :py:class:`~PIL.Image.Image` object.\n\n        \"\"\"\n        from . import ImagePalette\n\n        if self.mode not in (\"L\", \"P\"):\n            raise ValueError(\"illegal image mode\")\n\n        if source_palette is None:\n            if self.mode == \"P\":\n                real_source_palette = self.im.getpalette(\"RGB\")[:768]\n            else:  # L-mode\n                real_source_palette = bytearray(i // 3 for i in range(768))\n        else:\n            real_source_palette = source_palette\n\n        palette_bytes = b\"\"\n        new_positions = [0] * 256\n\n        # pick only the used colors from the palette\n        for i, oldPosition in enumerate(dest_map):\n            palette_bytes += real_source_palette[oldPosition * 3 : oldPosition * 3 + 3]\n            new_positions[oldPosition] = i\n\n        # replace the palette color id of all pixel with the new id\n\n        # Palette images are [0..255], mapped through a 1 or 3\n        # byte/color map.  We need to remap the whole image\n        # from palette 1 to palette 2. New_positions is\n        # an array of indexes into palette 1.  Palette 2 is\n        # palette 1 with any holes removed.\n\n        # We're going to leverage the convert mechanism to use the\n        # C code to remap the image from palette 1 to palette 2,\n        # by forcing the source image into 'L' mode and adding a\n        # mapping 'L' mode palette, then converting back to 'L'\n        # sans palette thus converting the image bytes, then\n        # assigning the optimized RGB palette.\n\n        # perf reference, 9500x4000 gif, w/~135 colors\n        # 14 sec prepatch, 1 sec postpatch with optimization forced.\n\n        mapping_palette = bytearray(new_positions)\n\n        m_im = self.copy()\n        m_im.mode = \"P\"\n\n        m_im.palette = ImagePalette.ImagePalette(\n            \"RGB\", palette=mapping_palette * 3, size=768\n        )\n        # possibly set palette dirty, then\n        # m_im.putpalette(mapping_palette, 'L')  # converts to 'P'\n        # or just force it.\n        # UNDONE -- this is part of the general issue with palettes\n        m_im.im.putpalette(*m_im.palette.getdata())\n\n        m_im = m_im.convert(\"L\")\n\n        # Internally, we require 768 bytes for a palette.\n        new_palette_bytes = palette_bytes + (768 - len(palette_bytes)) * b\"\\x00\"\n        m_im.putpalette(new_palette_bytes)\n        m_im.palette = ImagePalette.ImagePalette(\n            \"RGB\", palette=palette_bytes, size=len(palette_bytes)\n        )\n\n        return m_im\n\n    def _get_safe_box(self, size, resample, box):\n        \"\"\"Expands the box so it includes adjacent pixels\n        that may be used by resampling with the given resampling filter.\n        \"\"\"\n        filter_support = _filters_support[resample] - 0.5\n        scale_x = (box[2] - box[0]) / size[0]\n        scale_y = (box[3] - box[1]) / size[1]\n        support_x = filter_support * scale_x\n        support_y = filter_support * scale_y\n\n        return (\n            max(0, int(box[0] - support_x)),\n            max(0, int(box[1] - support_y)),\n            min(self.size[0], math.ceil(box[2] + support_x)),\n            min(self.size[1], math.ceil(box[3] + support_y)),\n        )\n\n    def resize(self, size, resample=BICUBIC, box=None, reducing_gap=None):\n        \"\"\"\n        Returns a resized copy of this image.\n\n        :param size: The requested size in pixels, as a 2-tuple:\n           (width, height).\n        :param resample: An optional resampling filter.  This can be\n           one of :py:attr:`PIL.Image.NEAREST`, :py:attr:`PIL.Image.BOX`,\n           :py:attr:`PIL.Image.BILINEAR`, :py:attr:`PIL.Image.HAMMING`,\n           :py:attr:`PIL.Image.BICUBIC` or :py:attr:`PIL.Image.LANCZOS`.\n           Default filter is :py:attr:`PIL.Image.BICUBIC`.\n           If the image has mode \"1\" or \"P\", it is\n           always set to :py:attr:`PIL.Image.NEAREST`.\n           See: :ref:`concept-filters`.\n        :param box: An optional 4-tuple of floats providing\n           the source image region to be scaled.\n           The values must be within (0, 0, width, height) rectangle.\n           If omitted or None, the entire source is used.\n        :param reducing_gap: Apply optimization by resizing the image\n           in two steps. First, reducing the image by integer times\n           using :py:meth:`~PIL.Image.Image.reduce`.\n           Second, resizing using regular resampling. The last step\n           changes size no less than by ``reducing_gap`` times.\n           ``reducing_gap`` may be None (no first step is performed)\n           or should be greater than 1.0. The bigger ``reducing_gap``,\n           the closer the result to the fair resampling.\n           The smaller ``reducing_gap``, the faster resizing.\n           With ``reducing_gap`` greater or equal to 3.0, the result is\n           indistinguishable from fair resampling in most cases.\n           The default value is None (no optimization).\n        :returns: An :py:class:`~PIL.Image.Image` object.\n        \"\"\"\n\n        if resample not in (NEAREST, BILINEAR, BICUBIC, LANCZOS, BOX, HAMMING):\n            message = \"Unknown resampling filter ({}).\".format(resample)\n\n            filters = [\n                \"{} ({})\".format(filter[1], filter[0])\n                for filter in (\n                    (NEAREST, \"Image.NEAREST\"),\n                    (LANCZOS, \"Image.LANCZOS\"),\n                    (BILINEAR, \"Image.BILINEAR\"),\n                    (BICUBIC, \"Image.BICUBIC\"),\n                    (BOX, \"Image.BOX\"),\n                    (HAMMING, \"Image.HAMMING\"),\n                )\n            ]\n            raise ValueError(\n                message + \" Use \" + \", \".join(filters[:-1]) + \" or \" + filters[-1]\n            )\n\n        if reducing_gap is not None and reducing_gap < 1.0:\n            raise ValueError(\"reducing_gap must be 1.0 or greater\")\n\n        size = tuple(size)\n\n        if box is None:\n            box = (0, 0) + self.size\n        else:\n            box = tuple(box)\n\n        if self.size == size and box == (0, 0) + self.size:\n            return self.copy()\n\n        if self.mode in (\"1\", \"P\"):\n            resample = NEAREST\n\n        if self.mode in [\"LA\", \"RGBA\"]:\n            im = self.convert(self.mode[:-1] + \"a\")\n            im = im.resize(size, resample, box)\n            return im.convert(self.mode)\n\n        self.load()\n\n        if reducing_gap is not None and resample != NEAREST:\n            factor_x = int((box[2] - box[0]) / size[0] / reducing_gap) or 1\n            factor_y = int((box[3] - box[1]) / size[1] / reducing_gap) or 1\n            if factor_x > 1 or factor_y > 1:\n                reduce_box = self._get_safe_box(size, resample, box)\n                factor = (factor_x, factor_y)\n                if callable(self.reduce):\n                    self = self.reduce(factor, box=reduce_box)\n                else:\n                    self = Image.reduce(self, factor, box=reduce_box)\n                box = (\n                    (box[0] - reduce_box[0]) / factor_x,\n                    (box[1] - reduce_box[1]) / factor_y,\n                    (box[2] - reduce_box[0]) / factor_x,\n                    (box[3] - reduce_box[1]) / factor_y,\n                )\n\n        return self._new(self.im.resize(size, resample, box))\n\n    def reduce(self, factor, box=None):\n        \"\"\"\n        Returns a copy of the image reduced by `factor` times.\n        If the size of the image is not dividable by the `factor`,\n        the resulting size will be rounded up.\n\n        :param factor: A greater than 0 integer or tuple of two integers\n           for width and height separately.\n        :param box: An optional 4-tuple of ints providing\n           the source image region to be reduced.\n           The values must be within (0, 0, width, height) rectangle.\n           If omitted or None, the entire source is used.\n        \"\"\"\n        if not isinstance(factor, (list, tuple)):\n            factor = (factor, factor)\n\n        if box is None:\n            box = (0, 0) + self.size\n        else:\n            box = tuple(box)\n\n        if factor == (1, 1) and box == (0, 0) + self.size:\n            return self.copy()\n\n        if self.mode in [\"LA\", \"RGBA\"]:\n            im = self.convert(self.mode[:-1] + \"a\")\n            im = im.reduce(factor, box)\n            return im.convert(self.mode)\n\n        self.load()\n\n        return self._new(self.im.reduce(factor, box))\n\n    def rotate(\n        self,\n        angle,\n        resample=NEAREST,\n        expand=0,\n        center=None,\n        translate=None,\n        fillcolor=None,\n    ):\n        \"\"\"\n        Returns a rotated copy of this image.  This method returns a\n        copy of this image, rotated the given number of degrees counter\n        clockwise around its centre.\n\n        :param angle: In degrees counter clockwise.\n        :param resample: An optional resampling filter.  This can be\n           one of :py:attr:`PIL.Image.NEAREST` (use nearest neighbour),\n           :py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2\n           environment), or :py:attr:`PIL.Image.BICUBIC`\n           (cubic spline interpolation in a 4x4 environment).\n           If omitted, or if the image has mode \"1\" or \"P\", it is\n           set to :py:attr:`PIL.Image.NEAREST`. See :ref:`concept-filters`.\n        :param expand: Optional expansion flag.  If true, expands the output\n           image to make it large enough to hold the entire rotated image.\n           If false or omitted, make the output image the same size as the\n           input image.  Note that the expand flag assumes rotation around\n           the center and no translation.\n        :param center: Optional center of rotation (a 2-tuple).  Origin is\n           the upper left corner.  Default is the center of the image.\n        :param translate: An optional post-rotate translation (a 2-tuple).\n        :param fillcolor: An optional color for area outside the rotated image.\n        :returns: An :py:class:`~PIL.Image.Image` object.\n        \"\"\"\n\n        angle = angle % 360.0\n\n        # Fast paths regardless of filter, as long as we're not\n        # translating or changing the center.\n        if not (center or translate):\n            if angle == 0:\n                return self.copy()\n            if angle == 180:\n                return self.transpose(ROTATE_180)\n            if angle == 90 and expand:\n                return self.transpose(ROTATE_90)\n            if angle == 270 and expand:\n                return self.transpose(ROTATE_270)\n\n        # Calculate the affine matrix.  Note that this is the reverse\n        # transformation (from destination image to source) because we\n        # want to interpolate the (discrete) destination pixel from\n        # the local area around the (floating) source pixel.\n\n        # The matrix we actually want (note that it operates from the right):\n        # (1, 0, tx)   (1, 0, cx)   ( cos a, sin a, 0)   (1, 0, -cx)\n        # (0, 1, ty) * (0, 1, cy) * (-sin a, cos a, 0) * (0, 1, -cy)\n        # (0, 0,  1)   (0, 0,  1)   (     0,     0, 1)   (0, 0,   1)\n\n        # The reverse matrix is thus:\n        # (1, 0, cx)   ( cos -a, sin -a, 0)   (1, 0, -cx)   (1, 0, -tx)\n        # (0, 1, cy) * (-sin -a, cos -a, 0) * (0, 1, -cy) * (0, 1, -ty)\n        # (0, 0,  1)   (      0,      0, 1)   (0, 0,   1)   (0, 0,   1)\n\n        # In any case, the final translation may be updated at the end to\n        # compensate for the expand flag.\n\n        w, h = self.size\n\n        if translate is None:\n            post_trans = (0, 0)\n        else:\n            post_trans = translate\n        if center is None:\n            # FIXME These should be rounded to ints?\n            rotn_center = (w / 2.0, h / 2.0)\n        else:\n            rotn_center = center\n\n        angle = -math.radians(angle)\n        matrix = [\n            round(math.cos(angle), 15),\n            round(math.sin(angle), 15),\n            0.0,\n            round(-math.sin(angle), 15),\n            round(math.cos(angle), 15),\n            0.0,\n        ]\n\n        def transform(x, y, matrix):\n            (a, b, c, d, e, f) = matrix\n            return a * x + b * y + c, d * x + e * y + f\n\n        matrix[2], matrix[5] = transform(\n            -rotn_center[0] - post_trans[0], -rotn_center[1] - post_trans[1], matrix\n        )\n        matrix[2] += rotn_center[0]\n        matrix[5] += rotn_center[1]\n\n        if expand:\n            # calculate output size\n            xx = []\n            yy = []\n            for x, y in ((0, 0), (w, 0), (w, h), (0, h)):\n                x, y = transform(x, y, matrix)\n                xx.append(x)\n                yy.append(y)\n            nw = math.ceil(max(xx)) - math.floor(min(xx))\n            nh = math.ceil(max(yy)) - math.floor(min(yy))\n\n            # We multiply a translation matrix from the right.  Because of its\n            # special form, this is the same as taking the image of the\n            # translation vector as new translation vector.\n            matrix[2], matrix[5] = transform(-(nw - w) / 2.0, -(nh - h) / 2.0, matrix)\n            w, h = nw, nh\n\n        return self.transform((w, h), AFFINE, matrix, resample, fillcolor=fillcolor)\n\n    def save(self, fp, format=None, **params):\n        \"\"\"\n        Saves this image under the given filename.  If no format is\n        specified, the format to use is determined from the filename\n        extension, if possible.\n\n        Keyword options can be used to provide additional instructions\n        to the writer. If a writer doesn't recognise an option, it is\n        silently ignored. The available options are described in the\n        :doc:`image format documentation\n        <../handbook/image-file-formats>` for each writer.\n\n        You can use a file object instead of a filename. In this case,\n        you must always specify the format. The file object must\n        implement the ``seek``, ``tell``, and ``write``\n        methods, and be opened in binary mode.\n\n        :param fp: A filename (string), pathlib.Path object or file object.\n        :param format: Optional format override.  If omitted, the\n           format to use is determined from the filename extension.\n           If a file object was used instead of a filename, this\n           parameter should always be used.\n        :param params: Extra parameters to the image writer.\n        :returns: None\n        :exception ValueError: If the output format could not be determined\n           from the file name.  Use the format option to solve this.\n        :exception OSError: If the file could not be written.  The file\n           may have been created, and may contain partial data.\n        \"\"\"\n\n        filename = \"\"\n        open_fp = False\n        if isPath(fp):\n            filename = fp\n            open_fp = True\n        elif isinstance(fp, Path):\n            filename = str(fp)\n            open_fp = True\n        if not filename and hasattr(fp, \"name\") and isPath(fp.name):\n            # only set the name for metadata purposes\n            filename = fp.name\n\n        # may mutate self!\n        self._ensure_mutable()\n\n        save_all = params.pop(\"save_all\", False)\n        self.encoderinfo = params\n        self.encoderconfig = ()\n\n        preinit()\n\n        ext = os.path.splitext(filename)[1].lower()\n\n        if not format:\n            if ext not in EXTENSION:\n                init()\n            try:\n                format = EXTENSION[ext]\n            except KeyError:\n                raise ValueError(\"unknown file extension: {}\".format(ext))\n\n        if format.upper() not in SAVE:\n            init()\n        if save_all:\n            save_handler = SAVE_ALL[format.upper()]\n        else:\n            save_handler = SAVE[format.upper()]\n\n        if open_fp:\n            if params.get(\"append\", False):\n                # Open also for reading (\"+\"), because TIFF save_all\n                # writer needs to go back and edit the written data.\n                fp = builtins.open(filename, \"r+b\")\n            else:\n                fp = builtins.open(filename, \"w+b\")\n\n        try:\n            save_handler(self, fp, filename)\n        finally:\n            # do what we can to clean up\n            if open_fp:\n                fp.close()\n\n    def seek(self, frame):\n        \"\"\"\n        Seeks to the given frame in this sequence file. If you seek\n        beyond the end of the sequence, the method raises an\n        **EOFError** exception. When a sequence file is opened, the\n        library automatically seeks to frame 0.\n\n        See :py:meth:`~PIL.Image.Image.tell`.\n\n        :param frame: Frame number, starting at 0.\n        :exception EOFError: If the call attempts to seek beyond the end\n            of the sequence.\n        \"\"\"\n\n        # overridden by file handlers\n        if frame != 0:\n            raise EOFError\n\n    def show(self, title=None, command=None):\n        \"\"\"\n        Displays this image. This method is mainly intended for\n        debugging purposes.\n\n        The image is first saved to a temporary file. By default, it will be in\n        PNG format.\n\n        On Unix, the image is then opened using the **display**, **eog** or\n        **xv** utility, depending on which one can be found.\n\n        On macOS, the image is opened with the native Preview application.\n\n        On Windows, the image is opened with the standard PNG display utility.\n\n        :param title: Optional title to use for the image window,\n           where possible.\n        :param command: command used to show the image\n        \"\"\"\n\n        _show(self, title=title, command=command)\n\n    def split(self):\n        \"\"\"\n        Split this image into individual bands. This method returns a\n        tuple of individual image bands from an image. For example,\n        splitting an \"RGB\" image creates three new images each\n        containing a copy of one of the original bands (red, green,\n        blue).\n\n        If you need only one band, :py:meth:`~PIL.Image.Image.getchannel`\n        method can be more convenient and faster.\n\n        :returns: A tuple containing bands.\n        \"\"\"\n\n        self.load()\n        if self.im.bands == 1:\n            ims = [self.copy()]\n        else:\n            ims = map(self._new, self.im.split())\n        return tuple(ims)\n\n    def getchannel(self, channel):\n        \"\"\"\n        Returns an image containing a single channel of the source image.\n\n        :param channel: What channel to return. Could be index\n          (0 for \"R\" channel of \"RGB\") or channel name\n          (\"A\" for alpha channel of \"RGBA\").\n        :returns: An image in \"L\" mode.\n\n        .. versionadded:: 4.3.0\n        \"\"\"\n        self.load()\n\n        if isinstance(channel, str):\n            try:\n                channel = self.getbands().index(channel)\n            except ValueError:\n                raise ValueError('The image has no channel \"{}\"'.format(channel))\n\n        return self._new(self.im.getband(channel))\n\n    def tell(self):\n        \"\"\"\n        Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`.\n\n        :returns: Frame number, starting with 0.\n        \"\"\"\n        return 0\n\n    def thumbnail(self, size, resample=BICUBIC, reducing_gap=2.0):\n        \"\"\"\n        Make this image into a thumbnail.  This method modifies the\n        image to contain a thumbnail version of itself, no larger than\n        the given size.  This method calculates an appropriate thumbnail\n        size to preserve the aspect of the image, calls the\n        :py:meth:`~PIL.Image.Image.draft` method to configure the file reader\n        (where applicable), and finally resizes the image.\n\n        Note that this function modifies the :py:class:`~PIL.Image.Image`\n        object in place.  If you need to use the full resolution image as well,\n        apply this method to a :py:meth:`~PIL.Image.Image.copy` of the original\n        image.\n\n        :param size: Requested size.\n        :param resample: Optional resampling filter.  This can be one\n           of :py:attr:`PIL.Image.NEAREST`, :py:attr:`PIL.Image.BILINEAR`,\n           :py:attr:`PIL.Image.BICUBIC`, or :py:attr:`PIL.Image.LANCZOS`.\n           If omitted, it defaults to :py:attr:`PIL.Image.BICUBIC`.\n           (was :py:attr:`PIL.Image.NEAREST` prior to version 2.5.0).\n           See: :ref:`concept-filters`.\n        :param reducing_gap: Apply optimization by resizing the image\n           in two steps. First, reducing the image by integer times\n           using :py:meth:`~PIL.Image.Image.reduce` or\n           :py:meth:`~PIL.Image.Image.draft` for JPEG images.\n           Second, resizing using regular resampling. The last step\n           changes size no less than by ``reducing_gap`` times.\n           ``reducing_gap`` may be None (no first step is performed)\n           or should be greater than 1.0. The bigger ``reducing_gap``,\n           the closer the result to the fair resampling.\n           The smaller ``reducing_gap``, the faster resizing.\n           With ``reducing_gap`` greater or equal to 3.0, the result is\n           indistinguishable from fair resampling in most cases.\n           The default value is 2.0 (very close to fair resampling\n           while still being faster in many cases).\n        :returns: None\n        \"\"\"\n\n        x, y = map(math.floor, size)\n        if x >= self.width and y >= self.height:\n            return\n\n        def round_aspect(number, key):\n            return max(min(math.floor(number), math.ceil(number), key=key), 1)\n\n        # preserve aspect ratio\n        aspect = self.width / self.height\n        if x / y >= aspect:\n            x = round_aspect(y * aspect, key=lambda n: abs(aspect - n / y))\n        else:\n            y = round_aspect(\n                x / aspect, key=lambda n: 0 if n == 0 else abs(aspect - x / n)\n            )\n        size = (x, y)\n\n        box = None\n        if reducing_gap is not None:\n            res = self.draft(None, (size[0] * reducing_gap, size[1] * reducing_gap))\n            if res is not None:\n                box = res[1]\n\n        if self.size != size:\n            im = self.resize(size, resample, box=box, reducing_gap=reducing_gap)\n\n            self.im = im.im\n            self._size = size\n            self.mode = self.im.mode\n\n        self.readonly = 0\n        self.pyaccess = None\n\n    # FIXME: the different transform methods need further explanation\n    # instead of bloating the method docs, add a separate chapter.\n    def transform(\n        self, size, method, data=None, resample=NEAREST, fill=1, fillcolor=None\n    ):\n        \"\"\"\n        Transforms this image.  This method creates a new image with the\n        given size, and the same mode as the original, and copies data\n        to the new image using the given transform.\n\n        :param size: The output size.\n        :param method: The transformation method.  This is one of\n          :py:attr:`PIL.Image.EXTENT` (cut out a rectangular subregion),\n          :py:attr:`PIL.Image.AFFINE` (affine transform),\n          :py:attr:`PIL.Image.PERSPECTIVE` (perspective transform),\n          :py:attr:`PIL.Image.QUAD` (map a quadrilateral to a rectangle), or\n          :py:attr:`PIL.Image.MESH` (map a number of source quadrilaterals\n          in one operation).\n\n          It may also be an :py:class:`~PIL.Image.ImageTransformHandler`\n          object::\n\n            class Example(Image.ImageTransformHandler):\n                def transform(size, method, data, resample, fill=1):\n                    # Return result\n\n          It may also be an object with a :py:meth:`~method.getdata` method\n          that returns a tuple supplying new **method** and **data** values::\n\n            class Example:\n                def getdata(self):\n                    method = Image.EXTENT\n                    data = (0, 0, 100, 100)\n                    return method, data\n        :param data: Extra data to the transformation method.\n        :param resample: Optional resampling filter.  It can be one of\n           :py:attr:`PIL.Image.NEAREST` (use nearest neighbour),\n           :py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2\n           environment), or :py:attr:`PIL.Image.BICUBIC` (cubic spline\n           interpolation in a 4x4 environment). If omitted, or if the image\n           has mode \"1\" or \"P\", it is set to :py:attr:`PIL.Image.NEAREST`.\n           See: :ref:`concept-filters`.\n        :param fill: If **method** is an\n          :py:class:`~PIL.Image.ImageTransformHandler` object, this is one of\n          the arguments passed to it. Otherwise, it is unused.\n        :param fillcolor: Optional fill color for the area outside the\n           transform in the output image.\n        :returns: An :py:class:`~PIL.Image.Image` object.\n        \"\"\"\n\n        if self.mode == \"LA\":\n            return (\n                self.convert(\"La\")\n                .transform(size, method, data, resample, fill, fillcolor)\n                .convert(\"LA\")\n            )\n\n        if self.mode == \"RGBA\":\n            return (\n                self.convert(\"RGBa\")\n                .transform(size, method, data, resample, fill, fillcolor)\n                .convert(\"RGBA\")\n            )\n\n        if isinstance(method, ImageTransformHandler):\n            return method.transform(size, self, resample=resample, fill=fill)\n\n        if hasattr(method, \"getdata\"):\n            # compatibility w. old-style transform objects\n            method, data = method.getdata()\n\n        if data is None:\n            raise ValueError(\"missing method data\")\n\n        im = new(self.mode, size, fillcolor)\n        im.info = self.info.copy()\n        if method == MESH:\n            # list of quads\n            for box, quad in data:\n                im.__transformer(box, self, QUAD, quad, resample, fillcolor is None)\n        else:\n            im.__transformer(\n                (0, 0) + size, self, method, data, resample, fillcolor is None\n            )\n\n        return im\n\n    def __transformer(self, box, image, method, data, resample=NEAREST, fill=1):\n        w = box[2] - box[0]\n        h = box[3] - box[1]\n\n        if method == AFFINE:\n            data = data[0:6]\n\n        elif method == EXTENT:\n            # convert extent to an affine transform\n            x0, y0, x1, y1 = data\n            xs = (x1 - x0) / w\n            ys = (y1 - y0) / h\n            method = AFFINE\n            data = (xs, 0, x0, 0, ys, y0)\n\n        elif method == PERSPECTIVE:\n            data = data[0:8]\n\n        elif method == QUAD:\n            # quadrilateral warp.  data specifies the four corners\n            # given as NW, SW, SE, and NE.\n            nw = data[0:2]\n            sw = data[2:4]\n            se = data[4:6]\n            ne = data[6:8]\n            x0, y0 = nw\n            As = 1.0 / w\n            At = 1.0 / h\n            data = (\n                x0,\n                (ne[0] - x0) * As,\n                (sw[0] - x0) * At,\n                (se[0] - sw[0] - ne[0] + x0) * As * At,\n                y0,\n                (ne[1] - y0) * As,\n                (sw[1] - y0) * At,\n                (se[1] - sw[1] - ne[1] + y0) * As * At,\n            )\n\n        else:\n            raise ValueError(\"unknown transformation method\")\n\n        if resample not in (NEAREST, BILINEAR, BICUBIC):\n            if resample in (BOX, HAMMING, LANCZOS):\n                message = {\n                    BOX: \"Image.BOX\",\n                    HAMMING: \"Image.HAMMING\",\n                    LANCZOS: \"Image.LANCZOS/Image.ANTIALIAS\",\n                }[resample] + \" ({}) cannot be used.\".format(resample)\n            else:\n                message = \"Unknown resampling filter ({}).\".format(resample)\n\n            filters = [\n                \"{} ({})\".format(filter[1], filter[0])\n                for filter in (\n                    (NEAREST, \"Image.NEAREST\"),\n                    (BILINEAR, \"Image.BILINEAR\"),\n                    (BICUBIC, \"Image.BICUBIC\"),\n                )\n            ]\n            raise ValueError(\n                message + \" Use \" + \", \".join(filters[:-1]) + \" or \" + filters[-1]\n            )\n\n        image.load()\n\n        self.load()\n\n        if image.mode in (\"1\", \"P\"):\n            resample = NEAREST\n\n        self.im.transform2(box, image.im, method, data, resample, fill)\n\n    def transpose(self, method):\n        \"\"\"\n        Transpose image (flip or rotate in 90 degree steps)\n\n        :param method: One of :py:attr:`PIL.Image.FLIP_LEFT_RIGHT`,\n          :py:attr:`PIL.Image.FLIP_TOP_BOTTOM`, :py:attr:`PIL.Image.ROTATE_90`,\n          :py:attr:`PIL.Image.ROTATE_180`, :py:attr:`PIL.Image.ROTATE_270`,\n          :py:attr:`PIL.Image.TRANSPOSE` or :py:attr:`PIL.Image.TRANSVERSE`.\n        :returns: Returns a flipped or rotated copy of this image.\n        \"\"\"\n\n        self.load()\n        return self._new(self.im.transpose(method))\n\n    def effect_spread(self, distance):\n        \"\"\"\n        Randomly spread pixels in an image.\n\n        :param distance: Distance to spread pixels.\n        \"\"\"\n        self.load()\n        return self._new(self.im.effect_spread(distance))\n\n    def toqimage(self):\n        \"\"\"Returns a QImage copy of this image\"\"\"\n        from . import ImageQt\n\n        if not ImageQt.qt_is_installed:\n            raise ImportError(\"Qt bindings are not installed\")\n        return ImageQt.toqimage(self)\n\n    def toqpixmap(self):\n        \"\"\"Returns a QPixmap copy of this image\"\"\"\n        from . import ImageQt\n\n        if not ImageQt.qt_is_installed:\n            raise ImportError(\"Qt bindings are not installed\")\n        return ImageQt.toqpixmap(self)\n\n\n# --------------------------------------------------------------------\n# Abstract handlers.\n\n\nclass ImagePointHandler:\n    # used as a mixin by point transforms (for use with im.point)\n    pass\n\n\nclass ImageTransformHandler:\n    # used as a mixin by geometry transforms (for use with im.transform)\n    pass\n\n\n# --------------------------------------------------------------------\n# Factories\n\n#\n# Debugging\n\n\ndef _wedge():\n    \"\"\"Create greyscale wedge (for debugging only)\"\"\"\n\n    return Image()._new(core.wedge(\"L\"))\n\n\ndef _check_size(size):\n    \"\"\"\n    Common check to enforce type and sanity check on size tuples\n\n    :param size: Should be a 2 tuple of (width, height)\n    :returns: True, or raises a ValueError\n    \"\"\"\n\n    if not isinstance(size, (list, tuple)):\n        raise ValueError(\"Size must be a tuple\")\n    if len(size) != 2:\n        raise ValueError(\"Size must be a tuple of length 2\")\n    if size[0] < 0 or size[1] < 0:\n        raise ValueError(\"Width and height must be >= 0\")\n\n    return True\n\n\ndef new(mode, size, color=0):\n    \"\"\"\n    Creates a new image with the given mode and size.\n\n    :param mode: The mode to use for the new image. See:\n       :ref:`concept-modes`.\n    :param size: A 2-tuple, containing (width, height) in pixels.\n    :param color: What color to use for the image.  Default is black.\n       If given, this should be a single integer or floating point value\n       for single-band modes, and a tuple for multi-band modes (one value\n       per band).  When creating RGB images, you can also use color\n       strings as supported by the ImageColor module.  If the color is\n       None, the image is not initialised.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    \"\"\"\n\n    _check_size(size)\n\n    if color is None:\n        # don't initialize\n        return Image()._new(core.new(mode, size))\n\n    if isinstance(color, str):\n        # css3-style specifier\n\n        from . import ImageColor\n\n        color = ImageColor.getcolor(color, mode)\n\n    im = Image()\n    if mode == \"P\" and isinstance(color, (list, tuple)) and len(color) in [3, 4]:\n        # RGB or RGBA value for a P image\n        from . import ImagePalette\n\n        im.palette = ImagePalette.ImagePalette()\n        color = im.palette.getcolor(color)\n    return im._new(core.fill(mode, size, color))\n\n\ndef frombytes(mode, size, data, decoder_name=\"raw\", *args):\n    \"\"\"\n    Creates a copy of an image memory from pixel data in a buffer.\n\n    In its simplest form, this function takes three arguments\n    (mode, size, and unpacked pixel data).\n\n    You can also use any pixel decoder supported by PIL.  For more\n    information on available decoders, see the section\n    :ref:`Writing Your Own File Decoder <file-decoders>`.\n\n    Note that this function decodes pixel data only, not entire images.\n    If you have an entire image in a string, wrap it in a\n    :py:class:`~io.BytesIO` object, and use :py:func:`~PIL.Image.open` to load\n    it.\n\n    :param mode: The image mode. See: :ref:`concept-modes`.\n    :param size: The image size.\n    :param data: A byte buffer containing raw data for the given mode.\n    :param decoder_name: What decoder to use.\n    :param args: Additional parameters for the given decoder.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    \"\"\"\n\n    _check_size(size)\n\n    # may pass tuple instead of argument list\n    if len(args) == 1 and isinstance(args[0], tuple):\n        args = args[0]\n\n    if decoder_name == \"raw\" and args == ():\n        args = mode\n\n    im = new(mode, size)\n    im.frombytes(data, decoder_name, args)\n    return im\n\n\ndef fromstring(*args, **kw):\n    raise NotImplementedError(\n        \"fromstring() has been removed. Please call frombytes() instead.\"\n    )\n\n\ndef frombuffer(mode, size, data, decoder_name=\"raw\", *args):\n    \"\"\"\n    Creates an image memory referencing pixel data in a byte buffer.\n\n    This function is similar to :py:func:`~PIL.Image.frombytes`, but uses data\n    in the byte buffer, where possible.  This means that changes to the\n    original buffer object are reflected in this image).  Not all modes can\n    share memory; supported modes include \"L\", \"RGBX\", \"RGBA\", and \"CMYK\".\n\n    Note that this function decodes pixel data only, not entire images.\n    If you have an entire image file in a string, wrap it in a\n    **BytesIO** object, and use :py:func:`~PIL.Image.open` to load it.\n\n    In the current version, the default parameters used for the \"raw\" decoder\n    differs from that used for :py:func:`~PIL.Image.frombytes`.  This is a\n    bug, and will probably be fixed in a future release.  The current release\n    issues a warning if you do this; to disable the warning, you should provide\n    the full set of parameters.  See below for details.\n\n    :param mode: The image mode. See: :ref:`concept-modes`.\n    :param size: The image size.\n    :param data: A bytes or other buffer object containing raw\n        data for the given mode.\n    :param decoder_name: What decoder to use.\n    :param args: Additional parameters for the given decoder.  For the\n        default encoder (\"raw\"), it's recommended that you provide the\n        full set of parameters::\n\n            frombuffer(mode, size, data, \"raw\", mode, 0, 1)\n\n    :returns: An :py:class:`~PIL.Image.Image` object.\n\n    .. versionadded:: 1.1.4\n    \"\"\"\n\n    _check_size(size)\n\n    # may pass tuple instead of argument list\n    if len(args) == 1 and isinstance(args[0], tuple):\n        args = args[0]\n\n    if decoder_name == \"raw\":\n        if args == ():\n            args = mode, 0, 1\n        if args[0] in _MAPMODES:\n            im = new(mode, (1, 1))\n            im = im._new(core.map_buffer(data, size, decoder_name, 0, args))\n            im.readonly = 1\n            return im\n\n    return frombytes(mode, size, data, decoder_name, args)\n\n\ndef fromarray(obj, mode=None):\n    \"\"\"\n    Creates an image memory from an object exporting the array interface\n    (using the buffer protocol).\n\n    If **obj** is not contiguous, then the tobytes method is called\n    and :py:func:`~PIL.Image.frombuffer` is used.\n\n    If you have an image in NumPy::\n\n      from PIL import Image\n      import numpy as np\n      im = Image.open('hopper.jpg')\n      a = np.asarray(im)\n\n    Then this can be used to convert it to a Pillow image::\n\n      im = Image.fromarray(a)\n\n    :param obj: Object with array interface\n    :param mode: Mode to use (will be determined from type if None)\n      See: :ref:`concept-modes`.\n    :returns: An image object.\n\n    .. versionadded:: 1.1.6\n    \"\"\"\n    arr = obj.__array_interface__\n    shape = arr[\"shape\"]\n    ndim = len(shape)\n    strides = arr.get(\"strides\", None)\n    if mode is None:\n        try:\n            typekey = (1, 1) + shape[2:], arr[\"typestr\"]\n        except KeyError:\n            raise TypeError(\"Cannot handle this data type\")\n        try:\n            mode, rawmode = _fromarray_typemap[typekey]\n        except KeyError:\n            raise TypeError(\"Cannot handle this data type: %s, %s\" % typekey)\n    else:\n        rawmode = mode\n    if mode in [\"1\", \"L\", \"I\", \"P\", \"F\"]:\n        ndmax = 2\n    elif mode == \"RGB\":\n        ndmax = 3\n    else:\n        ndmax = 4\n    if ndim > ndmax:\n        raise ValueError(\"Too many dimensions: %d > %d.\" % (ndim, ndmax))\n\n    size = 1 if ndim == 1 else shape[1], shape[0]\n    if strides is not None:\n        if hasattr(obj, \"tobytes\"):\n            obj = obj.tobytes()\n        else:\n            obj = obj.tostring()\n\n    return frombuffer(mode, size, obj, \"raw\", rawmode, 0, 1)\n\n\ndef fromqimage(im):\n    \"\"\"Creates an image instance from a QImage image\"\"\"\n    from . import ImageQt\n\n    if not ImageQt.qt_is_installed:\n        raise ImportError(\"Qt bindings are not installed\")\n    return ImageQt.fromqimage(im)\n\n\ndef fromqpixmap(im):\n    \"\"\"Creates an image instance from a QPixmap image\"\"\"\n    from . import ImageQt\n\n    if not ImageQt.qt_is_installed:\n        raise ImportError(\"Qt bindings are not installed\")\n    return ImageQt.fromqpixmap(im)\n\n\n_fromarray_typemap = {\n    # (shape, typestr) => mode, rawmode\n    # first two members of shape are set to one\n    ((1, 1), \"|b1\"): (\"1\", \"1;8\"),\n    ((1, 1), \"|u1\"): (\"L\", \"L\"),\n    ((1, 1), \"|i1\"): (\"I\", \"I;8\"),\n    ((1, 1), \"<u2\"): (\"I\", \"I;16\"),\n    ((1, 1), \">u2\"): (\"I\", \"I;16B\"),\n    ((1, 1), \"<i2\"): (\"I\", \"I;16S\"),\n    ((1, 1), \">i2\"): (\"I\", \"I;16BS\"),\n    ((1, 1), \"<u4\"): (\"I\", \"I;32\"),\n    ((1, 1), \">u4\"): (\"I\", \"I;32B\"),\n    ((1, 1), \"<i4\"): (\"I\", \"I;32S\"),\n    ((1, 1), \">i4\"): (\"I\", \"I;32BS\"),\n    ((1, 1), \"<f4\"): (\"F\", \"F;32F\"),\n    ((1, 1), \">f4\"): (\"F\", \"F;32BF\"),\n    ((1, 1), \"<f8\"): (\"F\", \"F;64F\"),\n    ((1, 1), \">f8\"): (\"F\", \"F;64BF\"),\n    ((1, 1, 2), \"|u1\"): (\"LA\", \"LA\"),\n    ((1, 1, 3), \"|u1\"): (\"RGB\", \"RGB\"),\n    ((1, 1, 4), \"|u1\"): (\"RGBA\", \"RGBA\"),\n}\n\n# shortcuts\n_fromarray_typemap[((1, 1), _ENDIAN + \"i4\")] = (\"I\", \"I\")\n_fromarray_typemap[((1, 1), _ENDIAN + \"f4\")] = (\"F\", \"F\")\n\n\ndef _decompression_bomb_check(size):\n    if MAX_IMAGE_PIXELS is None:\n        return\n\n    pixels = size[0] * size[1]\n\n    if pixels > 2 * MAX_IMAGE_PIXELS:\n        raise DecompressionBombError(\n            \"Image size (%d pixels) exceeds limit of %d pixels, \"\n            \"could be decompression bomb DOS attack.\" % (pixels, 2 * MAX_IMAGE_PIXELS)\n        )\n\n    if pixels > MAX_IMAGE_PIXELS:\n        warnings.warn(\n            \"Image size (%d pixels) exceeds limit of %d pixels, \"\n            \"could be decompression bomb DOS attack.\" % (pixels, MAX_IMAGE_PIXELS),\n            DecompressionBombWarning,\n        )\n\n\ndef open(fp, mode=\"r\"):\n    \"\"\"\n    Opens and identifies the given image file.\n\n    This is a lazy operation; this function identifies the file, but\n    the file remains open and the actual image data is not read from\n    the file until you try to process the data (or call the\n    :py:meth:`~PIL.Image.Image.load` method).  See\n    :py:func:`~PIL.Image.new`. See :ref:`file-handling`.\n\n    :param fp: A filename (string), pathlib.Path object or a file object.\n       The file object must implement :py:meth:`~file.read`,\n       :py:meth:`~file.seek`, and :py:meth:`~file.tell` methods,\n       and be opened in binary mode.\n    :param mode: The mode.  If given, this argument must be \"r\".\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    :exception FileNotFoundError: If the file cannot be found.\n    :exception PIL.UnidentifiedImageError: If the image cannot be opened and\n       identified.\n    :exception ValueError: If the ``mode`` is not \"r\", or if a ``StringIO``\n       instance is used for ``fp``.\n    \"\"\"\n\n    if mode != \"r\":\n        raise ValueError(\"bad mode %r\" % mode)\n    elif isinstance(fp, io.StringIO):\n        raise ValueError(\n            \"StringIO cannot be used to open an image. \"\n            \"Binary data must be used instead.\"\n        )\n\n    exclusive_fp = False\n    filename = \"\"\n    if isinstance(fp, Path):\n        filename = str(fp.resolve())\n    elif isPath(fp):\n        filename = fp\n\n    if filename:\n        fp = builtins.open(filename, \"rb\")\n        exclusive_fp = True\n\n    try:\n        fp.seek(0)\n    except (AttributeError, io.UnsupportedOperation):\n        fp = io.BytesIO(fp.read())\n        exclusive_fp = True\n\n    prefix = fp.read(16)\n\n    preinit()\n\n    accept_warnings = []\n\n    def _open_core(fp, filename, prefix):\n        for i in ID:\n            try:\n                factory, accept = OPEN[i]\n                result = not accept or accept(prefix)\n                if type(result) in [str, bytes]:\n                    accept_warnings.append(result)\n                elif result:\n                    fp.seek(0)\n                    im = factory(fp, filename)\n                    _decompression_bomb_check(im.size)\n                    return im\n            except (SyntaxError, IndexError, TypeError, struct.error):\n                # Leave disabled by default, spams the logs with image\n                # opening failures that are entirely expected.\n                # logger.debug(\"\", exc_info=True)\n                continue\n            except BaseException:\n                if exclusive_fp:\n                    fp.close()\n                raise\n        return None\n\n    im = _open_core(fp, filename, prefix)\n\n    if im is None:\n        if init():\n            im = _open_core(fp, filename, prefix)\n\n    if im:\n        im._exclusive_fp = exclusive_fp\n        return im\n\n    if exclusive_fp:\n        fp.close()\n    for message in accept_warnings:\n        warnings.warn(message)\n    raise UnidentifiedImageError(\n        \"cannot identify image file %r\" % (filename if filename else fp)\n    )\n\n\n#\n# Image processing.\n\n\ndef alpha_composite(im1, im2):\n    \"\"\"\n    Alpha composite im2 over im1.\n\n    :param im1: The first image. Must have mode RGBA.\n    :param im2: The second image.  Must have mode RGBA, and the same size as\n       the first image.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    \"\"\"\n\n    im1.load()\n    im2.load()\n    return im1._new(core.alpha_composite(im1.im, im2.im))\n\n\ndef blend(im1, im2, alpha):\n    \"\"\"\n    Creates a new image by interpolating between two input images, using\n    a constant alpha.::\n\n        out = image1 * (1.0 - alpha) + image2 * alpha\n\n    :param im1: The first image.\n    :param im2: The second image.  Must have the same mode and size as\n       the first image.\n    :param alpha: The interpolation alpha factor.  If alpha is 0.0, a\n       copy of the first image is returned. If alpha is 1.0, a copy of\n       the second image is returned. There are no restrictions on the\n       alpha value. If necessary, the result is clipped to fit into\n       the allowed output range.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    \"\"\"\n\n    im1.load()\n    im2.load()\n    return im1._new(core.blend(im1.im, im2.im, alpha))\n\n\ndef composite(image1, image2, mask):\n    \"\"\"\n    Create composite image by blending images using a transparency mask.\n\n    :param image1: The first image.\n    :param image2: The second image.  Must have the same mode and\n       size as the first image.\n    :param mask: A mask image.  This image can have mode\n       \"1\", \"L\", or \"RGBA\", and must have the same size as the\n       other two images.\n    \"\"\"\n\n    image = image2.copy()\n    image.paste(image1, None, mask)\n    return image\n\n\ndef eval(image, *args):\n    \"\"\"\n    Applies the function (which should take one argument) to each pixel\n    in the given image. If the image has more than one band, the same\n    function is applied to each band. Note that the function is\n    evaluated once for each possible pixel value, so you cannot use\n    random components or other generators.\n\n    :param image: The input image.\n    :param function: A function object, taking one integer argument.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    \"\"\"\n\n    return image.point(args[0])\n\n\ndef merge(mode, bands):\n    \"\"\"\n    Merge a set of single band images into a new multiband image.\n\n    :param mode: The mode to use for the output image. See:\n        :ref:`concept-modes`.\n    :param bands: A sequence containing one single-band image for\n        each band in the output image.  All bands must have the\n        same size.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    \"\"\"\n\n    if getmodebands(mode) != len(bands) or \"*\" in mode:\n        raise ValueError(\"wrong number of bands\")\n    for band in bands[1:]:\n        if band.mode != getmodetype(mode):\n            raise ValueError(\"mode mismatch\")\n        if band.size != bands[0].size:\n            raise ValueError(\"size mismatch\")\n    for band in bands:\n        band.load()\n    return bands[0]._new(core.merge(mode, *[b.im for b in bands]))\n\n\n# --------------------------------------------------------------------\n# Plugin registry\n\n\ndef register_open(id, factory, accept=None):\n    \"\"\"\n    Register an image file plugin.  This function should not be used\n    in application code.\n\n    :param id: An image format identifier.\n    :param factory: An image file factory method.\n    :param accept: An optional function that can be used to quickly\n       reject images having another format.\n    \"\"\"\n    id = id.upper()\n    ID.append(id)\n    OPEN[id] = factory, accept\n\n\ndef register_mime(id, mimetype):\n    \"\"\"\n    Registers an image MIME type.  This function should not be used\n    in application code.\n\n    :param id: An image format identifier.\n    :param mimetype: The image MIME type for this format.\n    \"\"\"\n    MIME[id.upper()] = mimetype\n\n\ndef register_save(id, driver):\n    \"\"\"\n    Registers an image save function.  This function should not be\n    used in application code.\n\n    :param id: An image format identifier.\n    :param driver: A function to save images in this format.\n    \"\"\"\n    SAVE[id.upper()] = driver\n\n\ndef register_save_all(id, driver):\n    \"\"\"\n    Registers an image function to save all the frames\n    of a multiframe format.  This function should not be\n    used in application code.\n\n    :param id: An image format identifier.\n    :param driver: A function to save images in this format.\n    \"\"\"\n    SAVE_ALL[id.upper()] = driver\n\n\ndef register_extension(id, extension):\n    \"\"\"\n    Registers an image extension.  This function should not be\n    used in application code.\n\n    :param id: An image format identifier.\n    :param extension: An extension used for this format.\n    \"\"\"\n    EXTENSION[extension.lower()] = id.upper()\n\n\ndef register_extensions(id, extensions):\n    \"\"\"\n    Registers image extensions.  This function should not be\n    used in application code.\n\n    :param id: An image format identifier.\n    :param extensions: A list of extensions used for this format.\n    \"\"\"\n    for extension in extensions:\n        register_extension(id, extension)\n\n\ndef registered_extensions():\n    \"\"\"\n    Returns a dictionary containing all file extensions belonging\n    to registered plugins\n    \"\"\"\n    if not EXTENSION:\n        init()\n    return EXTENSION\n\n\ndef register_decoder(name, decoder):\n    \"\"\"\n    Registers an image decoder.  This function should not be\n    used in application code.\n\n    :param name: The name of the decoder\n    :param decoder: A callable(mode, args) that returns an\n                    ImageFile.PyDecoder object\n\n    .. versionadded:: 4.1.0\n    \"\"\"\n    DECODERS[name] = decoder\n\n\ndef register_encoder(name, encoder):\n    \"\"\"\n    Registers an image encoder.  This function should not be\n    used in application code.\n\n    :param name: The name of the encoder\n    :param encoder: A callable(mode, args) that returns an\n                    ImageFile.PyEncoder object\n\n    .. versionadded:: 4.1.0\n    \"\"\"\n    ENCODERS[name] = encoder\n\n\n# --------------------------------------------------------------------\n# Simple display support.  User code may override this.\n\n\ndef _show(image, **options):\n    # override me, as necessary\n    _showxv(image, **options)\n\n\ndef _showxv(image, title=None, **options):\n    from . import ImageShow\n\n    ImageShow.show(image, title, **options)\n\n\n# --------------------------------------------------------------------\n# Effects\n\n\ndef effect_mandelbrot(size, extent, quality):\n    \"\"\"\n    Generate a Mandelbrot set covering the given extent.\n\n    :param size: The requested size in pixels, as a 2-tuple:\n       (width, height).\n    :param extent: The extent to cover, as a 4-tuple:\n       (x0, y0, x1, y2).\n    :param quality: Quality.\n    \"\"\"\n    return Image()._new(core.effect_mandelbrot(size, extent, quality))\n\n\ndef effect_noise(size, sigma):\n    \"\"\"\n    Generate Gaussian noise centered around 128.\n\n    :param size: The requested size in pixels, as a 2-tuple:\n       (width, height).\n    :param sigma: Standard deviation of noise.\n    \"\"\"\n    return Image()._new(core.effect_noise(size, sigma))\n\n\ndef linear_gradient(mode):\n    \"\"\"\n    Generate 256x256 linear gradient from black to white, top to bottom.\n\n    :param mode: Input mode.\n    \"\"\"\n    return Image()._new(core.linear_gradient(mode))\n\n\ndef radial_gradient(mode):\n    \"\"\"\n    Generate 256x256 radial gradient from black to white, centre to edge.\n\n    :param mode: Input mode.\n    \"\"\"\n    return Image()._new(core.radial_gradient(mode))\n\n\n# --------------------------------------------------------------------\n# Resources\n\n\ndef _apply_env_variables(env=None):\n    if env is None:\n        env = os.environ\n\n    for var_name, setter in [\n        (\"PILLOW_ALIGNMENT\", core.set_alignment),\n        (\"PILLOW_BLOCK_SIZE\", core.set_block_size),\n        (\"PILLOW_BLOCKS_MAX\", core.set_blocks_max),\n    ]:\n        if var_name not in env:\n            continue\n\n        var = env[var_name].lower()\n\n        units = 1\n        for postfix, mul in [(\"k\", 1024), (\"m\", 1024 * 1024)]:\n            if var.endswith(postfix):\n                units = mul\n                var = var[: -len(postfix)]\n\n        try:\n            var = int(var) * units\n        except ValueError:\n            warnings.warn(\"{} is not int\".format(var_name))\n            continue\n\n        try:\n            setter(var)\n        except ValueError as e:\n            warnings.warn(\"{}: {}\".format(var_name, e))\n\n\n_apply_env_variables()\natexit.register(core.clear_cache)\n\n\nclass Exif(MutableMapping):\n    endian = \"<\"\n\n    def __init__(self):\n        self._data = {}\n        self._ifds = {}\n        self._info = None\n        self._loaded_exif = None\n\n    def _fixup(self, value):\n        try:\n            if len(value) == 1 and not isinstance(value, dict):\n                return value[0]\n        except Exception:\n            pass\n        return value\n\n    def _fixup_dict(self, src_dict):\n        # Helper function for _getexif()\n        # returns a dict with any single item tuples/lists as individual values\n        return {k: self._fixup(v) for k, v in src_dict.items()}\n\n    def _get_ifd_dict(self, tag):\n        try:\n            # an offset pointer to the location of the nested embedded IFD.\n            # It should be a long, but may be corrupted.\n            self.fp.seek(self[tag])\n        except (KeyError, TypeError):\n            pass\n        else:\n            from . import TiffImagePlugin\n\n            info = TiffImagePlugin.ImageFileDirectory_v1(self.head)\n            info.load(self.fp)\n            return self._fixup_dict(info)\n\n    def load(self, data):\n        # Extract EXIF information.  This is highly experimental,\n        # and is likely to be replaced with something better in a future\n        # version.\n\n        # The EXIF record consists of a TIFF file embedded in a JPEG\n        # application marker (!).\n        if data == self._loaded_exif:\n            return\n        self._loaded_exif = data\n        self._data.clear()\n        self._ifds.clear()\n        self._info = None\n        if not data:\n            return\n\n        if data.startswith(b\"Exif\\x00\\x00\"):\n            data = data[6:]\n        self.fp = io.BytesIO(data)\n        self.head = self.fp.read(8)\n        # process dictionary\n        from . import TiffImagePlugin\n\n        self._info = TiffImagePlugin.ImageFileDirectory_v1(self.head)\n        self.endian = self._info._endian\n        self.fp.seek(self._info.next)\n        self._info.load(self.fp)\n\n        # get EXIF extension\n        ifd = self._get_ifd_dict(0x8769)\n        if ifd:\n            self._data.update(ifd)\n            self._ifds[0x8769] = ifd\n\n    def tobytes(self, offset=8):\n        from . import TiffImagePlugin\n\n        if self.endian == \"<\":\n            head = b\"II\\x2A\\x00\\x08\\x00\\x00\\x00\"\n        else:\n            head = b\"MM\\x00\\x2A\\x00\\x00\\x00\\x08\"\n        ifd = TiffImagePlugin.ImageFileDirectory_v2(ifh=head)\n        for tag, value in self.items():\n            ifd[tag] = value\n        return b\"Exif\\x00\\x00\" + head + ifd.tobytes(offset)\n\n    def get_ifd(self, tag):\n        if tag not in self._ifds and tag in self:\n            if tag in [0x8825, 0xA005]:\n                # gpsinfo, interop\n                self._ifds[tag] = self._get_ifd_dict(tag)\n            elif tag == 0x927C:  # makernote\n                from .TiffImagePlugin import ImageFileDirectory_v2\n\n                if self[0x927C][:8] == b\"FUJIFILM\":\n                    exif_data = self[0x927C]\n                    ifd_offset = i32le(exif_data[8:12])\n                    ifd_data = exif_data[ifd_offset:]\n\n                    makernote = {}\n                    for i in range(0, struct.unpack(\"<H\", ifd_data[:2])[0]):\n                        ifd_tag, typ, count, data = struct.unpack(\n                            \"<HHL4s\", ifd_data[i * 12 + 2 : (i + 1) * 12 + 2]\n                        )\n                        try:\n                            unit_size, handler = ImageFileDirectory_v2._load_dispatch[\n                                typ\n                            ]\n                        except KeyError:\n                            continue\n                        size = count * unit_size\n                        if size > 4:\n                            (offset,) = struct.unpack(\"<L\", data)\n                            data = ifd_data[offset - 12 : offset + size - 12]\n                        else:\n                            data = data[:size]\n\n                        if len(data) != size:\n                            warnings.warn(\n                                \"Possibly corrupt EXIF MakerNote data.  \"\n                                \"Expecting to read %d bytes but only got %d.\"\n                                \" Skipping tag %s\" % (size, len(data), ifd_tag)\n                            )\n                            continue\n\n                        if not data:\n                            continue\n\n                        makernote[ifd_tag] = handler(\n                            ImageFileDirectory_v2(), data, False\n                        )\n                    self._ifds[0x927C] = dict(self._fixup_dict(makernote))\n                elif self.get(0x010F) == \"Nintendo\":\n                    ifd_data = self[0x927C]\n\n                    makernote = {}\n                    for i in range(0, struct.unpack(\">H\", ifd_data[:2])[0]):\n                        ifd_tag, typ, count, data = struct.unpack(\n                            \">HHL4s\", ifd_data[i * 12 + 2 : (i + 1) * 12 + 2]\n                        )\n                        if ifd_tag == 0x1101:\n                            # CameraInfo\n                            (offset,) = struct.unpack(\">L\", data)\n                            self.fp.seek(offset)\n\n                            camerainfo = {\"ModelID\": self.fp.read(4)}\n\n                            self.fp.read(4)\n                            # Seconds since 2000\n                            camerainfo[\"TimeStamp\"] = i32le(self.fp.read(12))\n\n                            self.fp.read(4)\n                            camerainfo[\"InternalSerialNumber\"] = self.fp.read(4)\n\n                            self.fp.read(12)\n                            parallax = self.fp.read(4)\n                            handler = ImageFileDirectory_v2._load_dispatch[\n                                TiffTags.FLOAT\n                            ][1]\n                            camerainfo[\"Parallax\"] = handler(\n                                ImageFileDirectory_v2(), parallax, False\n                            )\n\n                            self.fp.read(4)\n                            camerainfo[\"Category\"] = self.fp.read(2)\n\n                            makernote = {0x1101: dict(self._fixup_dict(camerainfo))}\n                    self._ifds[0x927C] = makernote\n        return self._ifds.get(tag, {})\n\n    def __str__(self):\n        if self._info is not None:\n            # Load all keys into self._data\n            for tag in self._info.keys():\n                self[tag]\n\n        return str(self._data)\n\n    def __len__(self):\n        keys = set(self._data)\n        if self._info is not None:\n            keys.update(self._info)\n        return len(keys)\n\n    def __getitem__(self, tag):\n        if self._info is not None and tag not in self._data and tag in self._info:\n            self._data[tag] = self._fixup(self._info[tag])\n            if tag == 0x8825:\n                self._data[tag] = self.get_ifd(tag)\n            del self._info[tag]\n        return self._data[tag]\n\n    def __contains__(self, tag):\n        return tag in self._data or (self._info is not None and tag in self._info)\n\n    def __setitem__(self, tag, value):\n        if self._info is not None and tag in self._info:\n            del self._info[tag]\n        self._data[tag] = value\n\n    def __delitem__(self, tag):\n        if self._info is not None and tag in self._info:\n            del self._info[tag]\n        del self._data[tag]\n\n    def __iter__(self):\n        keys = set(self._data)\n        if self._info is not None:\n            keys.update(self._info)\n        return iter(keys)\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:** Setting EXIF X-Resolution Causes TypeError During Image Save

**Description:**
When attempting to set the EXIF `XResolution` to an integer value and save the image, a `TypeError` is raised unexpectedly. This issue occurs even though the `XResolution` should accept integer values and handle them correctly during the save operation.

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

def set_exif_x_resolution(image_path, output_path):
    with Image.open(image_path) as img:
        exif = img.getexif()
        exif[282] = 180  # Set XResolution to 180
        img.save(output_path, exif=exif)

set_exif_x_resolution("flower.jpg", "out.jpg")
```

**Expected Behavior:**
The image should be saved successfully with the `XResolution` EXIF tag set to `180`. The operation should complete without any errors, and the saved image should retain the specified resolution metadata.

**Actual Behavior:**
A `TypeError` is raised during the save operation, preventing the image from being saved with the updated EXIF data. This error suggests that the EXIF `XResolution` value is not being handled correctly when assigned an integer.

[/ISSUE]
--- END ISSUE ---

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

--- BEGIN FILE ---
```
### src/PIL/Image.py
#
# The Python Imaging Library.
# $Id$
#
# the Image class wrapper
#
# partial release history:
# 1995-09-09 fl   Created
# 1996-03-11 fl   PIL release 0.0 (proof of concept)
# 1996-04-30 fl   PIL release 0.1b1
# 1999-07-28 fl   PIL release 1.0 final
# 2000-06-07 fl   PIL release 1.1
# 2000-10-20 fl   PIL release 1.1.1
# 2001-05-07 fl   PIL release 1.1.2
# 2002-03-15 fl   PIL release 1.1.3
# 2003-05-10 fl   PIL release 1.1.4
# 2005-03-28 fl   PIL release 1.1.5
# 2006-12-02 fl   PIL release 1.1.6
# 2009-11-15 fl   PIL release 1.1.7
#
# Copyright (c) 1997-2009 by Secret Labs AB.  All rights reserved.
# Copyright (c) 1995-2009 by Fredrik Lundh.
#
# See the README file for information on usage and redistribution.
#

import atexit
import builtins
import io
import logging
import math
import numbers
import os
import struct
import sys
import tempfile
import warnings
import xml.etree.ElementTree
from collections.abc import Callable, MutableMapping
from pathlib import Path

# VERSION was removed in Pillow 6.0.0.
# PILLOW_VERSION is deprecated and will be removed in a future release.
# Use __version__ instead.
from . import (
    ImageMode,
    TiffTags,
    UnidentifiedImageError,
    __version__,
    _plugins,
    _raise_version_warning,
)
from ._binary import i8, i32le
from ._util import deferred_error, isPath

if sys.version_info >= (3, 7):

    def __getattr__(name):
        if name == "PILLOW_VERSION":
            _raise_version_warning()
            return __version__
        raise AttributeError("module '{}' has no attribute '{}'".format(__name__, name))


else:

    from . import PILLOW_VERSION

    # Silence warning
    assert PILLOW_VERSION


logger = logging.getLogger(__name__)


class DecompressionBombWarning(RuntimeWarning):
    pass


class DecompressionBombError(Exception):
    pass


# Limit to around a quarter gigabyte for a 24 bit (3 bpp) image
MAX_IMAGE_PIXELS = int(1024 * 1024 * 1024 // 4 // 3)


try:
    # If the _imaging C module is not present, Pillow will not load.
    # Note that other modules should not refer to _imaging directly;
    # import Image and use the Image.core variable instead.
    # Also note that Image.core is not a publicly documented interface,
    # and should be considered private and subject to change.
    from . import _imaging as core

    if __version__ != getattr(core, "PILLOW_VERSION", None):
        raise ImportError(
            "The _imaging extension was built for another version of Pillow or PIL:\n"
            "Core version: %s\n"
            "Pillow version: %s" % (getattr(core, "PILLOW_VERSION", None), __version__)
        )

except ImportError as v:
    core = deferred_error(ImportError("The _imaging C module is not installed."))
    # Explanations for ways that we know we might have an import error
    if str(v).startswith("Module use of python"):
        # The _imaging C module is present, but not compiled for
        # the right version (windows only).  Print a warning, if
        # possible.
        warnings.warn(
            "The _imaging extension was built for another version of Python.",
            RuntimeWarning,
        )
    elif str(v).startswith("The _imaging extension"):
        warnings.warn(str(v), RuntimeWarning)
    # Fail here anyway. Don't let people run with a mostly broken Pillow.
    # see docs/porting.rst
    raise


# works everywhere, win for pypy, not cpython
USE_CFFI_ACCESS = hasattr(sys, "pypy_version_info")
try:
    import cffi
except ImportError:
    cffi = None


def isImageType(t):
    """
    Checks if an object is an image object.

    .. warning::

       This function is for internal use only.

    :param t: object to check if it's an image
    :returns: True if the object is an image
    """
    return hasattr(t, "im")


#
# Constants

NONE = 0

# transpose
FLIP_LEFT_RIGHT = 0
FLIP_TOP_BOTTOM = 1
ROTATE_90 = 2
ROTATE_180 = 3
ROTATE_270 = 4
TRANSPOSE = 5
TRANSVERSE = 6

# transforms (also defined in Imaging.h)
AFFINE = 0
EXTENT = 1
PERSPECTIVE = 2
QUAD = 3
MESH = 4

# resampling filters (also defined in Imaging.h)
NEAREST = NONE = 0
BOX = 4
BILINEAR = LINEAR = 2
HAMMING = 5
BICUBIC = CUBIC = 3
LANCZOS = ANTIALIAS = 1

_filters_support = {BOX: 0.5, BILINEAR: 1.0, HAMMING: 1.0, BICUBIC: 2.0, LANCZOS: 3.0}


# dithers
NEAREST = NONE = 0
ORDERED = 1  # Not yet implemented
RASTERIZE = 2  # Not yet implemented
FLOYDSTEINBERG = 3  # default

# palettes/quantizers
WEB = 0
ADAPTIVE = 1

MEDIANCUT = 0
MAXCOVERAGE = 1
FASTOCTREE = 2
LIBIMAGEQUANT = 3

# categories
NORMAL = 0
SEQUENCE = 1
CONTAINER = 2

if hasattr(core, "DEFAULT_STRATEGY"):
    DEFAULT_STRATEGY = core.DEFAULT_STRATEGY
    FILTERED = core.FILTERED
    HUFFMAN_ONLY = core.HUFFMAN_ONLY
    RLE = core.RLE
    FIXED = core.FIXED


# --------------------------------------------------------------------
# Registries

ID = []
OPEN = {}
MIME = {}
SAVE = {}
SAVE_ALL = {}
EXTENSION = {}
DECODERS = {}
ENCODERS = {}

# --------------------------------------------------------------------
# Modes supported by this version

_MODEINFO = {
    # NOTE: this table will be removed in future versions.  use
    # getmode* functions or ImageMode descriptors instead.
    # official modes
    "1": ("L", "L", ("1",)),
    "L": ("L", "L", ("L",)),
    "I": ("L", "I", ("I",)),
    "F": ("L", "F", ("F",)),
    "P": ("P", "L", ("P",)),
    "RGB": ("RGB", "L", ("R", "G", "B")),
    "RGBX": ("RGB", "L", ("R", "G", "B", "X")),
    "RGBA": ("RGB", "L", ("R", "G", "B", "A")),
    "CMYK": ("RGB", "L", ("C", "M", "Y", "K")),
    "YCbCr": ("RGB", "L", ("Y", "Cb", "Cr")),
    "LAB": ("RGB", "L", ("L", "A", "B")),
    "HSV": ("RGB", "L", ("H", "S", "V")),
    # Experimental modes include I;16, I;16L, I;16B, RGBa, BGR;15, and
    # BGR;24.  Use these modes only if you know exactly what you're
    # doing...
}

if sys.byteorder == "little":
    _ENDIAN = "<"
else:
    _ENDIAN = ">"

_MODE_CONV = {
    # official modes
    "1": ("|b1", None),  # Bits need to be extended to bytes
    "L": ("|u1", None),
    "LA": ("|u1", 2),
    "I": (_ENDIAN + "i4", None),
    "F": (_ENDIAN + "f4", None),
    "P": ("|u1", None),
    "RGB": ("|u1", 3),
    "RGBX": ("|u1", 4),
    "RGBA": ("|u1", 4),
    "CMYK": ("|u1", 4),
    "YCbCr": ("|u1", 3),
    "LAB": ("|u1", 3),  # UNDONE - unsigned |u1i1i1
    "HSV": ("|u1", 3),
    # I;16 == I;16L, and I;32 == I;32L
    "I;16": ("<u2", None),
    "I;16B": (">u2", None),
    "I;16L": ("<u2", None),
    "I;16S": ("<i2", None),
    "I;16BS": (">i2", None),
    "I;16LS": ("<i2", None),
    "I;32": ("<u4", None),
    "I;32B": (">u4", None),
    "I;32L": ("<u4", None),
    "I;32S": ("<i4", None),
    "I;32BS": (">i4", None),
    "I;32LS": ("<i4", None),
}


def _conv_type_shape(im):
    typ, extra = _MODE_CONV[im.mode]
    if extra is None:
        return (im.size[1], im.size[0]), typ
    else:
        return (im.size[1], im.size[0], extra), typ


MODES = sorted(_MODEINFO)

# raw modes that may be memory mapped.  NOTE: if you change this, you
# may have to modify the stride calculation in map.c too!
_MAPMODES = ("L", "P", "RGBX", "RGBA", "CMYK", "I;16", "I;16L", "I;16B")


def getmodebase(mode):
    """
    Gets the "base" mode for given mode.  This function returns "L" for
    images that contain grayscale data, and "RGB" for images that
    contain color data.

    :param mode: Input mode.
    :returns: "L" or "RGB".
    :exception KeyError: If the input mode was not a standard mode.
    """
    return ImageMode.getmode(mode).basemode


def getmodetype(mode):
    """
    Gets the storage type mode.  Given a mode, this function returns a
    single-layer mode suitable for storing individual bands.

    :param mode: Input mode.
    :returns: "L", "I", or "F".
    :exception KeyError: If the input mode was not a standard mode.
    """
    return ImageMode.getmode(mode).basetype


def getmodebandnames(mode):
    """
    Gets a list of individual band names.  Given a mode, this function returns
    a tuple containing the names of individual bands (use
    :py:method:`~PIL.Image.getmodetype` to get the mode used to store each
    individual band.

    :param mode: Input mode.
    :returns: A tuple containing band names.  The length of the tuple
        gives the number of bands in an image of the given mode.
    :exception KeyError: If the input mode was not a standard mode.
    """
    return ImageMode.getmode(mode).bands


def getmodebands(mode):
    """
    Gets the number of individual bands for this mode.

    :param mode: Input mode.
    :returns: The number of bands in this mode.
    :exception KeyError: If the input mode was not a standard mode.
    """
    return len(ImageMode.getmode(mode).bands)


# --------------------------------------------------------------------
# Helpers

_initialized = 0


def preinit():
    """Explicitly load standard file format drivers."""

    global _initialized
    if _initialized >= 1:
        return

    try:
        from . import BmpImagePlugin

        assert BmpImagePlugin
    except ImportError:
        pass
    try:
        from . import GifImagePlugin

        assert GifImagePlugin
    except ImportError:
        pass
    try:
        from . import JpegImagePlugin

        assert JpegImagePlugin
    except ImportError:
        pass
    try:
        from . import PpmImagePlugin

        assert PpmImagePlugin
    except ImportError:
        pass
    try:
        from . import PngImagePlugin

        assert PngImagePlugin
    except ImportError:
        pass
    # try:
    #     import TiffImagePlugin
    #     assert TiffImagePlugin
    # except ImportError:
    #     pass

    _initialized = 1


def init():
    """
    Explicitly initializes the Python Imaging Library. This function
    loads all available file format drivers.
    """

    global _initialized
    if _initialized >= 2:
        return 0

    for plugin in _plugins:
        try:
            logger.debug("Importing %s", plugin)
            __import__("PIL.%s" % plugin, globals(), locals(), [])
        except ImportError as e:
            logger.debug("Image: failed to import %s: %s", plugin, e)

    if OPEN or SAVE:
        _initialized = 2
        return 1


# --------------------------------------------------------------------
# Codec factories (used by tobytes/frombytes and ImageFile.load)


def _getdecoder(mode, decoder_name, args, extra=()):

    # tweak arguments
    if args is None:
        args = ()
    elif not isinstance(args, tuple):
        args = (args,)

    try:
        decoder = DECODERS[decoder_name]
    except KeyError:
        pass
    else:
        return decoder(mode, *args + extra)

    try:
        # get decoder
        decoder = getattr(core, decoder_name + "_decoder")
    except AttributeError:
        raise OSError("decoder %s not available" % decoder_name)
    return decoder(mode, *args + extra)


def _getencoder(mode, encoder_name, args, extra=()):

    # tweak arguments
    if args is None:
        args = ()
    elif not isinstance(args, tuple):
        args = (args,)

    try:
        encoder = ENCODERS[encoder_name]
    except KeyError:
        pass
    else:
        return encoder(mode, *args + extra)

    try:
        # get encoder
        encoder = getattr(core, encoder_name + "_encoder")
    except AttributeError:
        raise OSError("encoder %s not available" % encoder_name)
    return encoder(mode, *args + extra)


# --------------------------------------------------------------------
# Simple expression analyzer


def coerce_e(value):
    return value if isinstance(value, _E) else _E(value)


class _E:
    def __init__(self, data):
        self.data = data

    def __add__(self, other):
        return _E((self.data, "__add__", coerce_e(other).data))

    def __mul__(self, other):
        return _E((self.data, "__mul__", coerce_e(other).data))


def _getscaleoffset(expr):
    stub = ["stub"]
    data = expr(_E(stub)).data
    try:
        (a, b, c) = data  # simplified syntax
        if a is stub and b == "__mul__" and isinstance(c, numbers.Number):
            return c, 0.0
        if a is stub and b == "__add__" and isinstance(c, numbers.Number):
            return 1.0, c
    except TypeError:
        pass
    try:
        ((a, b, c), d, e) = data  # full syntax
        if (
            a is stub
            and b == "__mul__"
            and isinstance(c, numbers.Number)
            and d == "__add__"
            and isinstance(e, numbers.Number)
        ):
            return c, e
    except TypeError:
        pass
    raise ValueError("illegal expression")


# --------------------------------------------------------------------
# Implementation wrapper


class Image:
    """
    This class represents an image object.  To create
    :py:class:`~PIL.Image.Image` objects, use the appropriate factory
    functions.  There's hardly ever any reason to call the Image constructor
    directly.

    * :py:func:`~PIL.Image.open`
    * :py:func:`~PIL.Image.new`
    * :py:func:`~PIL.Image.frombytes`
    """

    format = None
    format_description = None
    _close_exclusive_fp_after_loading = True

    def __init__(self):
        # FIXME: take "new" parameters / other image?
        # FIXME: turn mode and size into delegating properties?
        self.im = None
        self.mode = ""
        self._size = (0, 0)
        self.palette = None
        self.info = {}
        self.category = NORMAL
        self.readonly = 0
        self.pyaccess = None
        self._exif = None

    @property
    def width(self):
        return self.size[0]

    @property
    def height(self):
        return self.size[1]

    @property
    def size(self):
        return self._size

    def _new(self, im):
        new = Image()
        new.im = im
        new.mode = im.mode
        new._size = im.size
        if im.mode in ("P", "PA"):
            if self.palette:
                new.palette = self.palette.copy()
            else:
                from . import ImagePalette

                new.palette = ImagePalette.ImagePalette()
        new.info = self.info.copy()
        return new

    # Context manager support
    def __enter__(self):
        return self

    def __exit__(self, *args):
        if hasattr(self, "fp") and getattr(self, "_exclusive_fp", False):
            if hasattr(self, "_close__fp"):
                self._close__fp()
            if self.fp:
                self.fp.close()
        self.fp = None

    def close(self):
        """
        Closes the file pointer, if possible.

        This operation will destroy the image core and release its memory.
        The image data will be unusable afterward.

        This function is only required to close images that have not
        had their file read and closed by the
        :py:meth:`~PIL.Image.Image.load` method. See
        :ref:`file-handling` for more information.
        """
        try:
            if hasattr(self, "_close__fp"):
                self._close__fp()
            self.fp.close()
            self.fp = None
        except Exception as msg:
            logger.debug("Error closing: %s", msg)

        if getattr(self, "map", None):
            self.map = None

        # Instead of simply setting to None, we're setting up a
        # deferred error that will better explain that the core image
        # object is gone.
        self.im = deferred_error(ValueError("Operation on closed image"))

    def _copy(self):
        self.load()
        self.im = self.im.copy()
        self.pyaccess = None
        self.readonly = 0

    def _ensure_mutable(self):
        if self.readonly:
            self._copy()
        else:
            self.load()

    def _dump(self, file=None, format=None, **options):
        suffix = ""
        if format:
            suffix = "." + format

        if not file:
            f, filename = tempfile.mkstemp(suffix)
            os.close(f)
        else:
            filename = file
            if not filename.endswith(suffix):
                filename = filename + suffix

        self.load()

        if not format or format == "PPM":
            self.im.save_ppm(filename)
        else:
            self.save(filename, format, **options)

        return filename

    def __eq__(self, other):
        return (
            self.__class__ is other.__class__
            and self.mode == other.mode
            and self.size == other.size
            and self.info == other.info
            and self.category == other.category
            and self.readonly == other.readonly
            and self.getpalette() == other.getpalette()
            and self.tobytes() == other.tobytes()
        )

    def __repr__(self):
        return "<%s.%s image mode=%s size=%dx%d at 0x%X>" % (
            self.__class__.__module__,
            self.__class__.__name__,
            self.mode,
            self.size[0],
            self.size[1],
            id(self),
        )

    def _repr_png_(self):
        """ iPython display hook support

        :returns: png version of the image as bytes
        """
        b = io.BytesIO()
        self.save(b, "PNG")
        return b.getvalue()

    @property
    def __array_interface__(self):
        # numpy array interface support
        new = {}
        shape, typestr = _conv_type_shape(self)
        new["shape"] = shape
        new["typestr"] = typestr
        new["version"] = 3
        if self.mode == "1":
            # Binary images need to be extended from bits to bytes
            # See: https://github.com/python-pillow/Pillow/issues/350
            new["data"] = self.tobytes("raw", "L")
        else:
            new["data"] = self.tobytes()
        return new

    def __getstate__(self):
        return [self.info, self.mode, self.size, self.getpalette(), self.tobytes()]

    def __setstate__(self, state):
        Image.__init__(self)
        self.tile = []
        info, mode, size, palette, data = state
        self.info = info
        self.mode = mode
        self._size = size
        self.im = core.new(mode, size)
        if mode in ("L", "LA", "P", "PA") and palette:
            self.putpalette(palette)
        self.frombytes(data)

    def tobytes(self, encoder_name="raw", *args):
        """
        Return image as a bytes object.

        .. warning::

            This method returns the raw image data from the internal
            storage.  For compressed image data (e.g. PNG, JPEG) use
            :meth:`~.save`, with a BytesIO parameter for in-memory
            data.

        :param encoder_name: What encoder to use.  The default is to
                             use the standard "raw" encoder.
        :param args: Extra arguments to the encoder.
        :rtype: A bytes object.
        """

        # may pass tuple instead of argument list
        if len(args) == 1 and isinstance(args[0], tuple):
            args = args[0]

        if encoder_name == "raw" and args == ():
            args = self.mode

        self.load()

        # unpack data
        e = _getencoder(self.mode, encoder_name, args)
        e.setimage(self.im)

        bufsize = max(65536, self.size[0] * 4)  # see RawEncode.c

        data = []
        while True:
            l, s, d = e.encode(bufsize)
            data.append(d)
            if s:
                break
        if s < 0:
            raise RuntimeError("encoder error %d in tobytes" % s)

        return b"".join(data)

    def tostring(self, *args, **kw):
        raise NotImplementedError(
            "tostring() has been removed. Please call tobytes() instead."
        )

    def tobitmap(self, name="image"):
        """
        Returns the image converted to an X11 bitmap.

        .. note:: This method only works for mode "1" images.

        :param name: The name prefix to use for the bitmap variables.
        :returns: A string containing an X11 bitmap.
        :raises ValueError: If the mode is not "1"
        """

        self.load()
        if self.mode != "1":
            raise ValueError("not a bitmap")
        data = self.tobytes("xbm")
        return b"".join(
            [
                ("#define %s_width %d\n" % (name, self.size[0])).encode("ascii"),
                ("#define %s_height %d\n" % (name, self.size[1])).encode("ascii"),
                ("static char %s_bits[] = {\n" % name).encode("ascii"),
                data,
                b"};",
            ]
        )

    def frombytes(self, data, decoder_name="raw", *args):
        """
        Loads this image with pixel data from a bytes object.

        This method is similar to the :py:func:`~PIL.Image.frombytes` function,
        but loads data into this image instead of creating a new image object.
        """

        # may pass tuple instead of argument list
        if len(args) == 1 and isinstance(args[0], tuple):
            args = args[0]

        # default format
        if decoder_name == "raw" and args == ():
            args = self.mode

        # unpack data
        d = _getdecoder(self.mode, decoder_name, args)
        d.setimage(self.im)
        s = d.decode(data)

        if s[0] >= 0:
            raise ValueError("not enough image data")
        if s[1] != 0:
            raise ValueError("cannot decode image data")

    def fromstring(self, *args, **kw):
        raise NotImplementedError(
            "fromstring() has been removed. Please call frombytes() instead."
        )

    def load(self):
        """
        Allocates storage for the image and loads the pixel data.  In
        normal cases, you don't need to call this method, since the
        Image class automatically loads an opened image when it is
        accessed for the first time.

        If the file associated with the image was opened by Pillow, then this
        method will close it. The exception to this is if the image has
        multiple frames, in which case the file will be left open for seek
        operations. See :ref:`file-handling` for more information.

        :returns: An image access object.
        :rtype: :ref:`PixelAccess` or :py:class:`PIL.PyAccess`
        """
        if self.im and self.palette and self.palette.dirty:
            # realize palette
            self.im.putpalette(*self.palette.getdata())
            self.palette.dirty = 0
            self.palette.mode = "RGB"
            self.palette.rawmode = None
            if "transparency" in self.info:
                if isinstance(self.info["transparency"], int):
                    self.im.putpalettealpha(self.info["transparency"], 0)
                else:
                    self.im.putpalettealphas(self.info["transparency"])
                self.palette.mode = "RGBA"

        if self.im:
            if cffi and USE_CFFI_ACCESS:
                if self.pyaccess:
                    return self.pyaccess
                from . import PyAccess

                self.pyaccess = PyAccess.new(self, self.readonly)
                if self.pyaccess:
                    return self.pyaccess
            return self.im.pixel_access(self.readonly)

    def verify(self):
        """
        Verifies the contents of a file. For data read from a file, this
        method attempts to determine if the file is broken, without
        actually decoding the image data.  If this method finds any
        problems, it raises suitable exceptions.  If you need to load
        the image after using this method, you must reopen the image
        file.
        """
        pass

    def convert(self, mode=None, matrix=None, dither=None, palette=WEB, colors=256):
        """
        Returns a converted copy of this image. For the "P" mode, this
        method translates pixels through the palette.  If mode is
        omitted, a mode is chosen so that all information in the image
        and the palette can be represented without a palette.

        The current version supports all possible conversions between
        "L", "RGB" and "CMYK." The **matrix** argument only supports "L"
        and "RGB".

        When translating a color image to greyscale (mode "L"),
        the library uses the ITU-R 601-2 luma transform::

            L = R * 299/1000 + G * 587/1000 + B * 114/1000

        The default method of converting a greyscale ("L") or "RGB"
        image into a bilevel (mode "1") image uses Floyd-Steinberg
        dither to approximate the original image luminosity levels. If
        dither is NONE, all values larger than 128 are set to 255 (white),
        all other values to 0 (black). To use other thresholds, use the
        :py:meth:`~PIL.Image.Image.point` method.

        When converting from "RGBA" to "P" without a **matrix** argument,
        this passes the operation to :py:meth:`~PIL.Image.Image.quantize`,
        and **dither** and **palette** are ignored.

        :param mode: The requested mode. See: :ref:`concept-modes`.
        :param matrix: An optional conversion matrix.  If given, this
           should be 4- or 12-tuple containing floating point values.
        :param dither: Dithering method, used when converting from
           mode "RGB" to "P" or from "RGB" or "L" to "1".
           Available methods are NONE or FLOYDSTEINBERG (default).
           Note that this is not used when **matrix** is supplied.
        :param palette: Palette to use when converting from mode "RGB"
           to "P".  Available palettes are WEB or ADAPTIVE.
        :param colors: Number of colors to use for the ADAPTIVE palette.
           Defaults to 256.
        :rtype: :py:class:`~PIL.Image.Image`
        :returns: An :py:class:`~PIL.Image.Image` object.
        """

        self.load()

        if not mode and self.mode == "P":
            # determine default mode
            if self.palette:
                mode = self.palette.mode
            else:
                mode = "RGB"
        if not mode or (mode == self.mode and not matrix):
            return self.copy()

        has_transparency = self.info.get("transparency") is not None
        if matrix:
            # matrix conversion
            if mode not in ("L", "RGB"):
                raise ValueError("illegal conversion")
            im = self.im.convert_matrix(mode, matrix)
            new = self._new(im)
            if has_transparency and self.im.bands == 3:
                transparency = new.info["transparency"]

                def convert_transparency(m, v):
                    v = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * 0.5
                    return max(0, min(255, int(v)))

                if mode == "L":
                    transparency = convert_transparency(matrix, transparency)
                elif len(mode) == 3:
                    transparency = tuple(
                        [
                            convert_transparency(
                                matrix[i * 4 : i * 4 + 4], transparency
                            )
                            for i in range(0, len(transparency))
                        ]
                    )
                new.info["transparency"] = transparency
            return new

        if mode == "P" and self.mode == "RGBA":
            return self.quantize(colors)

        trns = None
        delete_trns = False
        # transparency handling
        if has_transparency:
            if self.mode in ("1", "L", "I", "RGB") and mode == "RGBA":
                # Use transparent conversion to promote from transparent
                # color to an alpha channel.
                new_im = self._new(
                    self.im.convert_transparent(mode, self.info["transparency"])
                )
                del new_im.info["transparency"]
                return new_im
            elif self.mode in ("L", "RGB", "P") and mode in ("L", "RGB", "P"):
                t = self.info["transparency"]
                if isinstance(t, bytes):
                    # Dragons. This can't be represented by a single color
                    warnings.warn(
                        "Palette images with Transparency expressed in bytes should be "
                        "converted to RGBA images"
                    )
                    delete_trns = True
                else:
                    # get the new transparency color.
                    # use existing conversions
                    trns_im = Image()._new(core.new(self.mode, (1, 1)))
                    if self.mode == "P":
                        trns_im.putpalette(self.palette)
                        if isinstance(t, tuple):
                            try:
                                t = trns_im.palette.getcolor(t)
                            except Exception:
                                raise ValueError(
                                    "Couldn't allocate a palette color for transparency"
                                )
                    trns_im.putpixel((0, 0), t)

                    if mode in ("L", "RGB"):
                        trns_im = trns_im.convert(mode)
                    else:
                        # can't just retrieve the palette number, got to do it
                        # after quantization.
                        trns_im = trns_im.convert("RGB")
                    trns = trns_im.getpixel((0, 0))

            elif self.mode == "P" and mode == "RGBA":
                t = self.info["transparency"]
                delete_trns = True

                if isinstance(t, bytes):
                    self.im.putpalettealphas(t)
                elif isinstance(t, int):
                    self.im.putpalettealpha(t, 0)
                else:
                    raise ValueError("Transparency for P mode should be bytes or int")

        if mode == "P" and palette == ADAPTIVE:
            im = self.im.quantize(colors)
            new = self._new(im)
            from . import ImagePalette

            new.palette = ImagePalette.raw("RGB", new.im.getpalette("RGB"))
            if delete_trns:
                # This could possibly happen if we requantize to fewer colors.
                # The transparency would be totally off in that case.
                del new.info["transparency"]
            if trns is not None:
                try:
                    new.info["transparency"] = new.palette.getcolor(trns)
                except Exception:
                    # if we can't make a transparent color, don't leave the old
                    # transparency hanging around to mess us up.
                    del new.info["transparency"]
                    warnings.warn("Couldn't allocate palette entry for transparency")
            return new

        # colorspace conversion
        if dither is None:
            dither = FLOYDSTEINBERG

        try:
            im = self.im.convert(mode, dither)
        except ValueError:
            try:
                # normalize source image and try again
                im = self.im.convert(getmodebase(self.mode))
                im = im.convert(mode, dither)
            except KeyError:
                raise ValueError("illegal conversion")

        new_im = self._new(im)
        if delete_trns:
            # crash fail if we leave a bytes transparency in an rgb/l mode.
            del new_im.info["transparency"]
        if trns is not None:
            if new_im.mode == "P":
                try:
                    new_im.info["transparency"] = new_im.palette.getcolor(trns)
                except Exception:
                    del new_im.info["transparency"]
                    warnings.warn("Couldn't allocate palette entry for transparency")
            else:
                new_im.info["transparency"] = trns
        return new_im

    def quantize(self, colors=256, method=None, kmeans=0, palette=None, dither=1):
        """
        Convert the image to 'P' mode with the specified number
        of colors.

        :param colors: The desired number of colors, <= 256
        :param method: 0 = median cut
                       1 = maximum coverage
                       2 = fast octree
                       3 = libimagequant
        :param kmeans: Integer
        :param palette: Quantize to the palette of given
                        :py:class:`PIL.Image.Image`.
        :param dither: Dithering method, used when converting from
           mode "RGB" to "P" or from "RGB" or "L" to "1".
           Available methods are NONE or FLOYDSTEINBERG (default).
           Default: 1 (legacy setting)
        :returns: A new image

        """

        self.load()

        if method is None:
            # defaults:
            method = 0
            if self.mode == "RGBA":
                method = 2

        if self.mode == "RGBA" and method not in (2, 3):
            # Caller specified an invalid mode.
            raise ValueError(
                "Fast Octree (method == 2) and libimagequant (method == 3) "
                "are the only valid methods for quantizing RGBA images"
            )

        if palette:
            # use palette from reference image
            palette.load()
            if palette.mode != "P":
                raise ValueError("bad mode for palette image")
            if self.mode != "RGB" and self.mode != "L":
                raise ValueError(
                    "only RGB or L mode images can be quantized to a palette"
                )
            im = self.im.convert("P", dither, palette.im)
            return self._new(im)

        im = self._new(self.im.quantize(colors, method, kmeans))

        from . import ImagePalette

        mode = im.im.getpalettemode()
        im.palette = ImagePalette.ImagePalette(mode, im.im.getpalette(mode, mode))

        return im

    def copy(self):
        """
        Copies this image. Use this method if you wish to paste things
        into an image, but still retain the original.

        :rtype: :py:class:`~PIL.Image.Image`
        :returns: An :py:class:`~PIL.Image.Image` object.
        """
        self.load()
        return self._new(self.im.copy())

    __copy__ = copy

    def crop(self, box=None):
        """
        Returns a rectangular region from this image. The box is a
        4-tuple defining the left, upper, right, and lower pixel
        coordinate. See :ref:`coordinate-system`.

        Note: Prior to Pillow 3.4.0, this was a lazy operation.

        :param box: The crop rectangle, as a (left, upper, right, lower)-tuple.
        :rtype: :py:class:`~PIL.Image.Image`
        :returns: An :py:class:`~PIL.Image.Image` object.
        """

        if box is None:
            return self.copy()

        self.load()
        return self._new(self._crop(self.im, box))

    def _crop(self, im, box):
        """
        Returns a rectangular region from the core image object im.

        This is equivalent to calling im.crop((x0, y0, x1, y1)), but
        includes additional sanity checks.

        :param im: a core image object
        :param box: The crop rectangle, as a (left, upper, right, lower)-tuple.
        :returns: A core image object.
        """

        x0, y0, x1, y1 = map(int, map(round, box))

        absolute_values = (abs(x1 - x0), abs(y1 - y0))

        _decompression_bomb_check(absolute_values)

        return im.crop((x0, y0, x1, y1))

    def draft(self, mode, size):
        """
        Configures the image file loader so it returns a version of the
        image that as closely as possible matches the given mode and
        size. For example, you can use this method to convert a color
        JPEG to greyscale while loading it.

        If any changes are made, returns a tuple with the chosen ``mode`` and
        ``box`` with coordinates of the original image within the altered one.

        Note that this method modifies the :py:class:`~PIL.Image.Image` object
        in place. If the image has already been loaded, this method has no
        effect.

        Note: This method is not implemented for most images. It is
        currently implemented only for JPEG and MPO images.

        :param mode: The requested mode.
        :param size: The requested size.
        """
        pass

    def _expand(self, xmargin, ymargin=None):
        if ymargin is None:
            ymargin = xmargin
        self.load()
        return self._new(self.im.expand(xmargin, ymargin, 0))

    def filter(self, filter):
        """
        Filters this image using the given filter.  For a list of
        available filters, see the :py:mod:`~PIL.ImageFilter` module.

        :param filter: Filter kernel.
        :returns: An :py:class:`~PIL.Image.Image` object.  """

        from . import ImageFilter

        self.load()

        if isinstance(filter, Callable):
            filter = filter()
        if not hasattr(filter, "filter"):
            raise TypeError(
                "filter argument should be ImageFilter.Filter instance or class"
            )

        multiband = isinstance(filter, ImageFilter.MultibandFilter)
        if self.im.bands == 1 or multiband:
            return self._new(filter.filter(self.im))

        ims = []
        for c in range(self.im.bands):
            ims.append(self._new(filter.filter(self.im.getband(c))))
        return merge(self.mode, ims)

    def getbands(self):
        """
        Returns a tuple containing the name of each band in this image.
        For example, **getbands** on an RGB image returns ("R", "G", "B").

        :returns: A tuple containing band names.
        :rtype: tuple
        """
        return ImageMode.getmode(self.mode).bands

    def getbbox(self):
        """
        Calculates the bounding box of the non-zero regions in the
        image.

        :returns: The bounding box is returned as a 4-tuple defining the
           left, upper, right, and lower pixel coordinate. See
           :ref:`coordinate-system`. If the image is completely empty, this
           method returns None.

        """

        self.load()
        return self.im.getbbox()

    def getcolors(self, maxcolors=256):
        """
        Returns a list of colors used in this image.

        :param maxcolors: Maximum number of colors.  If this number is
           exceeded, this method returns None.  The default limit is
           256 colors.
        :returns: An unsorted list of (count, pixel) values.
        """

        self.load()
        if self.mode in ("1", "L", "P"):
            h = self.im.histogram()
            out = []
            for i in range(256):
                if h[i]:
                    out.append((h[i], i))
            if len(out) > maxcolors:
                return None
            return out
        return self.im.getcolors(maxcolors)

    def getdata(self, band=None):
        """
        Returns the contents of this image as a sequence object
        containing pixel values.  The sequence object is flattened, so
        that values for line one follow directly after the values of
        line zero, and so on.

        Note that the sequence object returned by this method is an
        internal PIL data type, which only supports certain sequence
        operations.  To convert it to an ordinary sequence (e.g. for
        printing), use **list(im.getdata())**.

        :param band: What band to return.  The default is to return
           all bands.  To return a single band, pass in the index
           value (e.g. 0 to get the "R" band from an "RGB" image).
        :returns: A sequence-like object.
        """

        self.load()
        if band is not None:
            return self.im.getband(band)
        return self.im  # could be abused

    def getextrema(self):
        """
        Gets the the minimum and maximum pixel values for each band in
        the image.

        :returns: For a single-band image, a 2-tuple containing the
           minimum and maximum pixel value.  For a multi-band image,
           a tuple containing one 2-tuple for each band.
        """

        self.load()
        if self.im.bands > 1:
            extrema = []
            for i in range(self.im.bands):
                extrema.append(self.im.getband(i).getextrema())
            return tuple(extrema)
        return self.im.getextrema()

    def getexif(self):
        if self._exif is None:
            self._exif = Exif()

        exif_info = self.info.get("exif")
        if exif_info is None and "Raw profile type exif" in self.info:
            exif_info = bytes.fromhex(
                "".join(self.info["Raw profile type exif"].split("\n")[3:])
            )
        self._exif.load(exif_info)

        # XMP tags
        if 0x0112 not in self._exif:
            xmp_tags = self.info.get("XML:com.adobe.xmp")
            if xmp_tags:
                root = xml.etree.ElementTree.fromstring(xmp_tags)
                for elem in root.iter():
                    if elem.tag.endswith("}Description"):
                        orientation = elem.attrib.get(
                            "{http://ns.adobe.com/tiff/1.0/}Orientation"
                        )
                        if orientation:
                            self._exif[0x0112] = int(orientation)
                        break

        return self._exif

    def getim(self):
        """
        Returns a capsule that points to the internal image memory.

        :returns: A capsule object.
        """

        self.load()
        return self.im.ptr

    def getpalette(self):
        """
        Returns the image palette as a list.

        :returns: A list of color values [r, g, b, ...], or None if the
           image has no palette.
        """

        self.load()
        try:
            return list(self.im.getpalette())
        except ValueError:
            return None  # no palette

    def getpixel(self, xy):
        """
        Returns the pixel value at a given position.

        :param xy: The coordinate, given as (x, y). See
           :ref:`coordinate-system`.
        :returns: The pixel value.  If the image is a multi-layer image,
           this method returns a tuple.
        """

        self.load()
        if self.pyaccess:
            return self.pyaccess.getpixel(xy)
        return self.im.getpixel(xy)

    def getprojection(self):
        """
        Get projection to x and y axes

        :returns: Two sequences, indicating where there are non-zero
            pixels along the X-axis and the Y-axis, respectively.
        """

        self.load()
        x, y = self.im.getprojection()
        return [i8(c) for c in x], [i8(c) for c in y]

    def histogram(self, mask=None, extrema=None):
        """
        Returns a histogram for the image. The histogram is returned as
        a list of pixel counts, one for each pixel value in the source
        image. If the image has more than one band, the histograms for
        all bands are concatenated (for example, the histogram for an
        "RGB" image contains 768 values).

        A bilevel image (mode "1") is treated as a greyscale ("L") image
        by this method.

        If a mask is provided, the method returns a histogram for those
        parts of the image where the mask image is non-zero. The mask
        image must have the same size as the image, and be either a
        bi-level image (mode "1") or a greyscale image ("L").

        :param mask: An optional mask.
        :param extrema: An optional tuple of manually-specified extrema.
        :returns: A list containing pixel counts.
        """
        self.load()
        if mask:
            mask.load()
            return self.im.histogram((0, 0), mask.im)
        if self.mode in ("I", "F"):
            if extrema is None:
                extrema = self.getextrema()
            return self.im.histogram(extrema)
        return self.im.histogram()

    def entropy(self, mask=None, extrema=None):
        """
        Calculates and returns the entropy for the image.

        A bilevel image (mode "1") is treated as a greyscale ("L")
        image by this method.

        If a mask is provided, the method employs the histogram for
        those parts of the image where the mask image is non-zero.
        The mask image must have the same size as the image, and be
        either a bi-level image (mode "1") or a greyscale image ("L").

        :param mask: An optional mask.
        :param extrema: An optional tuple of manually-specified extrema.
        :returns: A float value representing the image entropy
        """
        self.load()
        if mask:
            mask.load()
            return self.im.entropy((0, 0), mask.im)
        if self.mode in ("I", "F"):
            if extrema is None:
                extrema = self.getextrema()
            return self.im.entropy(extrema)
        return self.im.entropy()

    def offset(self, xoffset, yoffset=None):
        raise NotImplementedError(
            "offset() has been removed. Please call ImageChops.offset() instead."
        )

    def paste(self, im, box=None, mask=None):
        """
        Pastes another image into this image. The box argument is either
        a 2-tuple giving the upper left corner, a 4-tuple defining the
        left, upper, right, and lower pixel coordinate, or None (same as
        (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size
        of the pasted image must match the size of the region.

        If the modes don't match, the pasted image is converted to the mode of
        this image (see the :py:meth:`~PIL.Image.Image.convert` method for
        details).

        Instead of an image, the source can be a integer or tuple
        containing pixel values.  The method then fills the region
        with the given color.  When creating RGB images, you can
        also use color strings as supported by the ImageColor module.

        If a mask is given, this method updates only the regions
        indicated by the mask.  You can use either "1", "L" or "RGBA"
        images (in the latter case, the alpha band is used as mask).
        Where the mask is 255, the given image is copied as is.  Where
        the mask is 0, the current value is preserved.  Intermediate
        values will mix the two images together, including their alpha
        channels if they have them.

        See :py:meth:`~PIL.Image.Image.alpha_composite` if you want to
        combine images with respect to their alpha channels.

        :param im: Source image or pixel value (integer or tuple).
        :param box: An optional 4-tuple giving the region to paste into.
           If a 2-tuple is used instead, it's treated as the upper left
           corner.  If omitted or None, the source is pasted into the
           upper left corner.

           If an image is given as the second argument and there is no
           third, the box defaults to (0, 0), and the second argument
           is interpreted as a mask image.
        :param mask: An optional mask image.
        """

        if isImageType(box) and mask is None:
            # abbreviated paste(im, mask) syntax
            mask = box
            box = None

        if box is None:
            box = (0, 0)

        if len(box) == 2:
            # upper left corner given; get size from image or mask
            if isImageType(im):
                size = im.size
            elif isImageType(mask):
                size = mask.size
            else:
                # FIXME: use self.size here?
                raise ValueError("cannot determine region size; use 4-item box")
            box += (box[0] + size[0], box[1] + size[1])

        if isinstance(im, str):
            from . import ImageColor

            im = ImageColor.getcolor(im, self.mode)

        elif isImageType(im):
            im.load()
            if self.mode != im.mode:
                if self.mode != "RGB" or im.mode not in ("RGBA", "RGBa"):
                    # should use an adapter for this!
                    im = im.convert(self.mode)
            im = im.im

        self._ensure_mutable()

        if mask:
            mask.load()
            self.im.paste(im, box, mask.im)
        else:
            self.im.paste(im, box)

    def alpha_composite(self, im, dest=(0, 0), source=(0, 0)):
        """ 'In-place' analog of Image.alpha_composite. Composites an image
        onto this image.

        :param im: image to composite over this one
        :param dest: Optional 2 tuple (left, top) specifying the upper
          left corner in this (destination) image.
        :param source: Optional 2 (left, top) tuple for the upper left
          corner in the overlay source image, or 4 tuple (left, top, right,
          bottom) for the bounds of the source rectangle

        Performance Note: Not currently implemented in-place in the core layer.
        """

        if not isinstance(source, (list, tuple)):
            raise ValueError("Source must be a tuple")
        if not isinstance(dest, (list, tuple)):
            raise ValueError("Destination must be a tuple")
        if not len(source) in (2, 4):
            raise ValueError("Source must be a 2 or 4-tuple")
        if not len(dest) == 2:
            raise ValueError("Destination must be a 2-tuple")
        if min(source) < 0:
            raise ValueError("Source must be non-negative")
        if min(dest) < 0:
            raise ValueError("Destination must be non-negative")

        if len(source) == 2:
            source = source + im.size

        # over image, crop if it's not the whole thing.
        if source == (0, 0) + im.size:
            overlay = im
        else:
            overlay = im.crop(source)

        # target for the paste
        box = dest + (dest[0] + overlay.width, dest[1] + overlay.height)

        # destination image. don't copy if we're using the whole image.
        if box == (0, 0) + self.size:
            background = self
        else:
            background = self.crop(box)

        result = alpha_composite(background, overlay)
        self.paste(result, box)

    def point(self, lut, mode=None):
        """
        Maps this image through a lookup table or function.

        :param lut: A lookup table, containing 256 (or 65536 if
           self.mode=="I" and mode == "L") values per band in the
           image.  A function can be used instead, it should take a
           single argument. The function is called once for each
           possible pixel value, and the resulting table is applied to
           all bands of the image.
        :param mode: Output mode (default is same as input).  In the
           current version, this can only be used if the source image
           has mode "L" or "P", and the output has mode "1" or the
           source image mode is "I" and the output mode is "L".
        :returns: An :py:class:`~PIL.Image.Image` object.
        """

        self.load()

        if isinstance(lut, ImagePointHandler):
            return lut.point(self)

        if callable(lut):
            # if it isn't a list, it should be a function
            if self.mode in ("I", "I;16", "F"):
                # check if the function can be used with point_transform
                # UNDONE wiredfool -- I think this prevents us from ever doing
                # a gamma function point transform on > 8bit images.
                scale, offset = _getscaleoffset(lut)
                return self._new(self.im.point_transform(scale, offset))
            # for other modes, convert the function to a table
            lut = [lut(i) for i in range(256)] * self.im.bands

        if self.mode == "F":
            # FIXME: _imaging returns a confusing error message for this case
            raise ValueError("point operation not supported for this mode")

        return self._new(self.im.point(lut, mode))

    def putalpha(self, alpha):
        """
        Adds or replaces the alpha layer in this image.  If the image
        does not have an alpha layer, it's converted to "LA" or "RGBA".
        The new layer must be either "L" or "1".

        :param alpha: The new alpha layer.  This can either be an "L" or "1"
           image having the same size as this image, or an integer or
           other color value.
        """

        self._ensure_mutable()

        if self.mode not in ("LA", "PA", "RGBA"):
            # attempt to promote self to a matching alpha mode
            try:
                mode = getmodebase(self.mode) + "A"
                try:
                    self.im.setmode(mode)
                except (AttributeError, ValueError):
                    # do things the hard way
                    im = self.im.convert(mode)
                    if im.mode not in ("LA", "PA", "RGBA"):
                        raise ValueError  # sanity check
                    self.im = im
                self.pyaccess = None
                self.mode = self.im.mode
            except (KeyError, ValueError):
                raise ValueError("illegal image mode")

        if self.mode in ("LA", "PA"):
            band = 1
        else:
            band = 3

        if isImageType(alpha):
            # alpha layer
            if alpha.mode not in ("1", "L"):
                raise ValueError("illegal image mode")
            alpha.load()
            if alpha.mode == "1":
                alpha = alpha.convert("L")
        else:
            # constant alpha
            try:
                self.im.fillband(band, alpha)
            except (AttributeError, ValueError):
                # do things the hard way
                alpha = new("L", self.size, alpha)
            else:
                return

        self.im.putband(alpha.im, band)

    def putdata(self, data, scale=1.0, offset=0.0):
        """
        Copies pixel data to this image.  This method copies data from a
        sequence object into the image, starting at the upper left
        corner (0, 0), and continuing until either the image or the
        sequence ends.  The scale and offset values are used to adjust
        the sequence values: **pixel = value*scale + offset**.

        :param data: A sequence object.
        :param scale: An optional scale value.  The default is 1.0.
        :param offset: An optional offset value.  The default is 0.0.
        """

        self._ensure_mutable()

        self.im.putdata(data, scale, offset)

    def putpalette(self, data, rawmode="RGB"):
        """
        Attaches a palette to this image.  The image must be a "P",
        "PA", "L" or "LA" image, and the palette sequence must contain
        768 integer values, where each group of three values represent
        the red, green, and blue values for the corresponding pixel
        index. Instead of an integer sequence, you can use an 8-bit
        string.

        :param data: A palette sequence (either a list or a string).
        :param rawmode: The raw mode of the palette.
        """
        from . import ImagePalette

        if self.mode not in ("L", "LA", "P", "PA"):
            raise ValueError("illegal image mode")
        self.load()
        if isinstance(data, ImagePalette.ImagePalette):
            palette = ImagePalette.raw(data.rawmode, data.palette)
        else:
            if not isinstance(data, bytes):
                data = bytes(data)
            palette = ImagePalette.raw(rawmode, data)
        self.mode = "PA" if "A" in self.mode else "P"
        self.palette = palette
        self.palette.mode = "RGB"
        self.load()  # install new palette

    def putpixel(self, xy, value):
        """
        Modifies the pixel at the given position. The color is given as
        a single numerical value for single-band images, and a tuple for
        multi-band images. In addition to this, RGB and RGBA tuples are
        accepted for P images.

        Note that this method is relatively slow.  For more extensive changes,
        use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw`
        module instead.

        See:

        * :py:meth:`~PIL.Image.Image.paste`
        * :py:meth:`~PIL.Image.Image.putdata`
        * :py:mod:`~PIL.ImageDraw`

        :param xy: The pixel coordinate, given as (x, y). See
           :ref:`coordinate-system`.
        :param value: The pixel value.
        """

        if self.readonly:
            self._copy()
        self.load()

        if self.pyaccess:
            return self.pyaccess.putpixel(xy, value)

        if (
            self.mode == "P"
            and isinstance(value, (list, tuple))
            and len(value) in [3, 4]
        ):
            # RGB or RGBA value for a P image
            value = self.palette.getcolor(value)
        return self.im.putpixel(xy, value)

    def remap_palette(self, dest_map, source_palette=None):
        """
        Rewrites the image to reorder the palette.

        :param dest_map: A list of indexes into the original palette.
           e.g. [1,0] would swap a two item palette, and list(range(256))
           is the identity transform.
        :param source_palette: Bytes or None.
        :returns:  An :py:class:`~PIL.Image.Image` object.

        """
        from . import ImagePalette

        if self.mode not in ("L", "P"):
            raise ValueError("illegal image mode")

        if source_palette is None:
            if self.mode == "P":
                real_source_palette = self.im.getpalette("RGB")[:768]
            else:  # L-mode
                real_source_palette = bytearray(i // 3 for i in range(768))
        else:
            real_source_palette = source_palette

        palette_bytes = b""
        new_positions = [0] * 256

        # pick only the used colors from the palette
        for i, oldPosition in enumerate(dest_map):
            palette_bytes += real_source_palette[oldPosition * 3 : oldPosition * 3 + 3]
            new_positions[oldPosition] = i

        # replace the palette color id of all pixel with the new id

        # Palette images are [0..255], mapped through a 1 or 3
        # byte/color map.  We need to remap the whole image
        # from palette 1 to palette 2. New_positions is
        # an array of indexes into palette 1.  Palette 2 is
        # palette 1 with any holes removed.

        # We're going to leverage the convert mechanism to use the
        # C code to remap the image from palette 1 to palette 2,
        # by forcing the source image into 'L' mode and adding a
        # mapping 'L' mode palette, then converting back to 'L'
        # sans palette thus converting the image bytes, then
        # assigning the optimized RGB palette.

        # perf reference, 9500x4000 gif, w/~135 colors
        # 14 sec prepatch, 1 sec postpatch with optimization forced.

        mapping_palette = bytearray(new_positions)

        m_im = self.copy()
        m_im.mode = "P"

        m_im.palette = ImagePalette.ImagePalette(
            "RGB", palette=mapping_palette * 3, size=768
        )
        # possibly set palette dirty, then
        # m_im.putpalette(mapping_palette, 'L')  # converts to 'P'
        # or just force it.
        # UNDONE -- this is part of the general issue with palettes
        m_im.im.putpalette(*m_im.palette.getdata())

        m_im = m_im.convert("L")

        # Internally, we require 768 bytes for a palette.
        new_palette_bytes = palette_bytes + (768 - len(palette_bytes)) * b"\x00"
        m_im.putpalette(new_palette_bytes)
        m_im.palette = ImagePalette.ImagePalette(
            "RGB", palette=palette_bytes, size=len(palette_bytes)
        )

        return m_im

    def _get_safe_box(self, size, resample, box):
        """Expands the box so it includes adjacent pixels
        that may be used by resampling with the given resampling filter.
        """
        filter_support = _filters_support[resample] - 0.5
        scale_x = (box[2] - box[0]) / size[0]
        scale_y = (box[3] - box[1]) / size[1]
        support_x = filter_support * scale_x
        support_y = filter_support * scale_y

        return (
            max(0, int(box[0] - support_x)),
            max(0, int(box[1] - support_y)),
            min(self.size[0], math.ceil(box[2] + support_x)),
            min(self.size[1], math.ceil(box[3] + support_y)),
        )

    def resize(self, size, resample=BICUBIC, box=None, reducing_gap=None):
        """
        Returns a resized copy of this image.

        :param size: The requested size in pixels, as a 2-tuple:
           (width, height).
        :param resample: An optional resampling filter.  This can be
           one of :py:attr:`PIL.Image.NEAREST`, :py:attr:`PIL.Image.BOX`,
           :py:attr:`PIL.Image.BILINEAR`, :py:attr:`PIL.Image.HAMMING`,
           :py:attr:`PIL.Image.BICUBIC` or :py:attr:`PIL.Image.LANCZOS`.
           Default filter is :py:attr:`PIL.Image.BICUBIC`.
           If the image has mode "1" or "P", it is
           always set to :py:attr:`PIL.Image.NEAREST`.
           See: :ref:`concept-filters`.
        :param box: An optional 4-tuple of floats providing
           the source image region to be scaled.
           The values must be within (0, 0, width, height) rectangle.
           If omitted or None, the entire source is used.
        :param reducing_gap: Apply optimization by resizing the image
           in two steps. First, reducing the image by integer times
           using :py:meth:`~PIL.Image.Image.reduce`.
           Second, resizing using regular resampling. The last step
           changes size no less than by ``reducing_gap`` times.
           ``reducing_gap`` may be None (no first step is performed)
           or should be greater than 1.0. The bigger ``reducing_gap``,
           the closer the result to the fair resampling.
           The smaller ``reducing_gap``, the faster resizing.
           With ``reducing_gap`` greater or equal to 3.0, the result is
           indistinguishable from fair resampling in most cases.
           The default value is None (no optimization).
        :returns: An :py:class:`~PIL.Image.Image` object.
        """

        if resample not in (NEAREST, BILINEAR, BICUBIC, LANCZOS, BOX, HAMMING):
            message = "Unknown resampling filter ({}).".format(resample)

            filters = [
                "{} ({})".format(filter[1], filter[0])
                for filter in (
                    (NEAREST, "Image.NEAREST"),
                    (LANCZOS, "Image.LANCZOS"),
                    (BILINEAR, "Image.BILINEAR"),
                    (BICUBIC, "Image.BICUBIC"),
                    (BOX, "Image.BOX"),
                    (HAMMING, "Image.HAMMING"),
                )
            ]
            raise ValueError(
                message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1]
            )

        if reducing_gap is not None and reducing_gap < 1.0:
            raise ValueError("reducing_gap must be 1.0 or greater")

        size = tuple(size)

        if box is None:
            box = (0, 0) + self.size
        else:
            box = tuple(box)

        if self.size == size and box == (0, 0) + self.size:
            return self.copy()

        if self.mode in ("1", "P"):
            resample = NEAREST

        if self.mode in ["LA", "RGBA"]:
            im = self.convert(self.mode[:-1] + "a")
            im = im.resize(size, resample, box)
            return im.convert(self.mode)

        self.load()

        if reducing_gap is not None and resample != NEAREST:
            factor_x = int((box[2] - box[0]) / size[0] / reducing_gap) or 1
            factor_y = int((box[3] - box[1]) / size[1] / reducing_gap) or 1
            if factor_x > 1 or factor_y > 1:
                reduce_box = self._get_safe_box(size, resample, box)
                factor = (factor_x, factor_y)
                if callable(self.reduce):
                    self = self.reduce(factor, box=reduce_box)
                else:
                    self = Image.reduce(self, factor, box=reduce_box)
                box = (
                    (box[0] - reduce_box[0]) / factor_x,
                    (box[1] - reduce_box[1]) / factor_y,
                    (box[2] - reduce_box[0]) / factor_x,
                    (box[3] - reduce_box[1]) / factor_y,
                )

        return self._new(self.im.resize(size, resample, box))

    def reduce(self, factor, box=None):
        """
        Returns a copy of the image reduced by `factor` times.
        If the size of the image is not dividable by the `factor`,
        the resulting size will be rounded up.

        :param factor: A greater than 0 integer or tuple of two integers
           for width and height separately.
        :param box: An optional 4-tuple of ints providing
           the source image region to be reduced.
           The values must be within (0, 0, width, height) rectangle.
           If omitted or None, the entire source is used.
        """
        if not isinstance(factor, (list, tuple)):
            factor = (factor, factor)

        if box is None:
            box = (0, 0) + self.size
        else:
            box = tuple(box)

        if factor == (1, 1) and box == (0, 0) + self.size:
            return self.copy()

        if self.mode in ["LA", "RGBA"]:
            im = self.convert(self.mode[:-1] + "a")
            im = im.reduce(factor, box)
            return im.convert(self.mode)

        self.load()

        return self._new(self.im.reduce(factor, box))

    def rotate(
        self,
        angle,
        resample=NEAREST,
        expand=0,
        center=None,
        translate=None,
        fillcolor=None,
    ):
        """
        Returns a rotated copy of this image.  This method returns a
        copy of this image, rotated the given number of degrees counter
        clockwise around its centre.

        :param angle: In degrees counter clockwise.
        :param resample: An optional resampling filter.  This can be
           one of :py:attr:`PIL.Image.NEAREST` (use nearest neighbour),
           :py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2
           environment), or :py:attr:`PIL.Image.BICUBIC`
           (cubic spline interpolation in a 4x4 environment).
           If omitted, or if the image has mode "1" or "P", it is
           set to :py:attr:`PIL.Image.NEAREST`. See :ref:`concept-filters`.
        :param expand: Optional expansion flag.  If true, expands the output
           image to make it large enough to hold the entire rotated image.
           If false or omitted, make the output image the same size as the
           input image.  Note that the expand flag assumes rotation around
           the center and no translation.
        :param center: Optional center of rotation (a 2-tuple).  Origin is
           the upper left corner.  Default is the center of the image.
        :param translate: An optional post-rotate translation (a 2-tuple).
        :param fillcolor: An optional color for area outside the rotated image.
        :returns: An :py:class:`~PIL.Image.Image` object.
        """

        angle = angle % 360.0

        # Fast paths regardless of filter, as long as we're not
        # translating or changing the center.
        if not (center or translate):
            if angle == 0:
                return self.copy()
            if angle == 180:
                return self.transpose(ROTATE_180)
            if angle == 90 and expand:
                return self.transpose(ROTATE_90)
            if angle == 270 and expand:
                return self.transpose(ROTATE_270)

        # Calculate the affine matrix.  Note that this is the reverse
        # transformation (from destination image to source) because we
        # want to interpolate the (discrete) destination pixel from
        # the local area around the (floating) source pixel.

        # The matrix we actually want (note that it operates from the right):
        # (1, 0, tx)   (1, 0, cx)   ( cos a, sin a, 0)   (1, 0, -cx)
        # (0, 1, ty) * (0, 1, cy) * (-sin a, cos a, 0) * (0, 1, -cy)
        # (0, 0,  1)   (0, 0,  1)   (     0,     0, 1)   (0, 0,   1)

        # The reverse matrix is thus:
        # (1, 0, cx)   ( cos -a, sin -a, 0)   (1, 0, -cx)   (1, 0, -tx)
        # (0, 1, cy) * (-sin -a, cos -a, 0) * (0, 1, -cy) * (0, 1, -ty)
        # (0, 0,  1)   (      0,      0, 1)   (0, 0,   1)   (0, 0,   1)

        # In any case, the final translation may be updated at the end to
        # compensate for the expand flag.

        w, h = self.size

        if translate is None:
            post_trans = (0, 0)
        else:
            post_trans = translate
        if center is None:
            # FIXME These should be rounded to ints?
            rotn_center = (w / 2.0, h / 2.0)
        else:
            rotn_center = center

        angle = -math.radians(angle)
        matrix = [
            round(math.cos(angle), 15),
            round(math.sin(angle), 15),
            0.0,
            round(-math.sin(angle), 15),
            round(math.cos(angle), 15),
            0.0,
        ]

        def transform(x, y, matrix):
            (a, b, c, d, e, f) = matrix
            return a * x + b * y + c, d * x + e * y + f

        matrix[2], matrix[5] = transform(
            -rotn_center[0] - post_trans[0], -rotn_center[1] - post_trans[1], matrix
        )
        matrix[2] += rotn_center[0]
        matrix[5] += rotn_center[1]

        if expand:
            # calculate output size
            xx = []
            yy = []
            for x, y in ((0, 0), (w, 0), (w, h), (0, h)):
                x, y = transform(x, y, matrix)
                xx.append(x)
                yy.append(y)
            nw = math.ceil(max(xx)) - math.floor(min(xx))
            nh = math.ceil(max(yy)) - math.floor(min(yy))

            # We multiply a translation matrix from the right.  Because of its
            # special form, this is the same as taking the image of the
            # translation vector as new translation vector.
            matrix[2], matrix[5] = transform(-(nw - w) / 2.0, -(nh - h) / 2.0, matrix)
            w, h = nw, nh

        return self.transform((w, h), AFFINE, matrix, resample, fillcolor=fillcolor)

    def save(self, fp, format=None, **params):
        """
        Saves this image under the given filename.  If no format is
        specified, the format to use is determined from the filename
        extension, if possible.

        Keyword options can be used to provide additional instructions
        to the writer. If a writer doesn't recognise an option, it is
        silently ignored. The available options are described in the
        :doc:`image format documentation
        <../handbook/image-file-formats>` for each writer.

        You can use a file object instead of a filename. In this case,
        you must always specify the format. The file object must
        implement the ``seek``, ``tell``, and ``write``
        methods, and be opened in binary mode.

        :param fp: A filename (string), pathlib.Path object or file object.
        :param format: Optional format override.  If omitted, the
           format to use is determined from the filename extension.
           If a file object was used instead of a filename, this
           parameter should always be used.
        :param params: Extra parameters to the image writer.
        :returns: None
        :exception ValueError: If the output format could not be determined
           from the file name.  Use the format option to solve this.
        :exception OSError: If the file could not be written.  The file
           may have been created, and may contain partial data.
        """

        filename = ""
        open_fp = False
        if isPath(fp):
            filename = fp
            open_fp = True
        elif isinstance(fp, Path):
            filename = str(fp)
            open_fp = True
        if not filename and hasattr(fp, "name") and isPath(fp.name):
            # only set the name for metadata purposes
            filename = fp.name

        # may mutate self!
        self._ensure_mutable()

        save_all = params.pop("save_all", False)
        self.encoderinfo = params
        self.encoderconfig = ()

        preinit()

        ext = os.path.splitext(filename)[1].lower()

        if not format:
            if ext not in EXTENSION:
                init()
            try:
                format = EXTENSION[ext]
            except KeyError:
                raise ValueError("unknown file extension: {}".format(ext))

        if format.upper() not in SAVE:
            init()
        if save_all:
            save_handler = SAVE_ALL[format.upper()]
        else:
            save_handler = SAVE[format.upper()]

        if open_fp:
            if params.get("append", False):
                # Open also for reading ("+"), because TIFF save_all
                # writer needs to go back and edit the written data.
                fp = builtins.open(filename, "r+b")
            else:
                fp = builtins.open(filename, "w+b")

        try:
            save_handler(self, fp, filename)
        finally:
            # do what we can to clean up
            if open_fp:
                fp.close()

    def seek(self, frame):
        """
        Seeks to the given frame in this sequence file. If you seek
        beyond the end of the sequence, the method raises an
        **EOFError** exception. When a sequence file is opened, the
        library automatically seeks to frame 0.

        See :py:meth:`~PIL.Image.Image.tell`.

        :param frame: Frame number, starting at 0.
        :exception EOFError: If the call attempts to seek beyond the end
            of the sequence.
        """

        # overridden by file handlers
        if frame != 0:
            raise EOFError

    def show(self, title=None, command=None):
        """
        Displays this image. This method is mainly intended for
        debugging purposes.

        The image is first saved to a temporary file. By default, it will be in
        PNG format.

        On Unix, the image is then opened using the **display**, **eog** or
        **xv** utility, depending on which one can be found.

        On macOS, the image is opened with the native Preview application.

        On Windows, the image is opened with the standard PNG display utility.

        :param title: Optional title to use for the image window,
           where possible.
        :param command: command used to show the image
        """

        _show(self, title=title, command=command)

    def split(self):
        """
        Split this image into individual bands. This method returns a
        tuple of individual image bands from an image. For example,
        splitting an "RGB" image creates three new images each
        containing a copy of one of the original bands (red, green,
        blue).

        If you need only one band, :py:meth:`~PIL.Image.Image.getchannel`
        method can be more convenient and faster.

        :returns: A tuple containing bands.
        """

        self.load()
        if self.im.bands == 1:
            ims = [self.copy()]
        else:
            ims = map(self._new, self.im.split())
        return tuple(ims)

    def getchannel(self, channel):
        """
        Returns an image containing a single channel of the source image.

        :param channel: What channel to return. Could be index
          (0 for "R" channel of "RGB") or channel name
          ("A" for alpha channel of "RGBA").
        :returns: An image in "L" mode.

        .. versionadded:: 4.3.0
        """
        self.load()

        if isinstance(channel, str):
            try:
                channel = self.getbands().index(channel)
            except ValueError:
                raise ValueError('The image has no channel "{}"'.format(channel))

        return self._new(self.im.getband(channel))

    def tell(self):
        """
        Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`.

        :returns: Frame number, starting with 0.
        """
        return 0

    def thumbnail(self, size, resample=BICUBIC, reducing_gap=2.0):
        """
        Make this image into a thumbnail.  This method modifies the
        image to contain a thumbnail version of itself, no larger than
        the given size.  This method calculates an appropriate thumbnail
        size to preserve the aspect of the image, calls the
        :py:meth:`~PIL.Image.Image.draft` method to configure the file reader
        (where applicable), and finally resizes the image.

        Note that this function modifies the :py:class:`~PIL.Image.Image`
        object in place.  If you need to use the full resolution image as well,
        apply this method to a :py:meth:`~PIL.Image.Image.copy` of the original
        image.

        :param size: Requested size.
        :param resample: Optional resampling filter.  This can be one
           of :py:attr:`PIL.Image.NEAREST`, :py:attr:`PIL.Image.BILINEAR`,
           :py:attr:`PIL.Image.BICUBIC`, or :py:attr:`PIL.Image.LANCZOS`.
           If omitted, it defaults to :py:attr:`PIL.Image.BICUBIC`.
           (was :py:attr:`PIL.Image.NEAREST` prior to version 2.5.0).
           See: :ref:`concept-filters`.
        :param reducing_gap: Apply optimization by resizing the image
           in two steps. First, reducing the image by integer times
           using :py:meth:`~PIL.Image.Image.reduce` or
           :py:meth:`~PIL.Image.Image.draft` for JPEG images.
           Second, resizing using regular resampling. The last step
           changes size no less than by ``reducing_gap`` times.
           ``reducing_gap`` may be None (no first step is performed)
           or should be greater than 1.0. The bigger ``reducing_gap``,
           the closer the result to the fair resampling.
           The smaller ``reducing_gap``, the faster resizing.
           With ``reducing_gap`` greater or equal to 3.0, the result is
           indistinguishable from fair resampling in most cases.
           The default value is 2.0 (very close to fair resampling
           while still being faster in many cases).
        :returns: None
        """

        x, y = map(math.floor, size)
        if x >= self.width and y >= self.height:
            return

        def round_aspect(number, key):
            return max(min(math.floor(number), math.ceil(number), key=key), 1)

        # preserve aspect ratio
        aspect = self.width / self.height
        if x / y >= aspect:
            x = round_aspect(y * aspect, key=lambda n: abs(aspect - n / y))
        else:
            y = round_aspect(
                x / aspect, key=lambda n: 0 if n == 0 else abs(aspect - x / n)
            )
        size = (x, y)

        box = None
        if reducing_gap is not None:
            res = self.draft(None, (size[0] * reducing_gap, size[1] * reducing_gap))
            if res is not None:
                box = res[1]

        if self.size != size:
            im = self.resize(size, resample, box=box, reducing_gap=reducing_gap)

            self.im = im.im
            self._size = size
            self.mode = self.im.mode

        self.readonly = 0
        self.pyaccess = None

    # FIXME: the different transform methods need further explanation
    # instead of bloating the method docs, add a separate chapter.
    def transform(
        self, size, method, data=None, resample=NEAREST, fill=1, fillcolor=None
    ):
        """
        Transforms this image.  This method creates a new image with the
        given size, and the same mode as the original, and copies data
        to the new image using the given transform.

        :param size: The output size.
        :param method: The transformation method.  This is one of
          :py:attr:`PIL.Image.EXTENT` (cut out a rectangular subregion),
          :py:attr:`PIL.Image.AFFINE` (affine transform),
          :py:attr:`PIL.Image.PERSPECTIVE` (perspective transform),
          :py:attr:`PIL.Image.QUAD` (map a quadrilateral to a rectangle), or
          :py:attr:`PIL.Image.MESH` (map a number of source quadrilaterals
          in one operation).

          It may also be an :py:class:`~PIL.Image.ImageTransformHandler`
          object::

            class Example(Image.ImageTransformHandler):
                def transform(size, method, data, resample, fill=1):
                    # Return result

          It may also be an object with a :py:meth:`~method.getdata` method
          that returns a tuple supplying new **method** and **data** values::

            class Example:
                def getdata(self):
                    method = Image.EXTENT
                    data = (0, 0, 100, 100)
                    return method, data
        :param data: Extra data to the transformation method.
        :param resample: Optional resampling filter.  It can be one of
           :py:attr:`PIL.Image.NEAREST` (use nearest neighbour),
           :py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2
           environment), or :py:attr:`PIL.Image.BICUBIC` (cubic spline
           interpolation in a 4x4 environment). If omitted, or if the image
           has mode "1" or "P", it is set to :py:attr:`PIL.Image.NEAREST`.
           See: :ref:`concept-filters`.
        :param fill: If **method** is an
          :py:class:`~PIL.Image.ImageTransformHandler` object, this is one of
          the arguments passed to it. Otherwise, it is unused.
        :param fillcolor: Optional fill color for the area outside the
           transform in the output image.
        :returns: An :py:class:`~PIL.Image.Image` object.
        """

        if self.mode == "LA":
            return (
                self.convert("La")
                .transform(size, method, data, resample, fill, fillcolor)
                .convert("LA")
            )

        if self.mode == "RGBA":
            return (
                self.convert("RGBa")
                .transform(size, method, data, resample, fill, fillcolor)
                .convert("RGBA")
            )

        if isinstance(method, ImageTransformHandler):
            return method.transform(size, self, resample=resample, fill=fill)

        if hasattr(method, "getdata"):
            # compatibility w. old-style transform objects
            method, data = method.getdata()

        if data is None:
            raise ValueError("missing method data")

        im = new(self.mode, size, fillcolor)
        im.info = self.info.copy()
        if method == MESH:
            # list of quads
            for box, quad in data:
                im.__transformer(box, self, QUAD, quad, resample, fillcolor is None)
        else:
            im.__transformer(
                (0, 0) + size, self, method, data, resample, fillcolor is None
            )

        return im

    def __transformer(self, box, image, method, data, resample=NEAREST, fill=1):
        w = box[2] - box[0]
        h = box[3] - box[1]

        if method == AFFINE:
            data = data[0:6]

        elif method == EXTENT:
            # convert extent to an affine transform
            x0, y0, x1, y1 = data
            xs = (x1 - x0) / w
            ys = (y1 - y0) / h
            method = AFFINE
            data = (xs, 0, x0, 0, ys, y0)

        elif method == PERSPECTIVE:
            data = data[0:8]

        elif method == QUAD:
            # quadrilateral warp.  data specifies the four corners
            # given as NW, SW, SE, and NE.
            nw = data[0:2]
            sw = data[2:4]
            se = data[4:6]
            ne = data[6:8]
            x0, y0 = nw
            As = 1.0 / w
            At = 1.0 / h
            data = (
                x0,
                (ne[0] - x0) * As,
                (sw[0] - x0) * At,
                (se[0] - sw[0] - ne[0] + x0) * As * At,
                y0,
                (ne[1] - y0) * As,
                (sw[1] - y0) * At,
                (se[1] - sw[1] - ne[1] + y0) * As * At,
            )

        else:
            raise ValueError("unknown transformation method")

        if resample not in (NEAREST, BILINEAR, BICUBIC):
            if resample in (BOX, HAMMING, LANCZOS):
                message = {
                    BOX: "Image.BOX",
                    HAMMING: "Image.HAMMING",
                    LANCZOS: "Image.LANCZOS/Image.ANTIALIAS",
                }[resample] + " ({}) cannot be used.".format(resample)
            else:
                message = "Unknown resampling filter ({}).".format(resample)

            filters = [
                "{} ({})".format(filter[1], filter[0])
                for filter in (
                    (NEAREST, "Image.NEAREST"),
                    (BILINEAR, "Image.BILINEAR"),
                    (BICUBIC, "Image.BICUBIC"),
                )
            ]
            raise ValueError(
                message + " Use " + ", ".join(filters[:-1]) + " or " + filters[-1]
            )

        image.load()

        self.load()

        if image.mode in ("1", "P"):
            resample = NEAREST

        self.im.transform2(box, image.im, method, data, resample, fill)

    def transpose(self, method):
        """
        Transpose image (flip or rotate in 90 degree steps)

        :param method: One of :py:attr:`PIL.Image.FLIP_LEFT_RIGHT`,
          :py:attr:`PIL.Image.FLIP_TOP_BOTTOM`, :py:attr:`PIL.Image.ROTATE_90`,
          :py:attr:`PIL.Image.ROTATE_180`, :py:attr:`PIL.Image.ROTATE_270`,
          :py:attr:`PIL.Image.TRANSPOSE` or :py:attr:`PIL.Image.TRANSVERSE`.
        :returns: Returns a flipped or rotated copy of this image.
        """

        self.load()
        return self._new(self.im.transpose(method))

    def effect_spread(self, distance):
        """
        Randomly spread pixels in an image.

        :param distance: Distance to spread pixels.
        """
        self.load()
        return self._new(self.im.effect_spread(distance))

    def toqimage(self):
        """Returns a QImage copy of this image"""
        from . import ImageQt

        if not ImageQt.qt_is_installed:
            raise ImportError("Qt bindings are not installed")
        return ImageQt.toqimage(self)

    def toqpixmap(self):
        """Returns a QPixmap copy of this image"""
        from . import ImageQt

        if not ImageQt.qt_is_installed:
            raise ImportError("Qt bindings are not installed")
        return ImageQt.toqpixmap(self)


# --------------------------------------------------------------------
# Abstract handlers.


class ImagePointHandler:
    # used as a mixin by point transforms (for use with im.point)
    pass


class ImageTransformHandler:
    # used as a mixin by geometry transforms (for use with im.transform)
    pass


# --------------------------------------------------------------------
# Factories

#
# Debugging


def _wedge():
    """Create greyscale wedge (for debugging only)"""

    return Image()._new(core.wedge("L"))


def _check_size(size):
    """
    Common check to enforce type and sanity check on size tuples

    :param size: Should be a 2 tuple of (width, height)
    :returns: True, or raises a ValueError
    """

    if not isinstance(size, (list, tuple)):
        raise ValueError("Size must be a tuple")
    if len(size) != 2:
        raise ValueError("Size must be a tuple of length 2")
    if size[0] < 0 or size[1] < 0:
        raise ValueError("Width and height must be >= 0")

    return True


def new(mode, size, color=0):
    """
    Creates a new image with the given mode and size.

    :param mode: The mode to use for the new image. See:
       :ref:`concept-modes`.
    :param size: A 2-tuple, containing (width, height) in pixels.
    :param color: What color to use for the image.  Default is black.
       If given, this should be a single integer or floating point value
       for single-band modes, and a tuple for multi-band modes (one value
       per band).  When creating RGB images, you can also use color
       strings as supported by the ImageColor module.  If the color is
       None, the image is not initialised.
    :returns: An :py:class:`~PIL.Image.Image` object.
    """

    _check_size(size)

    if color is None:
        # don't initialize
        return Image()._new(core.new(mode, size))

    if isinstance(color, str):
        # css3-style specifier

        from . import ImageColor

        color = ImageColor.getcolor(color, mode)

    im = Image()
    if mode == "P" and isinstance(color, (list, tuple)) and len(color) in [3, 4]:
        # RGB or RGBA value for a P image
        from . import ImagePalette

        im.palette = ImagePalette.ImagePalette()
        color = im.palette.getcolor(color)
    return im._new(core.fill(mode, size, color))


def frombytes(mode, size, data, decoder_name="raw", *args):
    """
    Creates a copy of an image memory from pixel data in a buffer.

    In its simplest form, this function takes three arguments
    (mode, size, and unpacked pixel data).

    You can also use any pixel decoder supported by PIL.  For more
    information on available decoders, see the section
    :ref:`Writing Your Own File Decoder <file-decoders>`.

    Note that this function decodes pixel data only, not entire images.
    If you have an entire image in a string, wrap it in a
    :py:class:`~io.BytesIO` object, and use :py:func:`~PIL.Image.open` to load
    it.

    :param mode: The image mode. See: :ref:`concept-modes`.
    :param size: The image size.
    :param data: A byte buffer containing raw data for the given mode.
    :param decoder_name: What decoder to use.
    :param args: Additional parameters for the given decoder.
    :returns: An :py:class:`~PIL.Image.Image` object.
    """

    _check_size(size)

    # may pass tuple instead of argument list
    if len(args) == 1 and isinstance(args[0], tuple):
        args = args[0]

    if decoder_name == "raw" and args == ():
        args = mode

    im = new(mode, size)
    im.frombytes(data, decoder_name, args)
    return im


def fromstring(*args, **kw):
    raise NotImplementedError(
        "fromstring() has been removed. Please call frombytes() instead."
    )


def frombuffer(mode, size, data, decoder_name="raw", *args):
    """
    Creates an image memory referencing pixel data in a byte buffer.

    This function is similar to :py:func:`~PIL.Image.frombytes`, but uses data
    in the byte buffer, where possible.  This means that changes to the
    original buffer object are reflected in this image).  Not all modes can
    share memory; supported modes include "L", "RGBX", "RGBA", and "CMYK".

    Note that this function decodes pixel data only, not entire images.
    If you have an entire image file in a string, wrap it in a
    **BytesIO** object, and use :py:func:`~PIL.Image.open` to load it.

    In the current version, the default parameters used for the "raw" decoder
    differs from that used for :py:func:`~PIL.Image.frombytes`.  This is a
    bug, and will probably be fixed in a future release.  The current release
    issues a warning if you do this; to disable the warning, you should provide
    the full set of parameters.  See below for details.

    :param mode: The image mode. See: :ref:`concept-modes`.
    :param size: The image size.
    :param data: A bytes or other buffer object containing raw
        data for the given mode.
    :param decoder_name: What decoder to use.
    :param args: Additional parameters for the given decoder.  For the
        default encoder ("raw"), it's recommended that you provide the
        full set of parameters::

            frombuffer(mode, size, data, "raw", mode, 0, 1)

    :returns: An :py:class:`~PIL.Image.Image` object.

    .. versionadded:: 1.1.4
    """

    _check_size(size)

    # may pass tuple instead of argument list
    if len(args) == 1 and isinstance(args[0], tuple):
        args = args[0]

    if decoder_name == "raw":
        if args == ():
            args = mode, 0, 1
        if args[0] in _MAPMODES:
            im = new(mode, (1, 1))
            im = im._new(core.map_buffer(data, size, decoder_name, 0, args))
            im.readonly = 1
            return im

    return frombytes(mode, size, data, decoder_name, args)


def fromarray(obj, mode=None):
    """
    Creates an image memory from an object exporting the array interface
    (using the buffer protocol).

    If **obj** is not contiguous, then the tobytes method is called
    and :py:func:`~PIL.Image.frombuffer` is used.

    If you have an image in NumPy::

      from PIL import Image
      import numpy as np
      im = Image.open('hopper.jpg')
      a = np.asarray(im)

    Then this can be used to convert it to a Pillow image::

      im = Image.fromarray(a)

    :param obj: Object with array interface
    :param mode: Mode to use (will be determined from type if None)
      See: :ref:`concept-modes`.
    :returns: An image object.

    .. versionadded:: 1.1.6
    """
    arr = obj.__array_interface__
    shape = arr["shape"]
    ndim = len(shape)
    strides = arr.get("strides", None)
    if mode is None:
        try:
            typekey = (1, 1) + shape[2:], arr["typestr"]
        except KeyError:
            raise TypeError("Cannot handle this data type")
        try:
            mode, rawmode = _fromarray_typemap[typekey]
        except KeyError:
            raise TypeError("Cannot handle this data type: %s, %s" % typekey)
    else:
        rawmode = mode
    if mode in ["1", "L", "I", "P", "F"]:
        ndmax = 2
    elif mode == "RGB":
        ndmax = 3
    else:
        ndmax = 4
    if ndim > ndmax:
        raise ValueError("Too many dimensions: %d > %d." % (ndim, ndmax))

    size = 1 if ndim == 1 else shape[1], shape[0]
    if strides is not None:
        if hasattr(obj, "tobytes"):
            obj = obj.tobytes()
        else:
            obj = obj.tostring()

    return frombuffer(mode, size, obj, "raw", rawmode, 0, 1)


def fromqimage(im):
    """Creates an image instance from a QImage image"""
    from . import ImageQt

    if not ImageQt.qt_is_installed:
        raise ImportError("Qt bindings are not installed")
    return ImageQt.fromqimage(im)


def fromqpixmap(im):
    """Creates an image instance from a QPixmap image"""
    from . import ImageQt

    if not ImageQt.qt_is_installed:
        raise ImportError("Qt bindings are not installed")
    return ImageQt.fromqpixmap(im)


_fromarray_typemap = {
    # (shape, typestr) => mode, rawmode
    # first two members of shape are set to one
    ((1, 1), "|b1"): ("1", "1;8"),
    ((1, 1), "|u1"): ("L", "L"),
    ((1, 1), "|i1"): ("I", "I;8"),
    ((1, 1), "<u2"): ("I", "I;16"),
    ((1, 1), ">u2"): ("I", "I;16B"),
    ((1, 1), "<i2"): ("I", "I;16S"),
    ((1, 1), ">i2"): ("I", "I;16BS"),
    ((1, 1), "<u4"): ("I", "I;32"),
    ((1, 1), ">u4"): ("I", "I;32B"),
    ((1, 1), "<i4"): ("I", "I;32S"),
    ((1, 1), ">i4"): ("I", "I;32BS"),
    ((1, 1), "<f4"): ("F", "F;32F"),
    ((1, 1), ">f4"): ("F", "F;32BF"),
    ((1, 1), "<f8"): ("F", "F;64F"),
    ((1, 1), ">f8"): ("F", "F;64BF"),
    ((1, 1, 2), "|u1"): ("LA", "LA"),
    ((1, 1, 3), "|u1"): ("RGB", "RGB"),
    ((1, 1, 4), "|u1"): ("RGBA", "RGBA"),
}

# shortcuts
_fromarray_typemap[((1, 1), _ENDIAN + "i4")] = ("I", "I")
_fromarray_typemap[((1, 1), _ENDIAN + "f4")] = ("F", "F")


def _decompression_bomb_check(size):
    if MAX_IMAGE_PIXELS is None:
        return

    pixels = size[0] * size[1]

    if pixels > 2 * MAX_IMAGE_PIXELS:
        raise DecompressionBombError(
            "Image size (%d pixels) exceeds limit of %d pixels, "
            "could be decompression bomb DOS attack." % (pixels, 2 * MAX_IMAGE_PIXELS)
        )

    if pixels > MAX_IMAGE_PIXELS:
        warnings.warn(
            "Image size (%d pixels) exceeds limit of %d pixels, "
            "could be decompression bomb DOS attack." % (pixels, MAX_IMAGE_PIXELS),
            DecompressionBombWarning,
        )


def open(fp, mode="r"):
    """
    Opens and identifies the given image file.

    This is a lazy operation; this function identifies the file, but
    the file remains open and the actual image data is not read from
    the file until you try to process the data (or call the
    :py:meth:`~PIL.Image.Image.load` method).  See
    :py:func:`~PIL.Image.new`. See :ref:`file-handling`.

    :param fp: A filename (string), pathlib.Path object or a file object.
       The file object must implement :py:meth:`~file.read`,
       :py:meth:`~file.seek`, and :py:meth:`~file.tell` methods,
       and be opened in binary mode.
    :param mode: The mode.  If given, this argument must be "r".
    :returns: An :py:class:`~PIL.Image.Image` object.
    :exception FileNotFoundError: If the file cannot be found.
    :exception PIL.UnidentifiedImageError: If the image cannot be opened and
       identified.
    :exception ValueError: If the ``mode`` is not "r", or if a ``StringIO``
       instance is used for ``fp``.
    """

    if mode != "r":
        raise ValueError("bad mode %r" % mode)
    elif isinstance(fp, io.StringIO):
        raise ValueError(
            "StringIO cannot be used to open an image. "
            "Binary data must be used instead."
        )

    exclusive_fp = False
    filename = ""
    if isinstance(fp, Path):
        filename = str(fp.resolve())
    elif isPath(fp):
        filename = fp

    if filename:
        fp = builtins.open(filename, "rb")
        exclusive_fp = True

    try:
        fp.seek(0)
    except (AttributeError, io.UnsupportedOperation):
        fp = io.BytesIO(fp.read())
        exclusive_fp = True

    prefix = fp.read(16)

    preinit()

    accept_warnings = []

    def _open_core(fp, filename, prefix):
        for i in ID:
            try:
                factory, accept = OPEN[i]
                result = not accept or accept(prefix)
                if type(result) in [str, bytes]:
                    accept_warnings.append(result)
                elif result:
                    fp.seek(0)
                    im = factory(fp, filename)
                    _decompression_bomb_check(im.size)
                    return im
            except (SyntaxError, IndexError, TypeError, struct.error):
                # Leave disabled by default, spams the logs with image
                # opening failures that are entirely expected.
                # logger.debug("", exc_info=True)
                continue
            except BaseException:
                if exclusive_fp:
                    fp.close()
                raise
        return None

    im = _open_core(fp, filename, prefix)

    if im is None:
        if init():
            im = _open_core(fp, filename, prefix)

    if im:
        im._exclusive_fp = exclusive_fp
        return im

    if exclusive_fp:
        fp.close()
    for message in accept_warnings:
        warnings.warn(message)
    raise UnidentifiedImageError(
        "cannot identify image file %r" % (filename if filename else fp)
    )


#
# Image processing.


def alpha_composite(im1, im2):
    """
    Alpha composite im2 over im1.

    :param im1: The first image. Must have mode RGBA.
    :param im2: The second image.  Must have mode RGBA, and the same size as
       the first image.
    :returns: An :py:class:`~PIL.Image.Image` object.
    """

    im1.load()
    im2.load()
    return im1._new(core.alpha_composite(im1.im, im2.im))


def blend(im1, im2, alpha):
    """
    Creates a new image by interpolating between two input images, using
    a constant alpha.::

        out = image1 * (1.0 - alpha) + image2 * alpha

    :param im1: The first image.
    :param im2: The second image.  Must have the same mode and size as
       the first image.
    :param alpha: The interpolation alpha factor.  If alpha is 0.0, a
       copy of the first image is returned. If alpha is 1.0, a copy of
       the second image is returned. There are no restrictions on the
       alpha value. If necessary, the result is clipped to fit into
       the allowed output range.
    :returns: An :py:class:`~PIL.Image.Image` object.
    """

    im1.load()
    im2.load()
    return im1._new(core.blend(im1.im, im2.im, alpha))


def composite(image1, image2, mask):
    """
    Create composite image by blending images using a transparency mask.

    :param image1: The first image.
    :param image2: The second image.  Must have the same mode and
       size as the first image.
    :param mask: A mask image.  This image can have mode
       "1", "L", or "RGBA", and must have the same size as the
       other two images.
    """

    image = image2.copy()
    image.paste(image1, None, mask)
    return image


def eval(image, *args):
    """
    Applies the function (which should take one argument) to each pixel
    in the given image. If the image has more than one band, the same
    function is applied to each band. Note that the function is
    evaluated once for each possible pixel value, so you cannot use
    random components or other generators.

    :param image: The input image.
    :param function: A function object, taking one integer argument.
    :returns: An :py:class:`~PIL.Image.Image` object.
    """

    return image.point(args[0])


def merge(mode, bands):
    """
    Merge a set of single band images into a new multiband image.

    :param mode: The mode to use for the output image. See:
        :ref:`concept-modes`.
    :param bands: A sequence containing one single-band image for
        each band in the output image.  All bands must have the
        same size.
    :returns: An :py:class:`~PIL.Image.Image` object.
    """

    if getmodebands(mode) != len(bands) or "*" in mode:
        raise ValueError("wrong number of bands")
    for band in bands[1:]:
        if band.mode != getmodetype(mode):
            raise ValueError("mode mismatch")
        if band.size != bands[0].size:
            raise ValueError("size mismatch")
    for band in bands:
        band.load()
    return bands[0]._new(core.merge(mode, *[b.im for b in bands]))


# --------------------------------------------------------------------
# Plugin registry


def register_open(id, factory, accept=None):
    """
    Register an image file plugin.  This function should not be used
    in application code.

    :param id: An image format identifier.
    :param factory: An image file factory method.
    :param accept: An optional function that can be used to quickly
       reject images having another format.
    """
    id = id.upper()
    ID.append(id)
    OPEN[id] = factory, accept


def register_mime(id, mimetype):
    """
    Registers an image MIME type.  This function should not be used
    in application code.

    :param id: An image format identifier.
    :param mimetype: The image MIME type for this format.
    """
    MIME[id.upper()] = mimetype


def register_save(id, driver):
    """
    Registers an image save function.  This function should not be
    used in application code.

    :param id: An image format identifier.
    :param driver: A function to save images in this format.
    """
    SAVE[id.upper()] = driver


def register_save_all(id, driver):
    """
    Registers an image function to save all the frames
    of a multiframe format.  This function should not be
    used in application code.

    :param id: An image format identifier.
    :param driver: A function to save images in this format.
    """
    SAVE_ALL[id.upper()] = driver


def register_extension(id, extension):
    """
    Registers an image extension.  This function should not be
    used in application code.

    :param id: An image format identifier.
    :param extension: An extension used for this format.
    """
    EXTENSION[extension.lower()] = id.upper()


def register_extensions(id, extensions):
    """
    Registers image extensions.  This function should not be
    used in application code.

    :param id: An image format identifier.
    :param extensions: A list of extensions used for this format.
    """
    for extension in extensions:
        register_extension(id, extension)


def registered_extensions():
    """
    Returns a dictionary containing all file extensions belonging
    to registered plugins
    """
    if not EXTENSION:
        init()
    return EXTENSION


def register_decoder(name, decoder):
    """
    Registers an image decoder.  This function should not be
    used in application code.

    :param name: The name of the decoder
    :param decoder: A callable(mode, args) that returns an
                    ImageFile.PyDecoder object

    .. versionadded:: 4.1.0
    """
    DECODERS[name] = decoder


def register_encoder(name, encoder):
    """
    Registers an image encoder.  This function should not be
    used in application code.

    :param name: The name of the encoder
    :param encoder: A callable(mode, args) that returns an
                    ImageFile.PyEncoder object

    .. versionadded:: 4.1.0
    """
    ENCODERS[name] = encoder


# --------------------------------------------------------------------
# Simple display support.  User code may override this.


def _show(image, **options):
    # override me, as necessary
    _showxv(image, **options)


def _showxv(image, title=None, **options):
    from . import ImageShow

    ImageShow.show(image, title, **options)


# --------------------------------------------------------------------
# Effects


def effect_mandelbrot(size, extent, quality):
    """
    Generate a Mandelbrot set covering the given extent.

    :param size: The requested size in pixels, as a 2-tuple:
       (width, height).
    :param extent: The extent to cover, as a 4-tuple:
       (x0, y0, x1, y2).
    :param quality: Quality.
    """
    return Image()._new(core.effect_mandelbrot(size, extent, quality))


def effect_noise(size, sigma):
    """
    Generate Gaussian noise centered around 128.

    :param size: The requested size in pixels, as a 2-tuple:
       (width, height).
    :param sigma: Standard deviation of noise.
    """
    return Image()._new(core.effect_noise(size, sigma))


def linear_gradient(mode):
    """
    Generate 256x256 linear gradient from black to white, top to bottom.

    :param mode: Input mode.
    """
    return Image()._new(core.linear_gradient(mode))


def radial_gradient(mode):
    """
    Generate 256x256 radial gradient from black to white, centre to edge.

    :param mode: Input mode.
    """
    return Image()._new(core.radial_gradient(mode))


# --------------------------------------------------------------------
# Resources


def _apply_env_variables(env=None):
    if env is None:
        env = os.environ

    for var_name, setter in [
        ("PILLOW_ALIGNMENT", core.set_alignment),
        ("PILLOW_BLOCK_SIZE", core.set_block_size),
        ("PILLOW_BLOCKS_MAX", core.set_blocks_max),
    ]:
        if var_name not in env:
            continue

        var = env[var_name].lower()

        units = 1
        for postfix, mul in [("k", 1024), ("m", 1024 * 1024)]:
            if var.endswith(postfix):
                units = mul
                var = var[: -len(postfix)]

        try:
            var = int(var) * units
        except ValueError:
            warnings.warn("{} is not int".format(var_name))
            continue

        try:
            setter(var)
        except ValueError as e:
            warnings.warn("{}: {}".format(var_name, e))


_apply_env_variables()
atexit.register(core.clear_cache)


class Exif(MutableMapping):
    endian = "<"

    def __init__(self):
        self._data = {}
        self._ifds = {}
        self._info = None
        self._loaded_exif = None

    def _fixup(self, value):
        try:
            if len(value) == 1 and not isinstance(value, dict):
                return value[0]
        except Exception:
            pass
        return value

    def _fixup_dict(self, src_dict):
        # Helper function for _getexif()
        # returns a dict with any single item tuples/lists as individual values
        return {k: self._fixup(v) for k, v in src_dict.items()}

    def _get_ifd_dict(self, tag):
        try:
            # an offset pointer to the location of the nested embedded IFD.
            # It should be a long, but may be corrupted.
            self.fp.seek(self[tag])
        except (KeyError, TypeError):
            pass
        else:
            from . import TiffImagePlugin

            info = TiffImagePlugin.ImageFileDirectory_v1(self.head)
            info.load(self.fp)
            return self._fixup_dict(info)

    def load(self, data):
        # Extract EXIF information.  This is highly experimental,
        # and is likely to be replaced with something better in a future
        # version.

        # The EXIF record consists of a TIFF file embedded in a JPEG
        # application marker (!).
        if data == self._loaded_exif:
            return
        self._loaded_exif = data
        self._data.clear()
        self._ifds.clear()
        self._info = None
        if not data:
            return

        if data.startswith(b"Exif\x00\x00"):
            data = data[6:]
        self.fp = io.BytesIO(data)
        self.head = self.fp.read(8)
        # process dictionary
        from . import TiffImagePlugin

        self._info = TiffImagePlugin.ImageFileDirectory_v1(self.head)
        self.endian = self._info._endian
        self.fp.seek(self._info.next)
        self._info.load(self.fp)

        # get EXIF extension
        ifd = self._get_ifd_dict(0x8769)
        if ifd:
            self._data.update(ifd)
            self._ifds[0x8769] = ifd

    def tobytes(self, offset=8):
        from . import TiffImagePlugin

        if self.endian == "<":
            head = b"II\x2A\x00\x08\x00\x00\x00"
        else:
            head = b"MM\x00\x2A\x00\x00\x00\x08"
        ifd = TiffImagePlugin.ImageFileDirectory_v2(ifh=head)
        for tag, value in self.items():
            ifd[tag] = value
        return b"Exif\x00\x00" + head + ifd.tobytes(offset)

    def get_ifd(self, tag):
        if tag not in self._ifds and tag in self:
            if tag in [0x8825, 0xA005]:
                # gpsinfo, interop
                self._ifds[tag] = self._get_ifd_dict(tag)
            elif tag == 0x927C:  # makernote
                from .TiffImagePlugin import ImageFileDirectory_v2

                if self[0x927C][:8] == b"FUJIFILM":
                    exif_data = self[0x927C]
                    ifd_offset = i32le(exif_data[8:12])
                    ifd_data = exif_data[ifd_offset:]

                    makernote = {}
                    for i in range(0, struct.unpack("<H", ifd_data[:2])[0]):
                        ifd_tag, typ, count, data = struct.unpack(
                            "<HHL4s", ifd_data[i * 12 + 2 : (i + 1) * 12 + 2]
                        )
                        try:
                            unit_size, handler = ImageFileDirectory_v2._load_dispatch[
                                typ
                            ]
                        except KeyError:
                            continue
                        size = count * unit_size
                        if size > 4:
                            (offset,) = struct.unpack("<L", data)
                            data = ifd_data[offset - 12 : offset + size - 12]
                        else:
                            data = data[:size]

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

                        if not data:
                            continue

                        makernote[ifd_tag] = handler(
                            ImageFileDirectory_v2(), data, False
                        )
                    self._ifds[0x927C] = dict(self._fixup_dict(makernote))
                elif self.get(0x010F) == "Nintendo":
                    ifd_data = self[0x927C]

                    makernote = {}
                    for i in range(0, struct.unpack(">H", ifd_data[:2])[0]):
                        ifd_tag, typ, count, data = struct.unpack(
                            ">HHL4s", ifd_data[i * 12 + 2 : (i + 1) * 12 + 2]
                        )
                        if ifd_tag == 0x1101:
                            # CameraInfo
                            (offset,) = struct.unpack(">L", data)
                            self.fp.seek(offset)

                            camerainfo = {"ModelID": self.fp.read(4)}

                            self.fp.read(4)
                            # Seconds since 2000
                            camerainfo["TimeStamp"] = i32le(self.fp.read(12))

                            self.fp.read(4)
                            camerainfo["InternalSerialNumber"] = self.fp.read(4)

                            self.fp.read(12)
                            parallax = self.fp.read(4)
                            handler = ImageFileDirectory_v2._load_dispatch[
                                TiffTags.FLOAT
                            ][1]
                            camerainfo["Parallax"] = handler(
                                ImageFileDirectory_v2(), parallax, False
                            )

                            self.fp.read(4)
                            camerainfo["Category"] = self.fp.read(2)

                            makernote = {0x1101: dict(self._fixup_dict(camerainfo))}
                    self._ifds[0x927C] = makernote
        return self._ifds.get(tag, {})

    def __str__(self):
        if self._info is not None:
            # Load all keys into self._data
            for tag in self._info.keys():
                self[tag]

        return str(self._data)

    def __len__(self):
        keys = set(self._data)
        if self._info is not None:
            keys.update(self._info)
        return len(keys)

    def __getitem__(self, tag):
        if self._info is not None and tag not in self._data and tag in self._info:
            self._data[tag] = self._fixup(self._info[tag])
            if tag == 0x8825:
                self._data[tag] = self.get_ifd(tag)
            del self._info[tag]
        return self._data[tag]

    def __contains__(self, tag):
        return tag in self._data or (self._info is not None and tag in self._info)

    def __setitem__(self, tag, value):
        if self._info is not None and tag in self._info:
            del self._info[tag]
        self._data[tag] = value

    def __delitem__(self, tag):
        if self._info is not None and tag in self._info:
            del self._info[tag]
        del self._data[tag]

    def __iter__(self):
        keys = set(self._data)
        if self._info is not None:
            keys.update(self._info)
        return iter(keys)

```
--- 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