{
    "file_diffs": [
        {
            "old_file_content": "from __future__ import annotations\n\nimport io\nimport os\nimport warnings\nfrom pathlib import Path\n\nimport pytest\n\nfrom PIL import IcnsImagePlugin, Image, _binary\n\nfrom .helper import assert_image_equal, assert_image_similar_tofile, skip_unless_feature\n\n# sample icon file\nTEST_FILE = \"Tests/images/pillow.icns\"\n\n\ndef test_sanity() -> None:\n    # Loading this icon by default should result in the largest size\n    # (512x512@2x) being loaded\n    with Image.open(TEST_FILE) as im:\n        # Assert that there is no unclosed file warning\n        with warnings.catch_warnings():\n            im.load()\n\n        assert im.mode == \"RGBA\"\n        assert im.size == (1024, 1024)\n        assert im.format == \"ICNS\"\n\n\ndef test_load() -> None:\n    with Image.open(TEST_FILE) as im:\n        assert im.load()[0, 0] == (0, 0, 0, 0)\n\n        # Test again now that it has already been loaded once\n        assert im.load()[0, 0] == (0, 0, 0, 0)\n\n\ndef test_save(tmp_path: Path) -> None:\n    temp_file = str(tmp_path / \"temp.icns\")\n\n    with Image.open(TEST_FILE) as im:\n        im.save(temp_file)\n\n    with Image.open(temp_file) as reread:\n        assert reread.mode == \"RGBA\"\n        assert reread.size == (1024, 1024)\n        assert reread.format == \"ICNS\"\n\n    file_length = os.path.getsize(temp_file)\n    with open(temp_file, \"rb\") as fp:\n        fp.seek(4)\n        assert _binary.i32be(fp.read(4)) == file_length\n\n\ndef test_save_append_images(tmp_path: Path) -> None:\n    temp_file = str(tmp_path / \"temp.icns\")\n    provided_im = Image.new(\"RGBA\", (32, 32), (255, 0, 0, 128))\n\n    with Image.open(TEST_FILE) as im:\n        im.save(temp_file, append_images=[provided_im])\n\n        assert_image_similar_tofile(im, temp_file, 1)\n\n        with Image.open(temp_file) as reread:\n            reread.size = (16, 16, 2)\n            reread.load()\n            assert_image_equal(reread, provided_im)\n\n\ndef test_save_fp() -> None:\n    fp = io.BytesIO()\n\n    with Image.open(TEST_FILE) as im:\n        im.save(fp, format=\"ICNS\")\n\n    with Image.open(fp) as reread:\n        assert reread.mode == \"RGBA\"\n        assert reread.size == (1024, 1024)\n        assert reread.format == \"ICNS\"\n\n\ndef test_sizes() -> None:\n    # Check that we can load all of the sizes, and that the final pixel\n    # dimensions are as expected\n    with Image.open(TEST_FILE) as im:\n        for w, h, r in im.info[\"sizes\"]:\n            wr = w * r\n            hr = h * r\n            im.size = (w, h, r)\n            im.load()\n            assert im.mode == \"RGBA\"\n            assert im.size == (wr, hr)\n\n        # Check that we cannot load an incorrect size\n        with pytest.raises(ValueError):\n            im.size = (1, 1)\n\n\ndef test_older_icon() -> None:\n    # This icon was made with Icon Composer rather than iconutil; it still\n    # uses PNG rather than JP2, however (since it was made on 10.9).\n    with Image.open(\"Tests/images/pillow2.icns\") as im:\n        for w, h, r in im.info[\"sizes\"]:\n            wr = w * r\n            hr = h * r\n            with Image.open(\"Tests/images/pillow2.icns\") as im2:\n                im2.size = (w, h, r)\n                im2.load()\n                assert im2.mode == \"RGBA\"\n                assert im2.size == (wr, hr)\n\n\n@skip_unless_feature(\"jpg_2000\")\ndef test_jp2_icon() -> None:\n    # This icon uses JPEG 2000 images instead of the PNG images.\n    # The advantage of doing this is that OS X 10.5 supports JPEG 2000\n    # but not PNG; some commercial software therefore does just this.\n\n    with Image.open(\"Tests/images/pillow3.icns\") as im:\n        for w, h, r in im.info[\"sizes\"]:\n            wr = w * r\n            hr = h * r\n            with Image.open(\"Tests/images/pillow3.icns\") as im2:\n                im2.size = (w, h, r)\n                im2.load()\n                assert im2.mode == \"RGBA\"\n                assert im2.size == (wr, hr)\n\n\ndef test_getimage() -> None:\n    with open(TEST_FILE, \"rb\") as fp:\n        icns_file = IcnsImagePlugin.IcnsFile(fp)\n\n        im = icns_file.getimage()\n        assert im.mode == \"RGBA\"\n        assert im.size == (1024, 1024)\n\n        im = icns_file.getimage((512, 512))\n        assert im.mode == \"RGBA\"\n        assert im.size == (512, 512)\n\n\ndef test_not_an_icns_file() -> None:\n    with io.BytesIO(b\"invalid\\n\") as fp:\n        with pytest.raises(SyntaxError):\n            IcnsImagePlugin.IcnsFile(fp)\n\n\n@skip_unless_feature(\"jpg_2000\")\ndef test_icns_decompression_bomb() -> None:\n    with Image.open(\n        \"Tests/images/oom-8ed3316a4109213ca96fb8a256a0bfefdece1461.icns\"\n    ) as im:\n        with pytest.raises(Image.DecompressionBombError):\n            im.load()\n",
            "new_file_content": "from __future__ import annotations\n\nimport io\nimport os\nimport warnings\nfrom pathlib import Path\n\nimport pytest\n\nfrom PIL import IcnsImagePlugin, Image, _binary\n\nfrom .helper import assert_image_equal, assert_image_similar_tofile, skip_unless_feature\n\n# sample icon file\nTEST_FILE = \"Tests/images/pillow.icns\"\n\n\ndef test_sanity() -> None:\n    # Loading this icon by default should result in the largest size\n    # (512x512@2x) being loaded\n    with Image.open(TEST_FILE) as im:\n        # Assert that there is no unclosed file warning\n        with warnings.catch_warnings():\n            im.load()\n\n        assert im.mode == \"RGBA\"\n        assert im.size == (1024, 1024)\n        assert im.format == \"ICNS\"\n\n\ndef test_load() -> None:\n    with Image.open(TEST_FILE) as im:\n        assert im.load()[0, 0] == (0, 0, 0, 0)\n\n        # Test again now that it has already been loaded once\n        assert im.load()[0, 0] == (0, 0, 0, 0)\n\n\ndef test_save(tmp_path: Path) -> None:\n    temp_file = str(tmp_path / \"temp.icns\")\n\n    with Image.open(TEST_FILE) as im:\n        im.save(temp_file)\n\n    with Image.open(temp_file) as reread:\n        assert reread.mode == \"RGBA\"\n        assert reread.size == (1024, 1024)\n        assert reread.format == \"ICNS\"\n\n    file_length = os.path.getsize(temp_file)\n    with open(temp_file, \"rb\") as fp:\n        fp.seek(4)\n        assert _binary.i32be(fp.read(4)) == file_length\n\n\ndef test_save_append_images(tmp_path: Path) -> None:\n    temp_file = str(tmp_path / \"temp.icns\")\n    provided_im = Image.new(\"RGBA\", (32, 32), (255, 0, 0, 128))\n\n    with Image.open(TEST_FILE) as im:\n        im.save(temp_file, append_images=[provided_im])\n\n        assert_image_similar_tofile(im, temp_file, 1)\n\n        with Image.open(temp_file) as reread:\n            reread.size = (16, 16)\n            reread.load(2)\n            assert_image_equal(reread, provided_im)\n\n\ndef test_save_fp() -> None:\n    fp = io.BytesIO()\n\n    with Image.open(TEST_FILE) as im:\n        im.save(fp, format=\"ICNS\")\n\n    with Image.open(fp) as reread:\n        assert reread.mode == \"RGBA\"\n        assert reread.size == (1024, 1024)\n        assert reread.format == \"ICNS\"\n\n\ndef test_sizes() -> None:\n    # Check that we can load all of the sizes, and that the final pixel\n    # dimensions are as expected\n    with Image.open(TEST_FILE) as im:\n        for w, h, r in im.info[\"sizes\"]:\n            wr = w * r\n            hr = h * r\n            im.size = (w, h, r)\n            im.load()\n            assert im.mode == \"RGBA\"\n            assert im.size == (wr, hr)\n\n            # Test using load() with scale\n            im.size = (w, h)\n            im.load(scale=r)\n            assert im.mode == \"RGBA\"\n            assert im.size == (wr, hr)\n\n        # Check that we cannot load an incorrect size\n        with pytest.raises(ValueError):\n            im.size = (1, 2)\n\n\ndef test_older_icon() -> None:\n    # This icon was made with Icon Composer rather than iconutil; it still\n    # uses PNG rather than JP2, however (since it was made on 10.9).\n    with Image.open(\"Tests/images/pillow2.icns\") as im:\n        for w, h, r in im.info[\"sizes\"]:\n            wr = w * r\n            hr = h * r\n            with Image.open(\"Tests/images/pillow2.icns\") as im2:\n                im2.size = (w, h)\n                im2.load(r)\n                assert im2.mode == \"RGBA\"\n                assert im2.size == (wr, hr)\n\n\n@skip_unless_feature(\"jpg_2000\")\ndef test_jp2_icon() -> None:\n    # This icon uses JPEG 2000 images instead of the PNG images.\n    # The advantage of doing this is that OS X 10.5 supports JPEG 2000\n    # but not PNG; some commercial software therefore does just this.\n\n    with Image.open(\"Tests/images/pillow3.icns\") as im:\n        for w, h, r in im.info[\"sizes\"]:\n            wr = w * r\n            hr = h * r\n            with Image.open(\"Tests/images/pillow3.icns\") as im2:\n                im2.size = (w, h)\n                im2.load(r)\n                assert im2.mode == \"RGBA\"\n                assert im2.size == (wr, hr)\n\n\ndef test_getimage() -> None:\n    with open(TEST_FILE, \"rb\") as fp:\n        icns_file = IcnsImagePlugin.IcnsFile(fp)\n\n        im = icns_file.getimage()\n        assert im.mode == \"RGBA\"\n        assert im.size == (1024, 1024)\n\n        im = icns_file.getimage((512, 512))\n        assert im.mode == \"RGBA\"\n        assert im.size == (512, 512)\n\n\ndef test_not_an_icns_file() -> None:\n    with io.BytesIO(b\"invalid\\n\") as fp:\n        with pytest.raises(SyntaxError):\n            IcnsImagePlugin.IcnsFile(fp)\n\n\n@skip_unless_feature(\"jpg_2000\")\ndef test_icns_decompression_bomb() -> None:\n    with Image.open(\n        \"Tests/images/oom-8ed3316a4109213ca96fb8a256a0bfefdece1461.icns\"\n    ) as im:\n        with pytest.raises(Image.DecompressionBombError):\n            im.load()\n",
            "header": {
                "file": {
                    "path": "Tests/test_file_icns.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "488984aef",
                "new_commit_hash": "f37a6996f",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/Tests/test_file_icns.py"
            },
            "plus_file": {
                "path": "b/Tests/test_file_icns.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 63,
                            "length": 8
                        },
                        "new_range": {
                            "start": 63,
                            "length": 8
                        },
                        "section": "def test_save_append_images(tmp_path: Path) -> None:"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        assert_image_similar_tofile(im, temp_file, 1)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        with Image.open(temp_file) as reread:",
                                "type": "context"
                            },
                            {
                                "content": "            reread.size = (16, 16, 2)",
                                "type": "deleted"
                            },
                            {
                                "content": "            reread.load()",
                                "type": "deleted"
                            },
                            {
                                "content": "            reread.size = (16, 16)",
                                "type": "added"
                            },
                            {
                                "content": "            reread.load(2)",
                                "type": "added"
                            },
                            {
                                "content": "            assert_image_equal(reread, provided_im)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Tests/test_file_icns.py",
                            "type": "function",
                            "name": "test_save_append_images",
                            "content": "def test_save_append_images(tmp_path: Path) -> None:\n    temp_file = str(tmp_path / \"temp.icns\")\n    provided_im = Image.new(\"RGBA\", (32, 32), (255, 0, 0, 128))\n\n    with Image.open(TEST_FILE) as im:\n        im.save(temp_file, append_images=[provided_im])\n\n        assert_image_similar_tofile(im, temp_file, 1)\n\n        with Image.open(temp_file) as reread:\n            reread.size = (16, 16, 2)\n            reread.load()\n            assert_image_equal(reread, provided_im)",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 56,
                            "end_lineno": 68,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 92,
                            "length": 9
                        },
                        "new_range": {
                            "start": 92,
                            "length": 15
                        },
                        "section": "def test_sizes() -> None:"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "            assert im.mode == \"RGBA\"",
                                "type": "context"
                            },
                            {
                                "content": "            assert im.size == (wr, hr)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "            # Test using load() with scale",
                                "type": "added"
                            },
                            {
                                "content": "            im.size = (w, h)",
                                "type": "added"
                            },
                            {
                                "content": "            im.load(scale=r)",
                                "type": "added"
                            },
                            {
                                "content": "            assert im.mode == \"RGBA\"",
                                "type": "added"
                            },
                            {
                                "content": "            assert im.size == (wr, hr)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        # Check that we cannot load an incorrect size",
                                "type": "context"
                            },
                            {
                                "content": "        with pytest.raises(ValueError):",
                                "type": "context"
                            },
                            {
                                "content": "            im.size = (1, 1)",
                                "type": "deleted"
                            },
                            {
                                "content": "            im.size = (1, 2)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "def test_older_icon() -> None:",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Tests/test_file_icns.py",
                            "type": "function",
                            "name": "test_sizes",
                            "content": "def test_sizes() -> None:\n    # Check that we can load all of the sizes, and that the final pixel\n    # dimensions are as expected\n    with Image.open(TEST_FILE) as im:\n        for w, h, r in im.info[\"sizes\"]:\n            wr = w * r\n            hr = h * r\n            im.size = (w, h, r)\n            im.load()\n            assert im.mode == \"RGBA\"\n            assert im.size == (wr, hr)\n\n        # Check that we cannot load an incorrect size\n        with pytest.raises(ValueError):\n            im.size = (1, 1)",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 83,
                            "end_lineno": 97,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 105,
                            "length": 8
                        },
                        "new_range": {
                            "start": 111,
                            "length": 8
                        },
                        "section": "def test_older_icon() -> None:"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "            wr = w * r",
                                "type": "context"
                            },
                            {
                                "content": "            hr = h * r",
                                "type": "context"
                            },
                            {
                                "content": "            with Image.open(\"Tests/images/pillow2.icns\") as im2:",
                                "type": "context"
                            },
                            {
                                "content": "                im2.size = (w, h, r)",
                                "type": "deleted"
                            },
                            {
                                "content": "                im2.load()",
                                "type": "deleted"
                            },
                            {
                                "content": "                im2.size = (w, h)",
                                "type": "added"
                            },
                            {
                                "content": "                im2.load(r)",
                                "type": "added"
                            },
                            {
                                "content": "                assert im2.mode == \"RGBA\"",
                                "type": "context"
                            },
                            {
                                "content": "                assert im2.size == (wr, hr)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Tests/test_file_icns.py",
                            "type": "function",
                            "name": "test_older_icon",
                            "content": "def test_older_icon() -> None:\n    # This icon was made with Icon Composer rather than iconutil; it still\n    # uses PNG rather than JP2, however (since it was made on 10.9).\n    with Image.open(\"Tests/images/pillow2.icns\") as im:\n        for w, h, r in im.info[\"sizes\"]:\n            wr = w * r\n            hr = h * r\n            with Image.open(\"Tests/images/pillow2.icns\") as im2:\n                im2.size = (w, h, r)\n                im2.load()\n                assert im2.mode == \"RGBA\"\n                assert im2.size == (wr, hr)",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 100,
                            "end_lineno": 111,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 122,
                            "length": 8
                        },
                        "new_range": {
                            "start": 128,
                            "length": 8
                        },
                        "section": "def test_jp2_icon() -> None:"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "            wr = w * r",
                                "type": "context"
                            },
                            {
                                "content": "            hr = h * r",
                                "type": "context"
                            },
                            {
                                "content": "            with Image.open(\"Tests/images/pillow3.icns\") as im2:",
                                "type": "context"
                            },
                            {
                                "content": "                im2.size = (w, h, r)",
                                "type": "deleted"
                            },
                            {
                                "content": "                im2.load()",
                                "type": "deleted"
                            },
                            {
                                "content": "                im2.size = (w, h)",
                                "type": "added"
                            },
                            {
                                "content": "                im2.load(r)",
                                "type": "added"
                            },
                            {
                                "content": "                assert im2.mode == \"RGBA\"",
                                "type": "context"
                            },
                            {
                                "content": "                assert im2.size == (wr, hr)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Tests/test_file_icns.py",
                            "type": "function",
                            "name": "test_jp2_icon",
                            "content": "def test_jp2_icon() -> None:\n    # This icon uses JPEG 2000 images instead of the PNG images.\n    # The advantage of doing this is that OS X 10.5 supports JPEG 2000\n    # but not PNG; some commercial software therefore does just this.\n\n    with Image.open(\"Tests/images/pillow3.icns\") as im:\n        for w, h, r in im.info[\"sizes\"]:\n            wr = w * r\n            hr = h * r\n            with Image.open(\"Tests/images/pillow3.icns\") as im2:\n                im2.size = (w, h, r)\n                im2.load()\n                assert im2.mode == \"RGBA\"\n                assert im2.size == (wr, hr)",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 115,
                            "end_lineno": 128,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": ".. _image-file-formats:\n\nImage file formats\n==================\n\nThe Python Imaging Library supports a wide variety of raster file formats.\nOver 30 different file formats can be identified and read by the library.\nWrite support is less extensive, but most common interchange and presentation\nformats are supported.\n\nThe :py:meth:`~PIL.Image.open` function identifies files from their\ncontents, not their names, but the :py:meth:`~PIL.Image.Image.save` method\nlooks at the name to determine which format to use, unless the format is given\nexplicitly.\n\nWhen an image is opened from a file, only that instance of the image is considered to\nhave the format. Copies of the image will contain data loaded from the file, but not\nthe file itself, meaning that it can no longer be considered to be in the original\nformat. So if :py:meth:`~PIL.Image.Image.copy` is called on an image, or another method\ninternally creates a copy of the image, then any methods or attributes specific to the\nformat will no longer be present. The ``fp`` (file pointer) attribute will no longer be\npresent, and the :py:attr:`~PIL.Image.Image.format` attribute will be ``None``.\n\nFully supported formats\n-----------------------\n\nBLP\n^^^\n\nBLP is the Blizzard Mipmap Format, a texture format used in World of\nWarcraft. Pillow supports reading ``JPEG`` Compressed or raw ``BLP1``\nimages, and all types of ``BLP2`` images.\n\nSaving\n~~~~~~\n\nPillow supports writing BLP images. The :py:meth:`~PIL.Image.Image.save` method\ncan take the following keyword arguments:\n\n**blp_version**\n    If present and set to \"BLP1\", images will be saved as BLP1. Otherwise, images\n    will be saved as BLP2.\n\nBMP\n^^^\n\nPillow reads and writes Windows and OS/2 BMP files containing ``1``, ``L``, ``P``,\nor ``RGB`` data. 16-colour images are read as ``P`` images.\nSupport for reading 8-bit run-length encoding was added in Pillow 9.1.0.\nSupport for reading 4-bit run-length encoding was added in Pillow 9.3.0.\n\nOpening\n~~~~~~~\n\nThe :py:meth:`~PIL.Image.open` method sets the following\n:py:attr:`~PIL.Image.Image.info` properties:\n\n**compression**\n    Set to 1 if the file is a 256-color run-length encoded image.\n    Set to 2 if the file is a 16-color run-length encoded image.\n\nDDS\n^^^\n\nDDS is a popular container texture format used in video games and natively supported\nby DirectX.\n\nDXT1 and DXT5 pixel formats can be read, only in ``RGBA`` mode.\n\n.. versionadded:: 3.4.0\n   DXT3 images can be read in ``RGB`` mode and DX10 images can be read in\n   ``RGB`` and ``RGBA`` mode.\n\n.. versionadded:: 6.0.0\n   Uncompressed ``RGBA`` images can be read.\n\n\n.. versionadded:: 8.3.0\n   BC5S images can be opened in ``RGB`` mode, and uncompressed ``RGB`` images\n   can be read. Uncompressed data can also be saved to image files.\n\n\n.. versionadded:: 9.3.0\n   ATI1 images can be opened in ``L`` mode and ATI2 images can be opened in\n   ``RGB`` mode.\n\n.. versionadded:: 9.4.0\n   Uncompressed ``L`` (\"luminance\") and ``LA`` images can be opened and saved.\n\n\n.. versionadded:: 10.1.0\n   BC5U can be read in ``RGB`` mode, and 8-bit color indexed images can be read\n   in ``P`` mode.\n\n\nDIB\n^^^\n\nPillow reads and writes DIB files. DIB files are similar to BMP files, so see\nabove for more information.\n\n    .. versionadded:: 6.0.0\n\nEPS\n^^^\n\nPillow identifies EPS files containing image data, and can read files that\ncontain embedded raster images (ImageData descriptors). If Ghostscript is\navailable, other EPS files can be read as well. The EPS driver can also write\nEPS images. The EPS driver can read EPS images in ``L``, ``LAB``, ``RGB`` and\n``CMYK`` mode, but Ghostscript may convert the images to ``RGB`` mode rather\nthan leaving them in the original color space. The EPS driver can write images\nin ``L``, ``RGB`` and ``CMYK`` modes.\n\nLoading\n~~~~~~~\n\nTo use Ghostscript, Pillow searches for the \"gs\" executable. On Windows, it\nalso searches for \"gswin32c\" and \"gswin64c\". To customise this behaviour,\n``EpsImagePlugin.gs_binary = \"gswin64\"`` will set the name of the executable to\nuse. ``EpsImagePlugin.gs_binary = False`` will prevent Ghostscript use.\n\nIf Ghostscript is available, you can call the :py:meth:`~PIL.Image.Image.load`\nmethod with the following parameters to affect how Ghostscript renders the EPS.\n\n**scale**\n    Affects the scale of the resultant rasterized image. If the EPS suggests\n    that the image be rendered at 100px x 100px, setting this parameter to\n    2 will make the Ghostscript render a 200px x 200px image instead. The\n    relative position of the bounding box is maintained::\n\n        im = Image.open(...)\n        im.size  # (100,100)\n        im.load(scale=2)\n        im.size  # (200,200)\n\n**transparency**\n    If true, generates an RGBA image with a transparent background, instead of\n    the default behaviour of an RGB image with a white background.\n\n\nGIF\n^^^\n\nPillow reads GIF87a and GIF89a versions of the GIF file format. The library\nwrites files in GIF87a by default, unless GIF89a features are used or GIF89a is\nalready in use. Files are written with LZW encoding.\n\nGIF files are initially read as grayscale (``L``) or palette mode (``P``)\nimages. Seeking to later frames in a ``P`` image will change the image to\n``RGB`` (or ``RGBA`` if the first frame had transparency).\n\n``P`` mode images are changed to ``RGB`` because each frame of a GIF may contain\nits own individual palette of up to 256 colors. When a new frame is placed onto a\nprevious frame, those colors may combine to exceed the ``P`` mode limit of 256\ncolors. Instead, the image is converted to ``RGB`` handle this.\n\nIf you would prefer the first ``P`` image frame to be ``RGB`` as well, so that\nevery ``P`` frame is converted to ``RGB`` or ``RGBA`` mode, there is a setting\navailable::\n\n    from PIL import GifImagePlugin\n    GifImagePlugin.LOADING_STRATEGY = GifImagePlugin.LoadingStrategy.RGB_ALWAYS\n\nGIF frames do not always contain individual palettes however. If there is only\na global palette, then all of the colors can fit within ``P`` mode. If you would\nprefer the frames to be kept as ``P`` in that case, there is also a setting\navailable::\n\n    from PIL import GifImagePlugin\n    GifImagePlugin.LOADING_STRATEGY = GifImagePlugin.LoadingStrategy.RGB_AFTER_DIFFERENT_PALETTE_ONLY\n\nTo restore the default behavior, where ``P`` mode images are only converted to\n``RGB`` or ``RGBA`` after the first frame::\n\n    from PIL import GifImagePlugin\n    GifImagePlugin.LOADING_STRATEGY = GifImagePlugin.LoadingStrategy.RGB_AFTER_FIRST\n\n.. _gif-opening:\n\nOpening\n~~~~~~~\n\nThe :py:meth:`~PIL.Image.open` method sets the following\n:py:attr:`~PIL.Image.Image.info` properties:\n\n**background**\n    Default background color (a palette color index).\n\n**transparency**\n    Transparency color index. This key is omitted if the image is not\n    transparent.\n\n**version**\n    Version (either ``GIF87a`` or ``GIF89a``).\n\n**duration**\n    May not be present. The time to display the current frame\n    of the GIF, in milliseconds.\n\n**loop**\n    May not be present. The number of times the GIF should loop. 0 means that\n    it will loop forever.\n\n**comment**\n    May not be present. A comment about the image. This is the last comment found\n    before the current frame's image.\n\n**extension**\n    May not be present. Contains application specific information.\n\nReading sequences\n~~~~~~~~~~~~~~~~~\n\nThe GIF loader supports the :py:meth:`~PIL.Image.Image.seek` and\n:py:meth:`~PIL.Image.Image.tell` methods. You can combine these methods\nto seek to the next frame (``im.seek(im.tell() + 1)``).\n\n``im.seek()`` raises an :py:exc:`EOFError` if you try to seek after the last frame.\n\n.. _gif-saving:\n\nSaving\n~~~~~~\n\nWhen calling :py:meth:`~PIL.Image.Image.save` to write a GIF file, the\nfollowing options are available::\n\n    im.save(out, save_all=True, append_images=[im1, im2, ...])\n\n**save_all**\n    If present and true, all frames of the image will be saved. If\n    not, then only the first frame of a multiframe image will be saved.\n\n**append_images**\n    A list of images to append as additional frames. Each of the\n    images in the list can be single or multiframe images.\n    This is currently supported for GIF, PDF, PNG, TIFF, and WebP.\n\n    It is also supported for ICO and ICNS. If images are passed in of relevant\n    sizes, they will be used instead of scaling down the main image.\n\n**include_color_table**\n    Whether or not to include local color table.\n\n**interlace**\n    Whether or not the image is interlaced. By default, it is, unless the image\n    is less than 16 pixels in width or height.\n\n**disposal**\n    Indicates the way in which the graphic is to be treated after being displayed.\n\n    * 0 - No disposal specified.\n    * 1 - Do not dispose.\n    * 2 - Restore to background color.\n    * 3 - Restore to previous content.\n\n     Pass a single integer for a constant disposal, or a list or tuple\n     to set the disposal for each frame separately.\n\n**palette**\n    Use the specified palette for the saved image. The palette should\n    be a bytes or bytearray object containing the palette entries in\n    RGBRGB... form. It should be no more than 768 bytes. Alternately,\n    the palette can be passed in as an\n    :py:class:`PIL.ImagePalette.ImagePalette` object.\n\n**optimize**\n    Whether to attempt to compress the palette by eliminating unused colors\n    (this is only useful if the palette can be compressed to the next smaller\n    power of 2 elements) and whether to mark all pixels that are not new in the\n    next frame as transparent.\n\n    This is attempted by default, unless a palette is specified as an option or\n    as part of the first image's :py:attr:`~PIL.Image.Image.info` dictionary.\n\nNote that if the image you are saving comes from an existing GIF, it may have\nthe following properties in its :py:attr:`~PIL.Image.Image.info` dictionary.\nFor these options, if you do not pass them in, they will default to\ntheir :py:attr:`~PIL.Image.Image.info` values.\n\n**transparency**\n    Transparency color index.\n\n**duration**\n    The display duration of each frame of the multiframe gif, in\n    milliseconds. Pass a single integer for a constant duration, or a\n    list or tuple to set the duration for each frame separately.\n\n**loop**\n    Integer number of times the GIF should loop. 0 means that it will loop\n    forever. If omitted or ``None``, the image will not loop.\n\n**comment**\n    A comment about the image.\n\nReading local images\n~~~~~~~~~~~~~~~~~~~~\n\nThe GIF loader creates an image memory the same size as the GIF file’s *logical\nscreen size*, and pastes the actual pixel data (the *local image*) into this\nimage. If you only want the actual pixel rectangle, you can crop the image::\n\n    im = Image.open(...)\n\n    if im.tile[0][0] == \"gif\":\n        # only read the first \"local image\" from this GIF file\n        box = im.tile[0][1]\n        im = im.crop(box)\n\nICNS\n^^^^\n\nPillow reads and writes macOS ``.icns`` files.  By default, the\nlargest available icon is read, though you can override this by setting the\n:py:attr:`~PIL.Image.Image.size` property before calling\n:py:meth:`~PIL.Image.Image.load`.  The :py:meth:`~PIL.Image.open` method\nsets the following :py:attr:`~PIL.Image.Image.info` property:\n\n.. note::\n\n    Prior to version 8.3.0, Pillow could only write ICNS files on macOS.\n\n**sizes**\n    A list of supported sizes found in this icon file; these are a\n    3-tuple, ``(width, height, scale)``, where ``scale`` is 2 for a retina\n    icon and 1 for a standard icon.  You *are* permitted to use this 3-tuple\n    format for the :py:attr:`~PIL.Image.Image.size` property if you set it\n    before calling :py:meth:`~PIL.Image.Image.load`; after loading, the size\n    will be reset to a 2-tuple containing pixel dimensions (so, e.g. if you\n    ask for ``(512, 512, 2)``, the final value of\n    :py:attr:`~PIL.Image.Image.size` will be ``(1024, 1024)``).\n\n.. _icns-saving:\n\nSaving\n~~~~~~\n\nThe :py:meth:`~PIL.Image.Image.save` method can take the following keyword arguments:\n\n**append_images**\n    A list of images to replace the scaled down versions of the image.\n    The order of the images does not matter, as their use is determined by\n    the size of each image.\n\n    .. versionadded:: 5.1.0\n\nICO\n^^^\n\nICO is used to store icons on Windows. The largest available icon is read.\n\n.. _ico-saving:\n\nSaving\n~~~~~~\n\nThe :py:meth:`~PIL.Image.Image.save` method supports the following options:\n\n**sizes**\n    A list of sizes including in this ico file; these are a 2-tuple,\n    ``(width, height)``; Default to ``[(16, 16), (24, 24), (32, 32), (48, 48),\n    (64, 64), (128, 128), (256, 256)]``. Any sizes bigger than the original\n    size or 256 will be ignored.\n\nThe :py:meth:`~PIL.Image.Image.save` method can take the following keyword arguments:\n\n**append_images**\n    A list of images to replace the scaled down versions of the image.\n    The order of the images does not matter, as their use is determined by\n    the size of each image.\n\n    .. versionadded:: 8.1.0\n\n**bitmap_format**\n    By default, the image data will be saved in PNG format. With a bitmap format of\n    \"bmp\", image data will be saved in BMP format instead.\n\n    .. versionadded:: 8.3.0\n\nIM\n^^\n\nIM is a format used by LabEye and other applications based on the IFUNC image\nprocessing library. The library reads and writes most uncompressed interchange\nversions of this format.\n\nIM is the only format that can store all internal Pillow formats.\n\nJPEG\n^^^^\n\nPillow reads JPEG, JFIF, and Adobe JPEG files containing ``L``, ``RGB``, or\n``CMYK`` data. It writes standard and progressive JFIF files.\n\nUsing the :py:meth:`~PIL.Image.Image.draft` method, you can speed things up by\nconverting ``RGB`` images to ``L``, and resize images to 1/2, 1/4 or 1/8 of\ntheir original size while loading them.\n\nBy default Pillow doesn't allow loading of truncated JPEG files, set\n:data:`.ImageFile.LOAD_TRUNCATED_IMAGES` to override this.\n\n.. _jpeg-opening:\n\nOpening\n~~~~~~~\n\nThe :py:meth:`~PIL.Image.open` method may set the following\n:py:attr:`~PIL.Image.Image.info` properties if available:\n\n**jfif**\n    JFIF application marker found. If the file is not a JFIF file, this key is\n    not present.\n\n**jfif_version**\n    A tuple representing the jfif version, (major version, minor version).\n\n**jfif_density**\n    A tuple representing the pixel density of the image, in units specified\n    by jfif_unit.\n\n**jfif_unit**\n    Units for the jfif_density:\n\n    * 0 - No Units\n    * 1 - Pixels per Inch\n    * 2 - Pixels per Centimeter\n\n**dpi**\n    A tuple representing the reported pixel density in pixels per inch, if\n    the file is a jfif file and the units are in inches.\n\n**adobe**\n    Adobe application marker found. If the file is not an Adobe JPEG file, this\n    key is not present.\n\n**adobe_transform**\n    Vendor Specific Tag.\n\n**progression**\n    Indicates that this is a progressive JPEG file.\n\n**icc_profile**\n    The ICC color profile for the image.\n\n**exif**\n    Raw EXIF data from the image.\n\n**comment**\n    A comment about the image.\n\n    .. versionadded:: 7.1.0\n\n.. _jpeg-saving:\n\nSaving\n~~~~~~\n\nThe :py:meth:`~PIL.Image.Image.save` method supports the following options:\n\n**quality**\n    The image quality, on a scale from 0 (worst) to 95 (best), or the string\n    ``keep``. The default is 75. Values above 95 should be avoided; 100 disables\n    portions of the JPEG compression algorithm, and results in large files with\n    hardly any gain in image quality. The value ``keep`` is only valid for JPEG\n    files and will retain the original image quality level, subsampling, and\n    qtables.\n\n**optimize**\n    If present and true, indicates that the encoder should make an extra pass\n    over the image in order to select optimal encoder settings.\n\n**progressive**\n    If present and true, indicates that this image should be stored as a\n    progressive JPEG file.\n\n**dpi**\n    A tuple of integers representing the pixel density, ``(x,y)``.\n\n**icc_profile**\n    If present and true, the image is stored with the provided ICC profile.\n    If this parameter is not provided, the image will be saved with no profile\n    attached. To preserve the existing profile::\n\n        im.save(filename, 'jpeg', icc_profile=im.info.get('icc_profile'))\n\n**exif**\n    If present, the image will be stored with the provided raw EXIF data.\n\n**keep_rgb**\n    By default, libjpeg converts images with an RGB color space to YCbCr.\n    If this option is present and true, those images will be stored as RGB\n    instead.\n\n    When this option is enabled, attempting to chroma-subsample RGB images\n    with the ``subsampling`` option will raise an :py:exc:`OSError`.\n\n    .. versionadded:: 10.2.0\n\n**subsampling**\n    If present, sets the subsampling for the encoder.\n\n    * ``keep``: Only valid for JPEG files, will retain the original image setting.\n    * ``4:4:4``, ``4:2:2``, ``4:2:0``: Specific sampling values\n    * ``0``: equivalent to ``4:4:4``\n    * ``1``: equivalent to ``4:2:2``\n    * ``2``: equivalent to ``4:2:0``\n\n    If absent, the setting will be determined by libjpeg or libjpeg-turbo.\n\n**restart_marker_blocks**\n    If present, emit a restart marker whenever the specified number of MCU\n    blocks has been produced.\n\n    .. versionadded:: 10.2.0\n\n**restart_marker_rows**\n    If present, emit a restart marker whenever the specified number of MCU\n    rows has been produced.\n\n    .. versionadded:: 10.2.0\n\n**qtables**\n    If present, sets the qtables for the encoder. This is listed as an\n    advanced option for wizards in the JPEG documentation. Use with\n    caution. ``qtables`` can be one of several types of values:\n\n    *  a string, naming a preset, e.g. ``keep``, ``web_low``, or ``web_high``\n    *  a list, tuple, or dictionary (with integer keys =\n       range(len(keys))) of lists of 64 integers. There must be\n       between 2 and 4 tables.\n\n    .. versionadded:: 2.5.0\n\n**streamtype**\n    Allows storing images without quantization and Huffman tables, or with\n    these tables but without image data.  This is useful for container formats\n    or network protocols that handle tables separately and share them between\n    images.\n\n    * ``0`` (default): interchange datastream, with tables and image data\n    * ``1``: abbreviated table specification (tables-only) datastream\n\n      .. versionadded:: 10.2.0\n\n    * ``2``: abbreviated image (image-only) datastream\n\n**comment**\n    A comment about the image.\n\n    .. versionadded:: 9.4.0\n\n\n.. note::\n\n    To enable JPEG support, you need to build and install the IJG JPEG library\n    before building the Python Imaging Library. See the distribution README for\n    details.\n\nJPEG 2000\n^^^^^^^^^\n\n.. versionadded:: 2.4.0\n\nPillow reads and writes JPEG 2000 files containing ``L``, ``LA``, ``RGB``,\n``RGBA``, or ``YCbCr`` data.  When reading, ``YCbCr`` data is converted to\n``RGB`` or ``RGBA`` depending on whether or not there is an alpha channel.\nBeginning with version 8.3.0, Pillow can read (but not write) ``RGB``,\n``RGBA``, and ``YCbCr`` images with subsampled components.  Pillow supports\nJPEG 2000 raw codestreams (``.j2k`` files), as well as boxed JPEG 2000 files\n(``.jp2`` or ``.jpx`` files).\n\nWhen loading, if you set the ``mode`` on the image prior to the\n:py:meth:`~PIL.Image.Image.load` method being invoked, you can ask Pillow to\nconvert the image to either ``RGB`` or ``RGBA`` rather than choosing for\nitself.  It is also possible to set ``reduce`` to the number of resolutions to\ndiscard (each one reduces the size of the resulting image by a factor of 2),\nand ``layers`` to specify the number of quality layers to load.\n\n.. _jpeg-2000-saving:\n\nSaving\n~~~~~~\n\nThe :py:meth:`~PIL.Image.Image.save` method supports the following options:\n\n**offset**\n    The image offset, as a tuple of integers, e.g. (16, 16)\n\n**tile_offset**\n    The tile offset, again as a 2-tuple of integers.\n\n**tile_size**\n    The tile size as a 2-tuple.  If not specified, or if set to None, the\n    image will be saved without tiling.\n\n**quality_mode**\n    Either ``\"rates\"`` or ``\"dB\"`` depending on the units you want to use to\n    specify image quality.\n\n**quality_layers**\n    A sequence of numbers, each of which represents either an approximate size\n    reduction (if quality mode is ``\"rates\"``) or a signal to noise ratio value\n    in decibels.  If not specified, defaults to a single layer of full quality.\n\n**num_resolutions**\n    The number of different image resolutions to be stored (which corresponds\n    to the number of Discrete Wavelet Transform decompositions plus one).\n\n**codeblock_size**\n    The code-block size as a 2-tuple.  Minimum size is 4 x 4, maximum is 1024 x\n    1024, with the additional restriction that no code-block may have more\n    than 4096 coefficients (i.e. the product of the two numbers must be no\n    greater than 4096).\n\n**precinct_size**\n    The precinct size as a 2-tuple.  Must be a power of two along both axes,\n    and must be greater than the code-block size.\n\n**irreversible**\n    If ``True``, use the lossy discrete waveform transformation DWT 9-7.\n    Defaults to ``False``, which uses the lossless DWT 5-3.\n\n**mct**\n    If ``1`` then enable multiple component transformation when encoding,\n    otherwise use ``0`` for no component transformation (default). If MCT is\n    enabled and ``irreversible`` is ``True`` then the Irreversible Color\n    Transformation will be applied, otherwise encoding will use the\n    Reversible Color Transformation. MCT works best with a ``mode`` of\n    ``RGB`` and is only applicable when the image data has 3 components.\n\n    .. versionadded:: 9.1.0\n\n**progression**\n    Controls the progression order; must be one of ``\"LRCP\"``, ``\"RLCP\"``,\n    ``\"RPCL\"``, ``\"PCRL\"``, ``\"CPRL\"``.  The letters stand for Component,\n    Position, Resolution and Layer respectively and control the order of\n    encoding, the idea being that e.g. an image encoded using LRCP mode can\n    have its quality layers decoded as they arrive at the decoder, while one\n    encoded using RLCP mode will have increasing resolutions decoded as they\n    arrive, and so on.\n\n**signed**\n    If true, then tell the encoder to save the image as signed.\n\n    .. versionadded:: 9.4.0\n\n**cinema_mode**\n    Set the encoder to produce output compliant with the digital cinema\n    specifications.  The options here are ``\"no\"`` (the default),\n    ``\"cinema2k-24\"`` for 24fps 2K, ``\"cinema2k-48\"`` for 48fps 2K, and\n    ``\"cinema4k-24\"`` for 24fps 4K.  Note that for compliant 2K files,\n    *at least one* of your image dimensions must match 2048 x 1080, while\n    for compliant 4K files, *at least one* of the dimensions must match\n    4096 x 2160.\n\n**no_jp2**\n    If ``True`` then don't wrap the raw codestream in the JP2 file format when\n    saving, otherwise the extension of the filename will be used to determine\n    the format (default).\n\n    .. versionadded:: 9.1.0\n\n**comment**\n    Adds a custom comment to the file, replacing the default\n    \"Created by OpenJPEG version\" comment.\n\n    .. versionadded:: 9.5.0\n\n**plt**\n    If ``True`` and OpenJPEG 2.4.0 or later is available, then include a PLT\n    (packet length, tile-part header) marker in the produced file.\n    Defaults to ``False``.\n\n    .. versionadded:: 9.5.0\n\n.. note::\n\n   To enable JPEG 2000 support, you need to build and install the OpenJPEG\n   library, version 2.0.0 or higher, before building the Python Imaging\n   Library.\n\n   Windows users can install the OpenJPEG binaries available on the\n   OpenJPEG website, but must add them to their PATH in order to use Pillow (if\n   you fail to do this, you will get errors about not being able to load the\n   ``_imaging`` DLL).\n\nMSP\n^^^\n\nPillow identifies and reads MSP files from Windows 1 and 2. The library writes\nuncompressed (Windows 1) versions of this format.\n\nPCX\n^^^\n\nPillow reads and writes PCX files containing ``1``, ``L``, ``P``, or ``RGB`` data.\n\nPFM\n^^^\n\n.. versionadded:: 10.3.0\n\nPillow reads and writes grayscale (Pf format) Portable FloatMap (PFM) files\ncontaining ``F`` data.\n\nColor (PF format) PFM files are not supported.\n\nOpening\n~~~~~~~\n\nThe :py:func:`~PIL.Image.open` function sets the following\n:py:attr:`~PIL.Image.Image.info` properties:\n\n**scale**\n    The absolute value of the number stored in the *Scale Factor / Endianness* line.\n\nPNG\n^^^\n\nPillow identifies, reads, and writes PNG files containing ``1``, ``L``, ``LA``,\n``I``, ``P``, ``RGB`` or ``RGBA`` data. Interlaced files are supported as of\nv1.1.7.\n\nAs of Pillow 6.0, EXIF data can be read from PNG images. However, unlike other\nimage formats, EXIF data is not guaranteed to be present in\n:py:attr:`~PIL.Image.Image.info` until :py:meth:`~PIL.Image.Image.load` has been\ncalled.\n\nBy default Pillow doesn't allow loading of truncated PNG files, set\n:data:`.ImageFile.LOAD_TRUNCATED_IMAGES` to override this.\n\n.. _png-opening:\n\nOpening\n~~~~~~~\n\nThe :py:func:`~PIL.Image.open` function sets the following\n:py:attr:`~PIL.Image.Image.info` properties, when appropriate:\n\n**chromaticity**\n    The chromaticity points, as an 8 tuple of floats. (``White Point\n    X``, ``White Point Y``, ``Red X``, ``Red Y``, ``Green X``, ``Green\n    Y``, ``Blue X``, ``Blue Y``)\n\n**gamma**\n    Gamma, given as a floating point number.\n\n**srgb**\n    The sRGB rendering intent as an integer.\n\n      * 0 Perceptual\n      * 1 Relative Colorimetric\n      * 2 Saturation\n      * 3 Absolute Colorimetric\n\n**transparency**\n    For ``P`` images: Either the palette index for full transparent pixels,\n    or a byte string with alpha values for each palette entry.\n\n    For ``1``, ``L``, ``I`` and ``RGB`` images, the color that represents\n    full transparent pixels in this image.\n\n    This key is omitted if the image is not a transparent palette image.\n\n.. _png-text:\n\n``open`` also sets ``Image.text`` to a dictionary of the values of the\n``tEXt``, ``zTXt``, and ``iTXt`` chunks of the PNG image. Individual\ncompressed chunks are limited to a decompressed size of\n:data:`.PngImagePlugin.MAX_TEXT_CHUNK`, by default 1MB, to prevent\ndecompression bombs. Additionally, the total size of all of the text\nchunks is limited to :data:`.PngImagePlugin.MAX_TEXT_MEMORY`, defaulting to\n64MB.\n\n.. _png-saving:\n\nSaving\n~~~~~~\n\nThe :py:meth:`~PIL.Image.Image.save` method supports the following options:\n\n**optimize**\n    If present and true, instructs the PNG writer to make the output file as\n    small as possible. This includes extra processing in order to find optimal\n    encoder settings.\n\n**transparency**\n    For ``P``, ``1``, ``L``, ``I``, and ``RGB`` images, this option controls\n    what color from the image to mark as transparent.\n\n    For ``P`` images, this can be a either the palette index,\n    or a byte string with alpha values for each palette entry.\n\n**dpi**\n    A tuple of two numbers corresponding to the desired dpi in each direction.\n\n**pnginfo**\n    A :py:class:`PIL.PngImagePlugin.PngInfo` instance containing chunks.\n\n**compress_level**\n    ZLIB compression level, a number between 0 and 9: 1 gives best speed,\n    9 gives best compression, 0 gives no compression at all. Default is 6.\n    When ``optimize`` option is True ``compress_level`` has no effect\n    (it is set to 9 regardless of a value passed).\n\n**icc_profile**\n    The ICC Profile to include in the saved file.\n\n**exif**\n    The exif data to include in the saved file.\n\n    .. versionadded:: 6.0.0\n\n**bits (experimental)**\n    For ``P`` images, this option controls how many bits to store. If omitted,\n    the PNG writer uses 8 bits (256 colors).\n\n**dictionary (experimental)**\n    Set the ZLIB encoder dictionary.\n\n.. note::\n\n    To enable PNG support, you need to build and install the ZLIB compression\n    library before building the Python Imaging Library. See the\n    :doc:`installation documentation <../installation>` for details.\n\n.. _apng-sequences:\n\nAPNG sequences\n~~~~~~~~~~~~~~\n\nThe PNG loader includes limited support for reading and writing Animated Portable\nNetwork Graphics (APNG) files.\nWhen an APNG file is loaded, :py:meth:`~PIL.ImageFile.ImageFile.get_format_mimetype`\nwill return ``\"image/apng\"``. The value of the :py:attr:`~PIL.Image.Image.is_animated`\nproperty will be ``True`` when the :py:attr:`~PIL.Image.Image.n_frames` property is\ngreater than 1. For APNG files, the ``n_frames`` property depends on both the animation\nframe count as well as the presence or absence of a default image. See the\n``default_image`` property documentation below for more details.\nThe :py:meth:`~PIL.Image.Image.seek` and :py:meth:`~PIL.Image.Image.tell` methods\nare supported.\n\n``im.seek()`` raises an :py:exc:`EOFError` if you try to seek after the last frame.\n\nThese :py:attr:`~PIL.Image.Image.info` properties will be set for APNG frames,\nwhere applicable:\n\n**default_image**\n    Specifies whether or not this APNG file contains a separate default image,\n    which is not a part of the actual APNG animation.\n\n    When an APNG file contains a default image, the initially loaded image (i.e.\n    the result of ``seek(0)``) will be the default image.\n    To account for the presence of the default image, the\n    :py:attr:`~PIL.Image.Image.n_frames` property will be set to ``frame_count + 1``,\n    where ``frame_count`` is the actual APNG animation frame count.\n    To load the first APNG animation frame, ``seek(1)`` must be called.\n\n    * ``True`` - The APNG contains default image, which is not an animation frame.\n    * ``False`` - The APNG does not contain a default image. The ``n_frames`` property\n      will be set to the actual APNG animation frame count.\n      The initially loaded image (i.e. ``seek(0)``) will be the first APNG animation\n      frame.\n\n**loop**\n    The number of times to loop this APNG, 0 indicates infinite looping.\n\n**duration**\n    The time to display this APNG frame (in milliseconds).\n\n.. note::\n\n    The APNG loader returns images the same size as the APNG file's logical screen size.\n    The returned image contains the pixel data for a given frame, after applying\n    any APNG frame disposal and frame blend operations (i.e. it contains what a web\n    browser would render for this frame - the composite of all previous frames and this\n    frame).\n\n    Any APNG file containing sequence errors is treated as an invalid image. The APNG\n    loader will not attempt to repair and reorder files containing sequence errors.\n\n.. _apng-saving:\n\nSaving\n~~~~~~\n\nWhen calling :py:meth:`~PIL.Image.Image.save`, by default only a single frame PNG file\nwill be saved. To save an APNG file (including a single frame APNG), the ``save_all``\nparameter must be set to ``True``. The following parameters can also be set:\n\n**default_image**\n    Boolean value, specifying whether or not the base image is a default image.\n    If ``True``, the base image will be used as the default image, and the first image\n    from the ``append_images`` sequence will be the first APNG animation frame.\n    If ``False``, the base image will be used as the first APNG animation frame.\n    Defaults to ``False``.\n\n**append_images**\n    A list or tuple of images to append as additional frames. Each of the\n    images in the list can be single or multiframe images. The size of each frame\n    should match the size of the base image. Also note that if a frame's mode does\n    not match that of the base image, the frame will be converted to the base image\n    mode.\n\n**loop**\n    Integer number of times to loop this APNG, 0 indicates infinite looping.\n    Defaults to 0.\n\n**duration**\n    Integer (or list or tuple of integers) length of time to display this APNG frame\n    (in milliseconds).\n    Defaults to 0.\n\n**disposal**\n    An integer (or list or tuple of integers) specifying the APNG disposal\n    operation to be used for this frame before rendering the next frame.\n    Defaults to 0.\n\n    * 0 (:py:data:`~PIL.PngImagePlugin.Disposal.OP_NONE`, default) -\n      No disposal is done on this frame before rendering the next frame.\n    * 1 (:py:data:`PIL.PngImagePlugin.Disposal.OP_BACKGROUND`) -\n      This frame's modified region is cleared to fully transparent black before\n      rendering the next frame.\n    * 2 (:py:data:`~PIL.PngImagePlugin.Disposal.OP_PREVIOUS`) -\n      This frame's modified region is reverted to the previous frame's contents before\n      rendering the next frame.\n\n**blend**\n    An integer (or list or tuple of integers) specifying the APNG blend\n    operation to be used for this frame before rendering the next frame.\n    Defaults to 0.\n\n    * 0 (:py:data:`~PIL.PngImagePlugin.Blend.OP_SOURCE`) -\n      All color components of this frame, including alpha, overwrite the previous output\n      image contents.\n    * 1 (:py:data:`~PIL.PngImagePlugin.Blend.OP_OVER`) -\n      This frame should be alpha composited with the previous output image contents.\n\n.. note::\n\n    The ``duration``, ``disposal`` and ``blend`` parameters can be set to lists or tuples to\n    specify values for each individual frame in the animation. The length of the list or tuple\n    must be identical to the total number of actual frames in the APNG animation.\n    If the APNG contains a default image (i.e. ``default_image`` is set to ``True``),\n    these list or tuple parameters should not include an entry for the default image.\n\n\nPPM\n^^^\n\nPillow reads and writes PBM, PGM, PPM and PNM files containing ``1``, ``L``, ``I`` or\n``RGB`` data.\n\n\"Raw\" (P4 to P6) formats can be read, and are used when writing.\n\nSince Pillow 9.2.0, \"plain\" (P1 to P3) formats can be read as well.\n\nSGI\n^^^\n\nPillow reads and writes uncompressed ``L``, ``RGB``, and ``RGBA`` files.\n\n\nSPIDER\n^^^^^^\n\nPillow reads and writes SPIDER image files of 32-bit floating point data\n(\"F;32F\").\n\nPillow also reads SPIDER stack files containing sequences of SPIDER images. The\n:py:meth:`~PIL.Image.Image.seek` and :py:meth:`~PIL.Image.Image.tell` methods are supported, and\nrandom access is allowed.\n\n.. _spider-opening:\n\nOpening\n~~~~~~~\n\nThe :py:meth:`~PIL.Image.open` method sets the following attributes:\n\n**format**\n    Set to ``SPIDER``\n\n**istack**\n    Set to 1 if the file is an image stack, else 0.\n\n**n_frames**\n    Set to the number of images in the stack.\n\nA convenience method, :py:meth:`~PIL.SpiderImagePlugin.SpiderImageFile.convert2byte`,\nis provided for converting floating point data to byte data (mode ``L``)::\n\n    im = Image.open(\"image001.spi\").convert2byte()\n\n.. _spider-saving:\n\nSaving\n~~~~~~\n\nThe extension of SPIDER files may be any 3 alphanumeric characters. Therefore\nthe output format must be specified explicitly::\n\n    im.save('newimage.spi', format='SPIDER')\n\nFor more information about the SPIDER image processing package, see\nhttps://github.com/spider-em/SPIDER\n\nTGA\n^^^\n\nPillow reads and writes TGA images containing ``L``, ``LA``, ``P``,\n``RGB``, and ``RGBA`` data. Pillow can read and write both uncompressed and\nrun-length encoded TGAs.\n\n.. _tga-saving:\n\nSaving\n~~~~~~\n\nThe :py:meth:`~PIL.Image.Image.save` method can take the following keyword arguments:\n\n**compression**\n    If set to \"tga_rle\", the file will be run-length encoded.\n\n    .. versionadded:: 5.3.0\n\n**id_section**\n    The identification field.\n\n    .. versionadded:: 5.3.0\n\n**orientation**\n    If present and a positive number, the first pixel is for the top left corner,\n    rather than the bottom left corner.\n\n    .. versionadded:: 5.3.0\n\nTIFF\n^^^^\n\nPillow reads and writes TIFF files. It can read both striped and tiled\nimages, pixel and plane interleaved multi-band images. If you have\nlibtiff and its headers installed, Pillow can read and write many kinds\nof compressed TIFF files. If not, Pillow will only read and write\nuncompressed files.\n\n.. note::\n\n    Beginning in version 5.0.0, Pillow requires libtiff to read or\n    write compressed files. Prior to that release, Pillow had buggy\n    support for reading Packbits, LZW and JPEG compressed TIFFs\n    without using libtiff.\n\n.. _tiff-opening:\n\nOpening\n~~~~~~~\n\nThe :py:meth:`~PIL.Image.open` method sets the following\n:py:attr:`~PIL.Image.Image.info` properties:\n\n**compression**\n    Compression mode.\n\n    .. versionadded:: 2.0.0\n\n**dpi**\n    Image resolution as an ``(xdpi, ydpi)`` tuple, where applicable. You can use\n    the :py:attr:`~PIL.TiffImagePlugin.TiffImageFile.tag` attribute to get more\n    detailed information about the image resolution.\n\n    .. versionadded:: 1.1.5\n\n**resolution**\n    Image resolution as an ``(xres, yres)`` tuple, where applicable. This is a\n    measurement in whichever unit is specified by the file.\n\n    .. versionadded:: 1.1.5\n\n\nThe :py:attr:`~PIL.TiffImagePlugin.TiffImageFile.tag_v2` attribute contains a\ndictionary of TIFF metadata. The keys are numerical indexes from\n:py:data:`.TiffTags.TAGS_V2`.  Values are strings or numbers for single\nitems, multiple values are returned in a tuple of values. Rational\nnumbers are returned as a :py:class:`~PIL.TiffImagePlugin.IFDRational`\nobject.\n\n    .. versionadded:: 3.0.0\n\nFor compatibility with legacy code, the\n:py:attr:`~PIL.TiffImagePlugin.TiffImageFile.tag` attribute contains a dictionary\nof decoded TIFF fields as returned prior to version 3.0.0.  Values are\nreturned as either strings or tuples of numeric values. Rational\nnumbers are returned as a tuple of ``(numerator, denominator)``.\n\n    .. deprecated:: 3.0.0\n\nReading Multi-frame TIFF Images\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThe TIFF loader supports the :py:meth:`~PIL.Image.Image.seek` and\n:py:meth:`~PIL.Image.Image.tell` methods, taking and returning frame numbers\nwithin the image file. You can combine these methods to seek to the next frame\n(``im.seek(im.tell() + 1)``). Frames are numbered from 0 to ``im.n_frames - 1``,\nand can be accessed in any order.\n\n``im.seek()`` raises an :py:exc:`EOFError` if you try to seek after the\nlast frame.\n\n.. _tiff-saving:\n\nSaving\n~~~~~~\n\nThe :py:meth:`~PIL.Image.Image.save` method can take the following keyword arguments:\n\n**save_all**\n    If true, Pillow will save all frames of the image to a multiframe tiff document.\n\n    .. versionadded:: 3.4.0\n\n**append_images**\n    A list of images to append as additional frames. Each of the\n    images in the list can be single or multiframe images. Note however, that for\n    correct results, all the appended images should have the same\n    ``encoderinfo`` and ``encoderconfig`` properties.\n\n    .. versionadded:: 4.2.0\n\n**tiffinfo**\n    A :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2` object or dict\n    object containing tiff tags and values. The TIFF field type is\n    autodetected for Numeric and string values, any other types\n    require using an :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`\n    object and setting the type in\n    :py:attr:`~PIL.TiffImagePlugin.ImageFileDirectory_v2.tagtype` with\n    the appropriate numerical value from\n    :py:data:`.TiffTags.TYPES`.\n\n    .. versionadded:: 2.3.0\n\n    Metadata values that are of the rational type should be passed in\n    using a :py:class:`~PIL.TiffImagePlugin.IFDRational` object.\n\n    .. versionadded:: 3.1.0\n\n    For compatibility with legacy code, a\n    :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1` object may\n    be passed in this field. However, this is deprecated.\n\n    .. versionadded:: 5.4.0\n\n    Previous versions only supported some tags when writing using\n    libtiff. The supported list is found in\n    :py:data:`.TiffTags.LIBTIFF_CORE`.\n\n    .. versionadded:: 6.1.0\n\n    Added support for signed types (e.g. ``TIFF_SIGNED_LONG``) and multiple values.\n    Multiple values for a single tag must be to\n    :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2` as a tuple and\n    require a matching type in\n    :py:attr:`~PIL.TiffImagePlugin.ImageFileDirectory_v2.tagtype` tagtype.\n\n**exif**\n    Alternate keyword to \"tiffinfo\", for consistency with other formats.\n\n    .. versionadded:: 8.4.0\n\n**compression**\n    A string containing the desired compression method for the\n    file. (valid only with libtiff installed) Valid compression\n    methods are: :data:`None`, ``\"group3\"``, ``\"group4\"``, ``\"jpeg\"``, ``\"lzma\"``,\n    ``\"packbits\"``, ``\"tiff_adobe_deflate\"``, ``\"tiff_ccitt\"``, ``\"tiff_lzw\"``,\n    ``\"tiff_raw_16\"``, ``\"tiff_sgilog\"``, ``\"tiff_sgilog24\"``, ``\"tiff_thunderscan\"``,\n    ``\"webp\"``, ``\"zstd\"``\n\n**quality**\n    The image quality for JPEG compression, on a scale from 0 (worst) to 100\n    (best). The default is 75.\n\n    .. versionadded:: 6.1.0\n\nThese arguments to set the tiff header fields are an alternative to\nusing the general tags available through tiffinfo.\n\n**description**\n\n**software**\n\n**date_time**\n\n**artist**\n\n**copyright**\n    Strings\n\n**icc_profile**\n    The ICC Profile to include in the saved file.\n\n**resolution_unit**\n    An integer. 1 for no unit, 2 for inches and 3 for centimeters.\n\n**resolution**\n    Either an integer or a float, used for both the x and y resolution.\n\n**x_resolution**\n    Either an integer or a float.\n\n**y_resolution**\n    Either an integer or a float.\n\n**dpi**\n    A tuple of ``(x_resolution, y_resolution)``, with inches as the resolution\n    unit. For consistency with other image formats, the x and y resolutions\n    of the dpi will be rounded to the nearest integer.\n\n\nWebP\n^^^^\n\nPillow reads and writes WebP files. Requires libwebp v0.5.0 or later.\n\n.. _webp-saving:\n\nSaving\n~~~~~~\n\nThe :py:meth:`~PIL.Image.Image.save` method supports the following options:\n\n**lossless**\n    If present and true, instructs the WebP writer to use lossless compression.\n\n**quality**\n    Integer, 0-100, defaults to 80. For lossy, 0 gives the smallest\n    size and 100 the largest. For lossless, this parameter is the amount\n    of effort put into the compression: 0 is the fastest, but gives larger\n    files compared to the slowest, but best, 100.\n\n**alpha_quality**\n    Integer, 0-100, defaults to 100. For lossy compression only. 0 gives the\n    smallest size and 100 is lossless.\n\n**method**\n    Quality/speed trade-off (0=fast, 6=slower-better). Defaults to 4.\n\n**exact**\n    If true, preserve the transparent RGB values. Otherwise, discard\n    invisible RGB values for better compression. Defaults to false.\n\n**icc_profile**\n    The ICC Profile to include in the saved file.\n\n**exif**\n    The exif data to include in the saved file.\n\n**xmp**\n    The XMP data to include in the saved file.\n\nSaving sequences\n~~~~~~~~~~~~~~~~\n\nWhen calling :py:meth:`~PIL.Image.Image.save` to write a WebP file, by default\nonly the first frame of a multiframe image will be saved. If the ``save_all``\nargument is present and true, then all frames will be saved, and the following\noptions will also be available.\n\n**append_images**\n    A list of images to append as additional frames. Each of the\n    images in the list can be single or multiframe images.\n\n**duration**\n    The display duration of each frame, in milliseconds. Pass a single\n    integer for a constant duration, or a list or tuple to set the\n    duration for each frame separately.\n\n**loop**\n    Number of times to repeat the animation. Defaults to [0 = infinite].\n\n**background**\n    Background color of the canvas, as an RGBA tuple with values in\n    the range of (0-255).\n\n**minimize_size**\n    If true, minimize the output size (slow). Implicitly disables\n    key-frame insertion.\n\n**kmin, kmax**\n    Minimum and maximum distance between consecutive key frames in\n    the output. The library may insert some key frames as needed\n    to satisfy this criteria. Note that these conditions should\n    hold: kmax > kmin and kmin >= kmax / 2 + 1. Also, if kmax <= 0,\n    then key-frame insertion is disabled; and if kmax == 1, then all\n    frames will be key-frames (kmin value does not matter for these\n    special cases).\n\n**allow_mixed**\n    If true, use mixed compression mode; the encoder heuristically\n    chooses between lossy and lossless for each frame.\n\nXBM\n^^^\n\nPillow reads and writes X bitmap files (mode ``1``).\n\nRead-only formats\n-----------------\n\nCUR\n^^^\n\nCUR is used to store cursors on Windows. The CUR decoder reads the largest\navailable cursor. Animated cursors are not supported.\n\nDCX\n^^^\n\nDCX is a container file format for PCX files, defined by Intel. The DCX format\nis commonly used in fax applications. The DCX decoder can read files containing\n``1``, ``L``, ``P``, or ``RGB`` data.\n\nWhen the file is opened, only the first image is read. You can use\n:py:meth:`~PIL.Image.Image.seek` or :py:mod:`~PIL.ImageSequence` to read other images.\n\nFITS\n^^^^\n\n.. versionadded:: 9.1.0\n\nPillow identifies and reads FITS files, commonly used for astronomy. Uncompressed and\nGZIP_1 compressed images can be read.\n\nFLI, FLC\n^^^^^^^^\n\nPillow reads Autodesk FLI and FLC animations.\n\nThe :py:meth:`~PIL.Image.open` method sets the following\n:py:attr:`~PIL.Image.Image.info` properties:\n\n**duration**\n    The delay (in milliseconds) between each frame.\n\nFPX\n^^^\n\nPillow reads Kodak FlashPix files. Only the highest resolution image is read from the\nfile, and the viewing transform is not taken into account.\n\nTo enable FPX support, you must install :pypi:`olefile`.\n\n.. note::\n\n    To enable full FlashPix support, you need to build and install the IJG JPEG\n    library before building the Python Imaging Library. See the distribution\n    README for details.\n\nFTEX\n^^^^\n\n.. versionadded:: 3.2.0\n\nThe FTEX decoder reads textures used for 3D objects in\nIndependence War 2: Edge Of Chaos. The plugin reads a single texture\nper file, in the compressed and uncompressed formats.\n\nGBR\n^^^\n\nThe GBR decoder reads GIMP brush files, version 1 and 2.\n\n.. _gbr-opening:\n\nOpening\n~~~~~~~\n\nThe :py:meth:`~PIL.Image.open` method sets the following\n:py:attr:`~PIL.Image.Image.info` properties:\n\n**comment**\n    The brush name.\n\n**spacing**\n    The spacing between the brushes, in pixels. Version 2 only.\n\nGD\n^^\n\nPillow reads uncompressed GD2 files. Note that you must use\n:py:func:`PIL.GdImageFile.open` to read such a file.\n\n.. _gd-opening:\n\nOpening\n~~~~~~~\n\nThe :py:meth:`~PIL.Image.open` method sets the following\n:py:attr:`~PIL.Image.Image.info` properties:\n\n**transparency**\n    Transparency color index. This key is omitted if the image is not\n    transparent.\n\nIMT\n^^^\n\nPillow reads Image Tools images containing ``L`` data.\n\nIPTC/NAA\n^^^^^^^^\n\nPillow provides limited read support for IPTC/NAA newsphoto files.\n\nMCIDAS\n^^^^^^\n\nPillow identifies and reads 8-bit McIdas area files.\n\nMIC\n^^^\n\nPillow identifies and reads Microsoft Image Composer (MIC) files. When opened,\nthe first sprite in the file is loaded. You can use :py:meth:`~PIL.Image.Image.seek` and\n:py:meth:`~PIL.Image.Image.tell` to read other sprites from the file.\n\nNote that there may be an embedded gamma of 2.2 in MIC files.\n\nTo enable MIC support, you must install :pypi:`olefile`.\n\nMPO\n^^^\n\nPillow identifies and reads Multi Picture Object (MPO) files, loading the primary\nimage when first opened. The :py:meth:`~PIL.Image.Image.seek` and :py:meth:`~PIL.Image.Image.tell`\nmethods may be used to read other pictures from the file. The pictures are\nzero-indexed and random access is supported.\n\n.. _mpo-saving:\n\nSaving\n~~~~~~\n\nWhen calling :py:meth:`~PIL.Image.Image.save` to write an MPO file, by default\nonly the first frame of a multiframe image will be saved. If the ``save_all``\nargument is present and true, then all frames will be saved, and the following\noption will also be available.\n\n**append_images**\n    A list of images to append as additional pictures. Each of the\n    images in the list can be single or multiframe images.\n\n    .. versionadded:: 9.3.0\n\nPCD\n^^^\n\nPillow reads PhotoCD files containing ``RGB`` data. This only reads the 768x512\nresolution image from the file. Higher resolutions are encoded in a proprietary\nencoding.\n\nPIXAR\n^^^^^\n\nPillow provides limited support for PIXAR raster files. The library can\nidentify and read “dumped” RGB files.\n\nThe format code is ``PIXAR``.\n\nPSD\n^^^\n\nPillow identifies and reads PSD files written by Adobe Photoshop 2.5 and 3.0.\n\nQOI\n^^^\n\n.. versionadded:: 9.5.0\n\nPillow reads images in Quite OK Image format using a Python decoder. If you wish to\nwrite code specifically for this format, :pypi:`qoi` is an alternative library that\nuses C to decode the image and interfaces with NumPy.\n\nSUN\n^^^\n\nPillow identifies and reads Sun raster files.\n\nWAL\n^^^\n\n.. versionadded:: 1.1.4\n\nPillow reads Quake2 WAL texture files.\n\nNote that this file format cannot be automatically identified, so you must use\nthe open function in the :py:mod:`~PIL.WalImageFile` module to read files in\nthis format.\n\nBy default, a Quake2 standard palette is attached to the texture. To override\nthe palette, use the :py:func:`PIL.Image.Image.putpalette()` method.\n\nWMF, EMF\n^^^^^^^^\n\nPillow can identify WMF and EMF files.\n\nOn Windows, it can read WMF and EMF files. By default, it will load the image\nat 72 dpi. To load it at another resolution::\n\n    from PIL import Image\n\n    with Image.open(\"drawing.wmf\") as im:\n        im.load(dpi=144)\n\nTo add other read or write support, use\n:py:func:`PIL.WmfImagePlugin.register_handler` to register a WMF and EMF\nhandler. ::\n\n    from typing import IO\n\n    from PIL import Image, ImageFile\n    from PIL import WmfImagePlugin\n\n\n    class WmfHandler(ImageFile.StubHandler):\n        def open(self, im: ImageFile.StubImageFile) -> None:\n            ...\n\n        def load(self, im: ImageFile.StubImageFile) -> Image.Image:\n            ...\n            return image\n\n        def save(self, im: Image.Image, fp: IO[bytes], filename: str) -> None:\n            ...\n\n\n    wmf_handler = WmfHandler()\n\n    WmfImagePlugin.register_handler(wmf_handler)\n\n    im = Image.open(\"sample.wmf\")\n\nXPM\n^^^\n\nPillow reads X pixmap files (mode ``P``) with 256 colors or less.\n\n.. _xpm-opening:\n\nOpening\n~~~~~~~\n\nThe :py:meth:`~PIL.Image.open` method sets the following\n:py:attr:`~PIL.Image.Image.info` properties:\n\n**transparency**\n    Transparency color index. This key is omitted if the image is not\n    transparent.\n\nWrite-only formats\n------------------\n\nPALM\n^^^^\n\nPillow provides write-only support for PALM pixmap files.\n\nThe format code is ``Palm``, the extension is ``.palm``.\n\nPDF\n^^^\n\nPillow can write PDF (Acrobat) images. Such images are written as binary PDF 1.4\nfiles. Different encoding methods are used, depending on the image mode.\n\n* 1 mode images are saved using TIFF encoding, or JPEG encoding if libtiff support is\n  unavailable\n* L, RGB and CMYK mode images use JPEG encoding\n* P mode images use HEX encoding\n* LA and RGBA mode images use JPEG2000 encoding\n\n.. _pdf-saving:\n\nSaving\n~~~~~~\n\nThe :py:meth:`~PIL.Image.Image.save` method can take the following keyword arguments:\n\n**save_all**\n    If a multiframe image is used, by default, only the first image will be saved.\n    To save all frames, each frame to a separate page of the PDF, the ``save_all``\n    parameter must be present and set to ``True``.\n\n    .. versionadded:: 3.0.0\n\n**append_images**\n    A list of :py:class:`PIL.Image.Image` objects to append as additional pages. Each\n    of the images in the list can be single or multiframe images. The ``save_all``\n    parameter must be present and set to ``True`` in conjunction with\n    ``append_images``.\n\n    .. versionadded:: 4.2.0\n\n**append**\n    Set to True to append pages to an existing PDF file. If the file doesn't\n    exist, an :py:exc:`OSError` will be raised.\n\n    .. versionadded:: 5.1.0\n\n**resolution**\n    Image resolution in DPI. This, together with the number of pixels in the\n    image, will determine the physical dimensions of the page that will be\n    saved in the PDF.\n\n**dpi**\n    A tuple of ``(x_resolution, y_resolution)``, with inches as the resolution\n    unit. If both the ``resolution`` parameter and the ``dpi`` parameter are\n    present, ``resolution`` will be ignored.\n\n**title**\n    The document’s title. If not appending to an existing PDF file, this will\n    default to the filename.\n\n    .. versionadded:: 5.1.0\n\n**author**\n    The name of the person who created the document.\n\n    .. versionadded:: 5.1.0\n\n**subject**\n    The subject of the document.\n\n    .. versionadded:: 5.1.0\n\n**keywords**\n    Keywords associated with the document.\n\n    .. versionadded:: 5.1.0\n\n**creator**\n    If the document was converted to PDF from another format, the name of the\n    conforming product that created the original document from which it was\n    converted.\n\n    .. versionadded:: 5.1.0\n\n**producer**\n    If the document was converted to PDF from another format, the name of the\n    conforming product that converted it to PDF.\n\n    .. versionadded:: 5.1.0\n\n**creationDate**\n    The creation date of the document. If not appending to an existing PDF\n    file, this will default to the current time.\n\n    .. versionadded:: 5.3.0\n\n**modDate**\n    The modification date of the document. If not appending to an existing PDF\n    file, this will default to the current time.\n\n    .. versionadded:: 5.3.0\n\nXV Thumbnails\n^^^^^^^^^^^^^\n\nPillow can read XV thumbnail files.\n\nIdentify-only formats\n---------------------\n\nBUFR\n^^^^\n\n.. versionadded:: 1.1.3\n\nPillow provides a stub driver for BUFR files.\n\nTo add read or write support to your application, use\n:py:func:`PIL.BufrStubImagePlugin.register_handler`.\n\nGRIB\n^^^^\n\n.. versionadded:: 1.1.5\n\nPillow provides a stub driver for GRIB files.\n\nThe driver requires the file to start with a GRIB header. If you have files\nwith embedded GRIB data, or files with multiple GRIB fields, your application\nhas to seek to the header before passing the file handle to Pillow.\n\nTo add read or write support to your application, use\n:py:func:`PIL.GribStubImagePlugin.register_handler`.\n\nHDF5\n^^^^\n\n.. versionadded:: 1.1.5\n\nPillow provides a stub driver for HDF5 files.\n\nTo add read or write support to your application, use\n:py:func:`PIL.Hdf5StubImagePlugin.register_handler`.\n\nMPEG\n^^^^\n\nPillow identifies MPEG files.\n",
            "new_file_content": ".. _image-file-formats:\n\nImage file formats\n==================\n\nThe Python Imaging Library supports a wide variety of raster file formats.\nOver 30 different file formats can be identified and read by the library.\nWrite support is less extensive, but most common interchange and presentation\nformats are supported.\n\nThe :py:meth:`~PIL.Image.open` function identifies files from their\ncontents, not their names, but the :py:meth:`~PIL.Image.Image.save` method\nlooks at the name to determine which format to use, unless the format is given\nexplicitly.\n\nWhen an image is opened from a file, only that instance of the image is considered to\nhave the format. Copies of the image will contain data loaded from the file, but not\nthe file itself, meaning that it can no longer be considered to be in the original\nformat. So if :py:meth:`~PIL.Image.Image.copy` is called on an image, or another method\ninternally creates a copy of the image, then any methods or attributes specific to the\nformat will no longer be present. The ``fp`` (file pointer) attribute will no longer be\npresent, and the :py:attr:`~PIL.Image.Image.format` attribute will be ``None``.\n\nFully supported formats\n-----------------------\n\nBLP\n^^^\n\nBLP is the Blizzard Mipmap Format, a texture format used in World of\nWarcraft. Pillow supports reading ``JPEG`` Compressed or raw ``BLP1``\nimages, and all types of ``BLP2`` images.\n\nSaving\n~~~~~~\n\nPillow supports writing BLP images. The :py:meth:`~PIL.Image.Image.save` method\ncan take the following keyword arguments:\n\n**blp_version**\n    If present and set to \"BLP1\", images will be saved as BLP1. Otherwise, images\n    will be saved as BLP2.\n\nBMP\n^^^\n\nPillow reads and writes Windows and OS/2 BMP files containing ``1``, ``L``, ``P``,\nor ``RGB`` data. 16-colour images are read as ``P`` images.\nSupport for reading 8-bit run-length encoding was added in Pillow 9.1.0.\nSupport for reading 4-bit run-length encoding was added in Pillow 9.3.0.\n\nOpening\n~~~~~~~\n\nThe :py:meth:`~PIL.Image.open` method sets the following\n:py:attr:`~PIL.Image.Image.info` properties:\n\n**compression**\n    Set to 1 if the file is a 256-color run-length encoded image.\n    Set to 2 if the file is a 16-color run-length encoded image.\n\nDDS\n^^^\n\nDDS is a popular container texture format used in video games and natively supported\nby DirectX.\n\nDXT1 and DXT5 pixel formats can be read, only in ``RGBA`` mode.\n\n.. versionadded:: 3.4.0\n   DXT3 images can be read in ``RGB`` mode and DX10 images can be read in\n   ``RGB`` and ``RGBA`` mode.\n\n.. versionadded:: 6.0.0\n   Uncompressed ``RGBA`` images can be read.\n\n\n.. versionadded:: 8.3.0\n   BC5S images can be opened in ``RGB`` mode, and uncompressed ``RGB`` images\n   can be read. Uncompressed data can also be saved to image files.\n\n\n.. versionadded:: 9.3.0\n   ATI1 images can be opened in ``L`` mode and ATI2 images can be opened in\n   ``RGB`` mode.\n\n.. versionadded:: 9.4.0\n   Uncompressed ``L`` (\"luminance\") and ``LA`` images can be opened and saved.\n\n\n.. versionadded:: 10.1.0\n   BC5U can be read in ``RGB`` mode, and 8-bit color indexed images can be read\n   in ``P`` mode.\n\n\nDIB\n^^^\n\nPillow reads and writes DIB files. DIB files are similar to BMP files, so see\nabove for more information.\n\n    .. versionadded:: 6.0.0\n\nEPS\n^^^\n\nPillow identifies EPS files containing image data, and can read files that\ncontain embedded raster images (ImageData descriptors). If Ghostscript is\navailable, other EPS files can be read as well. The EPS driver can also write\nEPS images. The EPS driver can read EPS images in ``L``, ``LAB``, ``RGB`` and\n``CMYK`` mode, but Ghostscript may convert the images to ``RGB`` mode rather\nthan leaving them in the original color space. The EPS driver can write images\nin ``L``, ``RGB`` and ``CMYK`` modes.\n\nLoading\n~~~~~~~\n\nTo use Ghostscript, Pillow searches for the \"gs\" executable. On Windows, it\nalso searches for \"gswin32c\" and \"gswin64c\". To customise this behaviour,\n``EpsImagePlugin.gs_binary = \"gswin64\"`` will set the name of the executable to\nuse. ``EpsImagePlugin.gs_binary = False`` will prevent Ghostscript use.\n\nIf Ghostscript is available, you can call the :py:meth:`~PIL.Image.Image.load`\nmethod with the following parameters to affect how Ghostscript renders the EPS.\n\n**scale**\n    Affects the scale of the resultant rasterized image. If the EPS suggests\n    that the image be rendered at 100px x 100px, setting this parameter to\n    2 will make the Ghostscript render a 200px x 200px image instead. The\n    relative position of the bounding box is maintained::\n\n        im = Image.open(...)\n        im.size  # (100,100)\n        im.load(scale=2)\n        im.size  # (200,200)\n\n**transparency**\n    If true, generates an RGBA image with a transparent background, instead of\n    the default behaviour of an RGB image with a white background.\n\n\nGIF\n^^^\n\nPillow reads GIF87a and GIF89a versions of the GIF file format. The library\nwrites files in GIF87a by default, unless GIF89a features are used or GIF89a is\nalready in use. Files are written with LZW encoding.\n\nGIF files are initially read as grayscale (``L``) or palette mode (``P``)\nimages. Seeking to later frames in a ``P`` image will change the image to\n``RGB`` (or ``RGBA`` if the first frame had transparency).\n\n``P`` mode images are changed to ``RGB`` because each frame of a GIF may contain\nits own individual palette of up to 256 colors. When a new frame is placed onto a\nprevious frame, those colors may combine to exceed the ``P`` mode limit of 256\ncolors. Instead, the image is converted to ``RGB`` handle this.\n\nIf you would prefer the first ``P`` image frame to be ``RGB`` as well, so that\nevery ``P`` frame is converted to ``RGB`` or ``RGBA`` mode, there is a setting\navailable::\n\n    from PIL import GifImagePlugin\n    GifImagePlugin.LOADING_STRATEGY = GifImagePlugin.LoadingStrategy.RGB_ALWAYS\n\nGIF frames do not always contain individual palettes however. If there is only\na global palette, then all of the colors can fit within ``P`` mode. If you would\nprefer the frames to be kept as ``P`` in that case, there is also a setting\navailable::\n\n    from PIL import GifImagePlugin\n    GifImagePlugin.LOADING_STRATEGY = GifImagePlugin.LoadingStrategy.RGB_AFTER_DIFFERENT_PALETTE_ONLY\n\nTo restore the default behavior, where ``P`` mode images are only converted to\n``RGB`` or ``RGBA`` after the first frame::\n\n    from PIL import GifImagePlugin\n    GifImagePlugin.LOADING_STRATEGY = GifImagePlugin.LoadingStrategy.RGB_AFTER_FIRST\n\n.. _gif-opening:\n\nOpening\n~~~~~~~\n\nThe :py:meth:`~PIL.Image.open` method sets the following\n:py:attr:`~PIL.Image.Image.info` properties:\n\n**background**\n    Default background color (a palette color index).\n\n**transparency**\n    Transparency color index. This key is omitted if the image is not\n    transparent.\n\n**version**\n    Version (either ``GIF87a`` or ``GIF89a``).\n\n**duration**\n    May not be present. The time to display the current frame\n    of the GIF, in milliseconds.\n\n**loop**\n    May not be present. The number of times the GIF should loop. 0 means that\n    it will loop forever.\n\n**comment**\n    May not be present. A comment about the image. This is the last comment found\n    before the current frame's image.\n\n**extension**\n    May not be present. Contains application specific information.\n\nReading sequences\n~~~~~~~~~~~~~~~~~\n\nThe GIF loader supports the :py:meth:`~PIL.Image.Image.seek` and\n:py:meth:`~PIL.Image.Image.tell` methods. You can combine these methods\nto seek to the next frame (``im.seek(im.tell() + 1)``).\n\n``im.seek()`` raises an :py:exc:`EOFError` if you try to seek after the last frame.\n\n.. _gif-saving:\n\nSaving\n~~~~~~\n\nWhen calling :py:meth:`~PIL.Image.Image.save` to write a GIF file, the\nfollowing options are available::\n\n    im.save(out, save_all=True, append_images=[im1, im2, ...])\n\n**save_all**\n    If present and true, all frames of the image will be saved. If\n    not, then only the first frame of a multiframe image will be saved.\n\n**append_images**\n    A list of images to append as additional frames. Each of the\n    images in the list can be single or multiframe images.\n    This is currently supported for GIF, PDF, PNG, TIFF, and WebP.\n\n    It is also supported for ICO and ICNS. If images are passed in of relevant\n    sizes, they will be used instead of scaling down the main image.\n\n**include_color_table**\n    Whether or not to include local color table.\n\n**interlace**\n    Whether or not the image is interlaced. By default, it is, unless the image\n    is less than 16 pixels in width or height.\n\n**disposal**\n    Indicates the way in which the graphic is to be treated after being displayed.\n\n    * 0 - No disposal specified.\n    * 1 - Do not dispose.\n    * 2 - Restore to background color.\n    * 3 - Restore to previous content.\n\n     Pass a single integer for a constant disposal, or a list or tuple\n     to set the disposal for each frame separately.\n\n**palette**\n    Use the specified palette for the saved image. The palette should\n    be a bytes or bytearray object containing the palette entries in\n    RGBRGB... form. It should be no more than 768 bytes. Alternately,\n    the palette can be passed in as an\n    :py:class:`PIL.ImagePalette.ImagePalette` object.\n\n**optimize**\n    Whether to attempt to compress the palette by eliminating unused colors\n    (this is only useful if the palette can be compressed to the next smaller\n    power of 2 elements) and whether to mark all pixels that are not new in the\n    next frame as transparent.\n\n    This is attempted by default, unless a palette is specified as an option or\n    as part of the first image's :py:attr:`~PIL.Image.Image.info` dictionary.\n\nNote that if the image you are saving comes from an existing GIF, it may have\nthe following properties in its :py:attr:`~PIL.Image.Image.info` dictionary.\nFor these options, if you do not pass them in, they will default to\ntheir :py:attr:`~PIL.Image.Image.info` values.\n\n**transparency**\n    Transparency color index.\n\n**duration**\n    The display duration of each frame of the multiframe gif, in\n    milliseconds. Pass a single integer for a constant duration, or a\n    list or tuple to set the duration for each frame separately.\n\n**loop**\n    Integer number of times the GIF should loop. 0 means that it will loop\n    forever. If omitted or ``None``, the image will not loop.\n\n**comment**\n    A comment about the image.\n\nReading local images\n~~~~~~~~~~~~~~~~~~~~\n\nThe GIF loader creates an image memory the same size as the GIF file’s *logical\nscreen size*, and pastes the actual pixel data (the *local image*) into this\nimage. If you only want the actual pixel rectangle, you can crop the image::\n\n    im = Image.open(...)\n\n    if im.tile[0][0] == \"gif\":\n        # only read the first \"local image\" from this GIF file\n        box = im.tile[0][1]\n        im = im.crop(box)\n\nICNS\n^^^^\n\nPillow reads and writes macOS ``.icns`` files.  By default, the\nlargest available icon is read, though you can override this by setting the\n:py:attr:`~PIL.Image.Image.size` property before calling\n:py:meth:`~PIL.Image.Image.load`.  The :py:meth:`~PIL.Image.open` method\nsets the following :py:attr:`~PIL.Image.Image.info` property:\n\n.. note::\n\n    Prior to version 8.3.0, Pillow could only write ICNS files on macOS.\n\n**sizes**\n    A list of supported sizes found in this icon file; these are a\n    3-tuple, ``(width, height, scale)``, where ``scale`` is 2 for a retina\n    icon and 1 for a standard icon.  You *are* permitted to use this 3-tuple\n    format for the :py:attr:`~PIL.Image.Image.size` property if you set it\n    before calling :py:meth:`~PIL.Image.Image.load`; after loading, the size\n    will be reset to a 2-tuple containing pixel dimensions (so, e.g. if you\n    ask for ``(512, 512, 2)``, the final value of\n    :py:attr:`~PIL.Image.Image.size` will be ``(1024, 1024)``).\n\n.. _icns-loading:\n\nLoading\n~~~~~~~\n\nYou can call the :py:meth:`~PIL.Image.Image.load` method with the following parameter.\n\n**scale**\n    Affects the scale of the resultant image. If the size is set to ``(512, 512)``,\n    after loading at scale 2, the final value of :py:attr:`~PIL.Image.Image.size` will\n    be ``(1024, 1024)``.\n\n.. _icns-saving:\n\nSaving\n~~~~~~\n\nThe :py:meth:`~PIL.Image.Image.save` method can take the following keyword arguments:\n\n**append_images**\n    A list of images to replace the scaled down versions of the image.\n    The order of the images does not matter, as their use is determined by\n    the size of each image.\n\n    .. versionadded:: 5.1.0\n\nICO\n^^^\n\nICO is used to store icons on Windows. The largest available icon is read.\n\n.. _ico-saving:\n\nSaving\n~~~~~~\n\nThe :py:meth:`~PIL.Image.Image.save` method supports the following options:\n\n**sizes**\n    A list of sizes including in this ico file; these are a 2-tuple,\n    ``(width, height)``; Default to ``[(16, 16), (24, 24), (32, 32), (48, 48),\n    (64, 64), (128, 128), (256, 256)]``. Any sizes bigger than the original\n    size or 256 will be ignored.\n\nThe :py:meth:`~PIL.Image.Image.save` method can take the following keyword arguments:\n\n**append_images**\n    A list of images to replace the scaled down versions of the image.\n    The order of the images does not matter, as their use is determined by\n    the size of each image.\n\n    .. versionadded:: 8.1.0\n\n**bitmap_format**\n    By default, the image data will be saved in PNG format. With a bitmap format of\n    \"bmp\", image data will be saved in BMP format instead.\n\n    .. versionadded:: 8.3.0\n\nIM\n^^\n\nIM is a format used by LabEye and other applications based on the IFUNC image\nprocessing library. The library reads and writes most uncompressed interchange\nversions of this format.\n\nIM is the only format that can store all internal Pillow formats.\n\nJPEG\n^^^^\n\nPillow reads JPEG, JFIF, and Adobe JPEG files containing ``L``, ``RGB``, or\n``CMYK`` data. It writes standard and progressive JFIF files.\n\nUsing the :py:meth:`~PIL.Image.Image.draft` method, you can speed things up by\nconverting ``RGB`` images to ``L``, and resize images to 1/2, 1/4 or 1/8 of\ntheir original size while loading them.\n\nBy default Pillow doesn't allow loading of truncated JPEG files, set\n:data:`.ImageFile.LOAD_TRUNCATED_IMAGES` to override this.\n\n.. _jpeg-opening:\n\nOpening\n~~~~~~~\n\nThe :py:meth:`~PIL.Image.open` method may set the following\n:py:attr:`~PIL.Image.Image.info` properties if available:\n\n**jfif**\n    JFIF application marker found. If the file is not a JFIF file, this key is\n    not present.\n\n**jfif_version**\n    A tuple representing the jfif version, (major version, minor version).\n\n**jfif_density**\n    A tuple representing the pixel density of the image, in units specified\n    by jfif_unit.\n\n**jfif_unit**\n    Units for the jfif_density:\n\n    * 0 - No Units\n    * 1 - Pixels per Inch\n    * 2 - Pixels per Centimeter\n\n**dpi**\n    A tuple representing the reported pixel density in pixels per inch, if\n    the file is a jfif file and the units are in inches.\n\n**adobe**\n    Adobe application marker found. If the file is not an Adobe JPEG file, this\n    key is not present.\n\n**adobe_transform**\n    Vendor Specific Tag.\n\n**progression**\n    Indicates that this is a progressive JPEG file.\n\n**icc_profile**\n    The ICC color profile for the image.\n\n**exif**\n    Raw EXIF data from the image.\n\n**comment**\n    A comment about the image.\n\n    .. versionadded:: 7.1.0\n\n.. _jpeg-saving:\n\nSaving\n~~~~~~\n\nThe :py:meth:`~PIL.Image.Image.save` method supports the following options:\n\n**quality**\n    The image quality, on a scale from 0 (worst) to 95 (best), or the string\n    ``keep``. The default is 75. Values above 95 should be avoided; 100 disables\n    portions of the JPEG compression algorithm, and results in large files with\n    hardly any gain in image quality. The value ``keep`` is only valid for JPEG\n    files and will retain the original image quality level, subsampling, and\n    qtables.\n\n**optimize**\n    If present and true, indicates that the encoder should make an extra pass\n    over the image in order to select optimal encoder settings.\n\n**progressive**\n    If present and true, indicates that this image should be stored as a\n    progressive JPEG file.\n\n**dpi**\n    A tuple of integers representing the pixel density, ``(x,y)``.\n\n**icc_profile**\n    If present and true, the image is stored with the provided ICC profile.\n    If this parameter is not provided, the image will be saved with no profile\n    attached. To preserve the existing profile::\n\n        im.save(filename, 'jpeg', icc_profile=im.info.get('icc_profile'))\n\n**exif**\n    If present, the image will be stored with the provided raw EXIF data.\n\n**keep_rgb**\n    By default, libjpeg converts images with an RGB color space to YCbCr.\n    If this option is present and true, those images will be stored as RGB\n    instead.\n\n    When this option is enabled, attempting to chroma-subsample RGB images\n    with the ``subsampling`` option will raise an :py:exc:`OSError`.\n\n    .. versionadded:: 10.2.0\n\n**subsampling**\n    If present, sets the subsampling for the encoder.\n\n    * ``keep``: Only valid for JPEG files, will retain the original image setting.\n    * ``4:4:4``, ``4:2:2``, ``4:2:0``: Specific sampling values\n    * ``0``: equivalent to ``4:4:4``\n    * ``1``: equivalent to ``4:2:2``\n    * ``2``: equivalent to ``4:2:0``\n\n    If absent, the setting will be determined by libjpeg or libjpeg-turbo.\n\n**restart_marker_blocks**\n    If present, emit a restart marker whenever the specified number of MCU\n    blocks has been produced.\n\n    .. versionadded:: 10.2.0\n\n**restart_marker_rows**\n    If present, emit a restart marker whenever the specified number of MCU\n    rows has been produced.\n\n    .. versionadded:: 10.2.0\n\n**qtables**\n    If present, sets the qtables for the encoder. This is listed as an\n    advanced option for wizards in the JPEG documentation. Use with\n    caution. ``qtables`` can be one of several types of values:\n\n    *  a string, naming a preset, e.g. ``keep``, ``web_low``, or ``web_high``\n    *  a list, tuple, or dictionary (with integer keys =\n       range(len(keys))) of lists of 64 integers. There must be\n       between 2 and 4 tables.\n\n    .. versionadded:: 2.5.0\n\n**streamtype**\n    Allows storing images without quantization and Huffman tables, or with\n    these tables but without image data.  This is useful for container formats\n    or network protocols that handle tables separately and share them between\n    images.\n\n    * ``0`` (default): interchange datastream, with tables and image data\n    * ``1``: abbreviated table specification (tables-only) datastream\n\n      .. versionadded:: 10.2.0\n\n    * ``2``: abbreviated image (image-only) datastream\n\n**comment**\n    A comment about the image.\n\n    .. versionadded:: 9.4.0\n\n\n.. note::\n\n    To enable JPEG support, you need to build and install the IJG JPEG library\n    before building the Python Imaging Library. See the distribution README for\n    details.\n\nJPEG 2000\n^^^^^^^^^\n\n.. versionadded:: 2.4.0\n\nPillow reads and writes JPEG 2000 files containing ``L``, ``LA``, ``RGB``,\n``RGBA``, or ``YCbCr`` data.  When reading, ``YCbCr`` data is converted to\n``RGB`` or ``RGBA`` depending on whether or not there is an alpha channel.\nBeginning with version 8.3.0, Pillow can read (but not write) ``RGB``,\n``RGBA``, and ``YCbCr`` images with subsampled components.  Pillow supports\nJPEG 2000 raw codestreams (``.j2k`` files), as well as boxed JPEG 2000 files\n(``.jp2`` or ``.jpx`` files).\n\nWhen loading, if you set the ``mode`` on the image prior to the\n:py:meth:`~PIL.Image.Image.load` method being invoked, you can ask Pillow to\nconvert the image to either ``RGB`` or ``RGBA`` rather than choosing for\nitself.  It is also possible to set ``reduce`` to the number of resolutions to\ndiscard (each one reduces the size of the resulting image by a factor of 2),\nand ``layers`` to specify the number of quality layers to load.\n\n.. _jpeg-2000-saving:\n\nSaving\n~~~~~~\n\nThe :py:meth:`~PIL.Image.Image.save` method supports the following options:\n\n**offset**\n    The image offset, as a tuple of integers, e.g. (16, 16)\n\n**tile_offset**\n    The tile offset, again as a 2-tuple of integers.\n\n**tile_size**\n    The tile size as a 2-tuple.  If not specified, or if set to None, the\n    image will be saved without tiling.\n\n**quality_mode**\n    Either ``\"rates\"`` or ``\"dB\"`` depending on the units you want to use to\n    specify image quality.\n\n**quality_layers**\n    A sequence of numbers, each of which represents either an approximate size\n    reduction (if quality mode is ``\"rates\"``) or a signal to noise ratio value\n    in decibels.  If not specified, defaults to a single layer of full quality.\n\n**num_resolutions**\n    The number of different image resolutions to be stored (which corresponds\n    to the number of Discrete Wavelet Transform decompositions plus one).\n\n**codeblock_size**\n    The code-block size as a 2-tuple.  Minimum size is 4 x 4, maximum is 1024 x\n    1024, with the additional restriction that no code-block may have more\n    than 4096 coefficients (i.e. the product of the two numbers must be no\n    greater than 4096).\n\n**precinct_size**\n    The precinct size as a 2-tuple.  Must be a power of two along both axes,\n    and must be greater than the code-block size.\n\n**irreversible**\n    If ``True``, use the lossy discrete waveform transformation DWT 9-7.\n    Defaults to ``False``, which uses the lossless DWT 5-3.\n\n**mct**\n    If ``1`` then enable multiple component transformation when encoding,\n    otherwise use ``0`` for no component transformation (default). If MCT is\n    enabled and ``irreversible`` is ``True`` then the Irreversible Color\n    Transformation will be applied, otherwise encoding will use the\n    Reversible Color Transformation. MCT works best with a ``mode`` of\n    ``RGB`` and is only applicable when the image data has 3 components.\n\n    .. versionadded:: 9.1.0\n\n**progression**\n    Controls the progression order; must be one of ``\"LRCP\"``, ``\"RLCP\"``,\n    ``\"RPCL\"``, ``\"PCRL\"``, ``\"CPRL\"``.  The letters stand for Component,\n    Position, Resolution and Layer respectively and control the order of\n    encoding, the idea being that e.g. an image encoded using LRCP mode can\n    have its quality layers decoded as they arrive at the decoder, while one\n    encoded using RLCP mode will have increasing resolutions decoded as they\n    arrive, and so on.\n\n**signed**\n    If true, then tell the encoder to save the image as signed.\n\n    .. versionadded:: 9.4.0\n\n**cinema_mode**\n    Set the encoder to produce output compliant with the digital cinema\n    specifications.  The options here are ``\"no\"`` (the default),\n    ``\"cinema2k-24\"`` for 24fps 2K, ``\"cinema2k-48\"`` for 48fps 2K, and\n    ``\"cinema4k-24\"`` for 24fps 4K.  Note that for compliant 2K files,\n    *at least one* of your image dimensions must match 2048 x 1080, while\n    for compliant 4K files, *at least one* of the dimensions must match\n    4096 x 2160.\n\n**no_jp2**\n    If ``True`` then don't wrap the raw codestream in the JP2 file format when\n    saving, otherwise the extension of the filename will be used to determine\n    the format (default).\n\n    .. versionadded:: 9.1.0\n\n**comment**\n    Adds a custom comment to the file, replacing the default\n    \"Created by OpenJPEG version\" comment.\n\n    .. versionadded:: 9.5.0\n\n**plt**\n    If ``True`` and OpenJPEG 2.4.0 or later is available, then include a PLT\n    (packet length, tile-part header) marker in the produced file.\n    Defaults to ``False``.\n\n    .. versionadded:: 9.5.0\n\n.. note::\n\n   To enable JPEG 2000 support, you need to build and install the OpenJPEG\n   library, version 2.0.0 or higher, before building the Python Imaging\n   Library.\n\n   Windows users can install the OpenJPEG binaries available on the\n   OpenJPEG website, but must add them to their PATH in order to use Pillow (if\n   you fail to do this, you will get errors about not being able to load the\n   ``_imaging`` DLL).\n\nMSP\n^^^\n\nPillow identifies and reads MSP files from Windows 1 and 2. The library writes\nuncompressed (Windows 1) versions of this format.\n\nPCX\n^^^\n\nPillow reads and writes PCX files containing ``1``, ``L``, ``P``, or ``RGB`` data.\n\nPFM\n^^^\n\n.. versionadded:: 10.3.0\n\nPillow reads and writes grayscale (Pf format) Portable FloatMap (PFM) files\ncontaining ``F`` data.\n\nColor (PF format) PFM files are not supported.\n\nOpening\n~~~~~~~\n\nThe :py:func:`~PIL.Image.open` function sets the following\n:py:attr:`~PIL.Image.Image.info` properties:\n\n**scale**\n    The absolute value of the number stored in the *Scale Factor / Endianness* line.\n\nPNG\n^^^\n\nPillow identifies, reads, and writes PNG files containing ``1``, ``L``, ``LA``,\n``I``, ``P``, ``RGB`` or ``RGBA`` data. Interlaced files are supported as of\nv1.1.7.\n\nAs of Pillow 6.0, EXIF data can be read from PNG images. However, unlike other\nimage formats, EXIF data is not guaranteed to be present in\n:py:attr:`~PIL.Image.Image.info` until :py:meth:`~PIL.Image.Image.load` has been\ncalled.\n\nBy default Pillow doesn't allow loading of truncated PNG files, set\n:data:`.ImageFile.LOAD_TRUNCATED_IMAGES` to override this.\n\n.. _png-opening:\n\nOpening\n~~~~~~~\n\nThe :py:func:`~PIL.Image.open` function sets the following\n:py:attr:`~PIL.Image.Image.info` properties, when appropriate:\n\n**chromaticity**\n    The chromaticity points, as an 8 tuple of floats. (``White Point\n    X``, ``White Point Y``, ``Red X``, ``Red Y``, ``Green X``, ``Green\n    Y``, ``Blue X``, ``Blue Y``)\n\n**gamma**\n    Gamma, given as a floating point number.\n\n**srgb**\n    The sRGB rendering intent as an integer.\n\n      * 0 Perceptual\n      * 1 Relative Colorimetric\n      * 2 Saturation\n      * 3 Absolute Colorimetric\n\n**transparency**\n    For ``P`` images: Either the palette index for full transparent pixels,\n    or a byte string with alpha values for each palette entry.\n\n    For ``1``, ``L``, ``I`` and ``RGB`` images, the color that represents\n    full transparent pixels in this image.\n\n    This key is omitted if the image is not a transparent palette image.\n\n.. _png-text:\n\n``open`` also sets ``Image.text`` to a dictionary of the values of the\n``tEXt``, ``zTXt``, and ``iTXt`` chunks of the PNG image. Individual\ncompressed chunks are limited to a decompressed size of\n:data:`.PngImagePlugin.MAX_TEXT_CHUNK`, by default 1MB, to prevent\ndecompression bombs. Additionally, the total size of all of the text\nchunks is limited to :data:`.PngImagePlugin.MAX_TEXT_MEMORY`, defaulting to\n64MB.\n\n.. _png-saving:\n\nSaving\n~~~~~~\n\nThe :py:meth:`~PIL.Image.Image.save` method supports the following options:\n\n**optimize**\n    If present and true, instructs the PNG writer to make the output file as\n    small as possible. This includes extra processing in order to find optimal\n    encoder settings.\n\n**transparency**\n    For ``P``, ``1``, ``L``, ``I``, and ``RGB`` images, this option controls\n    what color from the image to mark as transparent.\n\n    For ``P`` images, this can be a either the palette index,\n    or a byte string with alpha values for each palette entry.\n\n**dpi**\n    A tuple of two numbers corresponding to the desired dpi in each direction.\n\n**pnginfo**\n    A :py:class:`PIL.PngImagePlugin.PngInfo` instance containing chunks.\n\n**compress_level**\n    ZLIB compression level, a number between 0 and 9: 1 gives best speed,\n    9 gives best compression, 0 gives no compression at all. Default is 6.\n    When ``optimize`` option is True ``compress_level`` has no effect\n    (it is set to 9 regardless of a value passed).\n\n**icc_profile**\n    The ICC Profile to include in the saved file.\n\n**exif**\n    The exif data to include in the saved file.\n\n    .. versionadded:: 6.0.0\n\n**bits (experimental)**\n    For ``P`` images, this option controls how many bits to store. If omitted,\n    the PNG writer uses 8 bits (256 colors).\n\n**dictionary (experimental)**\n    Set the ZLIB encoder dictionary.\n\n.. note::\n\n    To enable PNG support, you need to build and install the ZLIB compression\n    library before building the Python Imaging Library. See the\n    :doc:`installation documentation <../installation>` for details.\n\n.. _apng-sequences:\n\nAPNG sequences\n~~~~~~~~~~~~~~\n\nThe PNG loader includes limited support for reading and writing Animated Portable\nNetwork Graphics (APNG) files.\nWhen an APNG file is loaded, :py:meth:`~PIL.ImageFile.ImageFile.get_format_mimetype`\nwill return ``\"image/apng\"``. The value of the :py:attr:`~PIL.Image.Image.is_animated`\nproperty will be ``True`` when the :py:attr:`~PIL.Image.Image.n_frames` property is\ngreater than 1. For APNG files, the ``n_frames`` property depends on both the animation\nframe count as well as the presence or absence of a default image. See the\n``default_image`` property documentation below for more details.\nThe :py:meth:`~PIL.Image.Image.seek` and :py:meth:`~PIL.Image.Image.tell` methods\nare supported.\n\n``im.seek()`` raises an :py:exc:`EOFError` if you try to seek after the last frame.\n\nThese :py:attr:`~PIL.Image.Image.info` properties will be set for APNG frames,\nwhere applicable:\n\n**default_image**\n    Specifies whether or not this APNG file contains a separate default image,\n    which is not a part of the actual APNG animation.\n\n    When an APNG file contains a default image, the initially loaded image (i.e.\n    the result of ``seek(0)``) will be the default image.\n    To account for the presence of the default image, the\n    :py:attr:`~PIL.Image.Image.n_frames` property will be set to ``frame_count + 1``,\n    where ``frame_count`` is the actual APNG animation frame count.\n    To load the first APNG animation frame, ``seek(1)`` must be called.\n\n    * ``True`` - The APNG contains default image, which is not an animation frame.\n    * ``False`` - The APNG does not contain a default image. The ``n_frames`` property\n      will be set to the actual APNG animation frame count.\n      The initially loaded image (i.e. ``seek(0)``) will be the first APNG animation\n      frame.\n\n**loop**\n    The number of times to loop this APNG, 0 indicates infinite looping.\n\n**duration**\n    The time to display this APNG frame (in milliseconds).\n\n.. note::\n\n    The APNG loader returns images the same size as the APNG file's logical screen size.\n    The returned image contains the pixel data for a given frame, after applying\n    any APNG frame disposal and frame blend operations (i.e. it contains what a web\n    browser would render for this frame - the composite of all previous frames and this\n    frame).\n\n    Any APNG file containing sequence errors is treated as an invalid image. The APNG\n    loader will not attempt to repair and reorder files containing sequence errors.\n\n.. _apng-saving:\n\nSaving\n~~~~~~\n\nWhen calling :py:meth:`~PIL.Image.Image.save`, by default only a single frame PNG file\nwill be saved. To save an APNG file (including a single frame APNG), the ``save_all``\nparameter must be set to ``True``. The following parameters can also be set:\n\n**default_image**\n    Boolean value, specifying whether or not the base image is a default image.\n    If ``True``, the base image will be used as the default image, and the first image\n    from the ``append_images`` sequence will be the first APNG animation frame.\n    If ``False``, the base image will be used as the first APNG animation frame.\n    Defaults to ``False``.\n\n**append_images**\n    A list or tuple of images to append as additional frames. Each of the\n    images in the list can be single or multiframe images. The size of each frame\n    should match the size of the base image. Also note that if a frame's mode does\n    not match that of the base image, the frame will be converted to the base image\n    mode.\n\n**loop**\n    Integer number of times to loop this APNG, 0 indicates infinite looping.\n    Defaults to 0.\n\n**duration**\n    Integer (or list or tuple of integers) length of time to display this APNG frame\n    (in milliseconds).\n    Defaults to 0.\n\n**disposal**\n    An integer (or list or tuple of integers) specifying the APNG disposal\n    operation to be used for this frame before rendering the next frame.\n    Defaults to 0.\n\n    * 0 (:py:data:`~PIL.PngImagePlugin.Disposal.OP_NONE`, default) -\n      No disposal is done on this frame before rendering the next frame.\n    * 1 (:py:data:`PIL.PngImagePlugin.Disposal.OP_BACKGROUND`) -\n      This frame's modified region is cleared to fully transparent black before\n      rendering the next frame.\n    * 2 (:py:data:`~PIL.PngImagePlugin.Disposal.OP_PREVIOUS`) -\n      This frame's modified region is reverted to the previous frame's contents before\n      rendering the next frame.\n\n**blend**\n    An integer (or list or tuple of integers) specifying the APNG blend\n    operation to be used for this frame before rendering the next frame.\n    Defaults to 0.\n\n    * 0 (:py:data:`~PIL.PngImagePlugin.Blend.OP_SOURCE`) -\n      All color components of this frame, including alpha, overwrite the previous output\n      image contents.\n    * 1 (:py:data:`~PIL.PngImagePlugin.Blend.OP_OVER`) -\n      This frame should be alpha composited with the previous output image contents.\n\n.. note::\n\n    The ``duration``, ``disposal`` and ``blend`` parameters can be set to lists or tuples to\n    specify values for each individual frame in the animation. The length of the list or tuple\n    must be identical to the total number of actual frames in the APNG animation.\n    If the APNG contains a default image (i.e. ``default_image`` is set to ``True``),\n    these list or tuple parameters should not include an entry for the default image.\n\n\nPPM\n^^^\n\nPillow reads and writes PBM, PGM, PPM and PNM files containing ``1``, ``L``, ``I`` or\n``RGB`` data.\n\n\"Raw\" (P4 to P6) formats can be read, and are used when writing.\n\nSince Pillow 9.2.0, \"plain\" (P1 to P3) formats can be read as well.\n\nSGI\n^^^\n\nPillow reads and writes uncompressed ``L``, ``RGB``, and ``RGBA`` files.\n\n\nSPIDER\n^^^^^^\n\nPillow reads and writes SPIDER image files of 32-bit floating point data\n(\"F;32F\").\n\nPillow also reads SPIDER stack files containing sequences of SPIDER images. The\n:py:meth:`~PIL.Image.Image.seek` and :py:meth:`~PIL.Image.Image.tell` methods are supported, and\nrandom access is allowed.\n\n.. _spider-opening:\n\nOpening\n~~~~~~~\n\nThe :py:meth:`~PIL.Image.open` method sets the following attributes:\n\n**format**\n    Set to ``SPIDER``\n\n**istack**\n    Set to 1 if the file is an image stack, else 0.\n\n**n_frames**\n    Set to the number of images in the stack.\n\nA convenience method, :py:meth:`~PIL.SpiderImagePlugin.SpiderImageFile.convert2byte`,\nis provided for converting floating point data to byte data (mode ``L``)::\n\n    im = Image.open(\"image001.spi\").convert2byte()\n\n.. _spider-saving:\n\nSaving\n~~~~~~\n\nThe extension of SPIDER files may be any 3 alphanumeric characters. Therefore\nthe output format must be specified explicitly::\n\n    im.save('newimage.spi', format='SPIDER')\n\nFor more information about the SPIDER image processing package, see\nhttps://github.com/spider-em/SPIDER\n\nTGA\n^^^\n\nPillow reads and writes TGA images containing ``L``, ``LA``, ``P``,\n``RGB``, and ``RGBA`` data. Pillow can read and write both uncompressed and\nrun-length encoded TGAs.\n\n.. _tga-saving:\n\nSaving\n~~~~~~\n\nThe :py:meth:`~PIL.Image.Image.save` method can take the following keyword arguments:\n\n**compression**\n    If set to \"tga_rle\", the file will be run-length encoded.\n\n    .. versionadded:: 5.3.0\n\n**id_section**\n    The identification field.\n\n    .. versionadded:: 5.3.0\n\n**orientation**\n    If present and a positive number, the first pixel is for the top left corner,\n    rather than the bottom left corner.\n\n    .. versionadded:: 5.3.0\n\nTIFF\n^^^^\n\nPillow reads and writes TIFF files. It can read both striped and tiled\nimages, pixel and plane interleaved multi-band images. If you have\nlibtiff and its headers installed, Pillow can read and write many kinds\nof compressed TIFF files. If not, Pillow will only read and write\nuncompressed files.\n\n.. note::\n\n    Beginning in version 5.0.0, Pillow requires libtiff to read or\n    write compressed files. Prior to that release, Pillow had buggy\n    support for reading Packbits, LZW and JPEG compressed TIFFs\n    without using libtiff.\n\n.. _tiff-opening:\n\nOpening\n~~~~~~~\n\nThe :py:meth:`~PIL.Image.open` method sets the following\n:py:attr:`~PIL.Image.Image.info` properties:\n\n**compression**\n    Compression mode.\n\n    .. versionadded:: 2.0.0\n\n**dpi**\n    Image resolution as an ``(xdpi, ydpi)`` tuple, where applicable. You can use\n    the :py:attr:`~PIL.TiffImagePlugin.TiffImageFile.tag` attribute to get more\n    detailed information about the image resolution.\n\n    .. versionadded:: 1.1.5\n\n**resolution**\n    Image resolution as an ``(xres, yres)`` tuple, where applicable. This is a\n    measurement in whichever unit is specified by the file.\n\n    .. versionadded:: 1.1.5\n\n\nThe :py:attr:`~PIL.TiffImagePlugin.TiffImageFile.tag_v2` attribute contains a\ndictionary of TIFF metadata. The keys are numerical indexes from\n:py:data:`.TiffTags.TAGS_V2`.  Values are strings or numbers for single\nitems, multiple values are returned in a tuple of values. Rational\nnumbers are returned as a :py:class:`~PIL.TiffImagePlugin.IFDRational`\nobject.\n\n    .. versionadded:: 3.0.0\n\nFor compatibility with legacy code, the\n:py:attr:`~PIL.TiffImagePlugin.TiffImageFile.tag` attribute contains a dictionary\nof decoded TIFF fields as returned prior to version 3.0.0.  Values are\nreturned as either strings or tuples of numeric values. Rational\nnumbers are returned as a tuple of ``(numerator, denominator)``.\n\n    .. deprecated:: 3.0.0\n\nReading Multi-frame TIFF Images\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThe TIFF loader supports the :py:meth:`~PIL.Image.Image.seek` and\n:py:meth:`~PIL.Image.Image.tell` methods, taking and returning frame numbers\nwithin the image file. You can combine these methods to seek to the next frame\n(``im.seek(im.tell() + 1)``). Frames are numbered from 0 to ``im.n_frames - 1``,\nand can be accessed in any order.\n\n``im.seek()`` raises an :py:exc:`EOFError` if you try to seek after the\nlast frame.\n\n.. _tiff-saving:\n\nSaving\n~~~~~~\n\nThe :py:meth:`~PIL.Image.Image.save` method can take the following keyword arguments:\n\n**save_all**\n    If true, Pillow will save all frames of the image to a multiframe tiff document.\n\n    .. versionadded:: 3.4.0\n\n**append_images**\n    A list of images to append as additional frames. Each of the\n    images in the list can be single or multiframe images. Note however, that for\n    correct results, all the appended images should have the same\n    ``encoderinfo`` and ``encoderconfig`` properties.\n\n    .. versionadded:: 4.2.0\n\n**tiffinfo**\n    A :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2` object or dict\n    object containing tiff tags and values. The TIFF field type is\n    autodetected for Numeric and string values, any other types\n    require using an :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`\n    object and setting the type in\n    :py:attr:`~PIL.TiffImagePlugin.ImageFileDirectory_v2.tagtype` with\n    the appropriate numerical value from\n    :py:data:`.TiffTags.TYPES`.\n\n    .. versionadded:: 2.3.0\n\n    Metadata values that are of the rational type should be passed in\n    using a :py:class:`~PIL.TiffImagePlugin.IFDRational` object.\n\n    .. versionadded:: 3.1.0\n\n    For compatibility with legacy code, a\n    :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1` object may\n    be passed in this field. However, this is deprecated.\n\n    .. versionadded:: 5.4.0\n\n    Previous versions only supported some tags when writing using\n    libtiff. The supported list is found in\n    :py:data:`.TiffTags.LIBTIFF_CORE`.\n\n    .. versionadded:: 6.1.0\n\n    Added support for signed types (e.g. ``TIFF_SIGNED_LONG``) and multiple values.\n    Multiple values for a single tag must be to\n    :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2` as a tuple and\n    require a matching type in\n    :py:attr:`~PIL.TiffImagePlugin.ImageFileDirectory_v2.tagtype` tagtype.\n\n**exif**\n    Alternate keyword to \"tiffinfo\", for consistency with other formats.\n\n    .. versionadded:: 8.4.0\n\n**compression**\n    A string containing the desired compression method for the\n    file. (valid only with libtiff installed) Valid compression\n    methods are: :data:`None`, ``\"group3\"``, ``\"group4\"``, ``\"jpeg\"``, ``\"lzma\"``,\n    ``\"packbits\"``, ``\"tiff_adobe_deflate\"``, ``\"tiff_ccitt\"``, ``\"tiff_lzw\"``,\n    ``\"tiff_raw_16\"``, ``\"tiff_sgilog\"``, ``\"tiff_sgilog24\"``, ``\"tiff_thunderscan\"``,\n    ``\"webp\"``, ``\"zstd\"``\n\n**quality**\n    The image quality for JPEG compression, on a scale from 0 (worst) to 100\n    (best). The default is 75.\n\n    .. versionadded:: 6.1.0\n\nThese arguments to set the tiff header fields are an alternative to\nusing the general tags available through tiffinfo.\n\n**description**\n\n**software**\n\n**date_time**\n\n**artist**\n\n**copyright**\n    Strings\n\n**icc_profile**\n    The ICC Profile to include in the saved file.\n\n**resolution_unit**\n    An integer. 1 for no unit, 2 for inches and 3 for centimeters.\n\n**resolution**\n    Either an integer or a float, used for both the x and y resolution.\n\n**x_resolution**\n    Either an integer or a float.\n\n**y_resolution**\n    Either an integer or a float.\n\n**dpi**\n    A tuple of ``(x_resolution, y_resolution)``, with inches as the resolution\n    unit. For consistency with other image formats, the x and y resolutions\n    of the dpi will be rounded to the nearest integer.\n\n\nWebP\n^^^^\n\nPillow reads and writes WebP files. Requires libwebp v0.5.0 or later.\n\n.. _webp-saving:\n\nSaving\n~~~~~~\n\nThe :py:meth:`~PIL.Image.Image.save` method supports the following options:\n\n**lossless**\n    If present and true, instructs the WebP writer to use lossless compression.\n\n**quality**\n    Integer, 0-100, defaults to 80. For lossy, 0 gives the smallest\n    size and 100 the largest. For lossless, this parameter is the amount\n    of effort put into the compression: 0 is the fastest, but gives larger\n    files compared to the slowest, but best, 100.\n\n**alpha_quality**\n    Integer, 0-100, defaults to 100. For lossy compression only. 0 gives the\n    smallest size and 100 is lossless.\n\n**method**\n    Quality/speed trade-off (0=fast, 6=slower-better). Defaults to 4.\n\n**exact**\n    If true, preserve the transparent RGB values. Otherwise, discard\n    invisible RGB values for better compression. Defaults to false.\n\n**icc_profile**\n    The ICC Profile to include in the saved file.\n\n**exif**\n    The exif data to include in the saved file.\n\n**xmp**\n    The XMP data to include in the saved file.\n\nSaving sequences\n~~~~~~~~~~~~~~~~\n\nWhen calling :py:meth:`~PIL.Image.Image.save` to write a WebP file, by default\nonly the first frame of a multiframe image will be saved. If the ``save_all``\nargument is present and true, then all frames will be saved, and the following\noptions will also be available.\n\n**append_images**\n    A list of images to append as additional frames. Each of the\n    images in the list can be single or multiframe images.\n\n**duration**\n    The display duration of each frame, in milliseconds. Pass a single\n    integer for a constant duration, or a list or tuple to set the\n    duration for each frame separately.\n\n**loop**\n    Number of times to repeat the animation. Defaults to [0 = infinite].\n\n**background**\n    Background color of the canvas, as an RGBA tuple with values in\n    the range of (0-255).\n\n**minimize_size**\n    If true, minimize the output size (slow). Implicitly disables\n    key-frame insertion.\n\n**kmin, kmax**\n    Minimum and maximum distance between consecutive key frames in\n    the output. The library may insert some key frames as needed\n    to satisfy this criteria. Note that these conditions should\n    hold: kmax > kmin and kmin >= kmax / 2 + 1. Also, if kmax <= 0,\n    then key-frame insertion is disabled; and if kmax == 1, then all\n    frames will be key-frames (kmin value does not matter for these\n    special cases).\n\n**allow_mixed**\n    If true, use mixed compression mode; the encoder heuristically\n    chooses between lossy and lossless for each frame.\n\nXBM\n^^^\n\nPillow reads and writes X bitmap files (mode ``1``).\n\nRead-only formats\n-----------------\n\nCUR\n^^^\n\nCUR is used to store cursors on Windows. The CUR decoder reads the largest\navailable cursor. Animated cursors are not supported.\n\nDCX\n^^^\n\nDCX is a container file format for PCX files, defined by Intel. The DCX format\nis commonly used in fax applications. The DCX decoder can read files containing\n``1``, ``L``, ``P``, or ``RGB`` data.\n\nWhen the file is opened, only the first image is read. You can use\n:py:meth:`~PIL.Image.Image.seek` or :py:mod:`~PIL.ImageSequence` to read other images.\n\nFITS\n^^^^\n\n.. versionadded:: 9.1.0\n\nPillow identifies and reads FITS files, commonly used for astronomy. Uncompressed and\nGZIP_1 compressed images can be read.\n\nFLI, FLC\n^^^^^^^^\n\nPillow reads Autodesk FLI and FLC animations.\n\nThe :py:meth:`~PIL.Image.open` method sets the following\n:py:attr:`~PIL.Image.Image.info` properties:\n\n**duration**\n    The delay (in milliseconds) between each frame.\n\nFPX\n^^^\n\nPillow reads Kodak FlashPix files. Only the highest resolution image is read from the\nfile, and the viewing transform is not taken into account.\n\nTo enable FPX support, you must install :pypi:`olefile`.\n\n.. note::\n\n    To enable full FlashPix support, you need to build and install the IJG JPEG\n    library before building the Python Imaging Library. See the distribution\n    README for details.\n\nFTEX\n^^^^\n\n.. versionadded:: 3.2.0\n\nThe FTEX decoder reads textures used for 3D objects in\nIndependence War 2: Edge Of Chaos. The plugin reads a single texture\nper file, in the compressed and uncompressed formats.\n\nGBR\n^^^\n\nThe GBR decoder reads GIMP brush files, version 1 and 2.\n\n.. _gbr-opening:\n\nOpening\n~~~~~~~\n\nThe :py:meth:`~PIL.Image.open` method sets the following\n:py:attr:`~PIL.Image.Image.info` properties:\n\n**comment**\n    The brush name.\n\n**spacing**\n    The spacing between the brushes, in pixels. Version 2 only.\n\nGD\n^^\n\nPillow reads uncompressed GD2 files. Note that you must use\n:py:func:`PIL.GdImageFile.open` to read such a file.\n\n.. _gd-opening:\n\nOpening\n~~~~~~~\n\nThe :py:meth:`~PIL.Image.open` method sets the following\n:py:attr:`~PIL.Image.Image.info` properties:\n\n**transparency**\n    Transparency color index. This key is omitted if the image is not\n    transparent.\n\nIMT\n^^^\n\nPillow reads Image Tools images containing ``L`` data.\n\nIPTC/NAA\n^^^^^^^^\n\nPillow provides limited read support for IPTC/NAA newsphoto files.\n\nMCIDAS\n^^^^^^\n\nPillow identifies and reads 8-bit McIdas area files.\n\nMIC\n^^^\n\nPillow identifies and reads Microsoft Image Composer (MIC) files. When opened,\nthe first sprite in the file is loaded. You can use :py:meth:`~PIL.Image.Image.seek` and\n:py:meth:`~PIL.Image.Image.tell` to read other sprites from the file.\n\nNote that there may be an embedded gamma of 2.2 in MIC files.\n\nTo enable MIC support, you must install :pypi:`olefile`.\n\nMPO\n^^^\n\nPillow identifies and reads Multi Picture Object (MPO) files, loading the primary\nimage when first opened. The :py:meth:`~PIL.Image.Image.seek` and :py:meth:`~PIL.Image.Image.tell`\nmethods may be used to read other pictures from the file. The pictures are\nzero-indexed and random access is supported.\n\n.. _mpo-saving:\n\nSaving\n~~~~~~\n\nWhen calling :py:meth:`~PIL.Image.Image.save` to write an MPO file, by default\nonly the first frame of a multiframe image will be saved. If the ``save_all``\nargument is present and true, then all frames will be saved, and the following\noption will also be available.\n\n**append_images**\n    A list of images to append as additional pictures. Each of the\n    images in the list can be single or multiframe images.\n\n    .. versionadded:: 9.3.0\n\nPCD\n^^^\n\nPillow reads PhotoCD files containing ``RGB`` data. This only reads the 768x512\nresolution image from the file. Higher resolutions are encoded in a proprietary\nencoding.\n\nPIXAR\n^^^^^\n\nPillow provides limited support for PIXAR raster files. The library can\nidentify and read “dumped” RGB files.\n\nThe format code is ``PIXAR``.\n\nPSD\n^^^\n\nPillow identifies and reads PSD files written by Adobe Photoshop 2.5 and 3.0.\n\nQOI\n^^^\n\n.. versionadded:: 9.5.0\n\nPillow reads images in Quite OK Image format using a Python decoder. If you wish to\nwrite code specifically for this format, :pypi:`qoi` is an alternative library that\nuses C to decode the image and interfaces with NumPy.\n\nSUN\n^^^\n\nPillow identifies and reads Sun raster files.\n\nWAL\n^^^\n\n.. versionadded:: 1.1.4\n\nPillow reads Quake2 WAL texture files.\n\nNote that this file format cannot be automatically identified, so you must use\nthe open function in the :py:mod:`~PIL.WalImageFile` module to read files in\nthis format.\n\nBy default, a Quake2 standard palette is attached to the texture. To override\nthe palette, use the :py:func:`PIL.Image.Image.putpalette()` method.\n\nWMF, EMF\n^^^^^^^^\n\nPillow can identify WMF and EMF files.\n\nOn Windows, it can read WMF and EMF files. By default, it will load the image\nat 72 dpi. To load it at another resolution::\n\n    from PIL import Image\n\n    with Image.open(\"drawing.wmf\") as im:\n        im.load(dpi=144)\n\nTo add other read or write support, use\n:py:func:`PIL.WmfImagePlugin.register_handler` to register a WMF and EMF\nhandler. ::\n\n    from typing import IO\n\n    from PIL import Image, ImageFile\n    from PIL import WmfImagePlugin\n\n\n    class WmfHandler(ImageFile.StubHandler):\n        def open(self, im: ImageFile.StubImageFile) -> None:\n            ...\n\n        def load(self, im: ImageFile.StubImageFile) -> Image.Image:\n            ...\n            return image\n\n        def save(self, im: Image.Image, fp: IO[bytes], filename: str) -> None:\n            ...\n\n\n    wmf_handler = WmfHandler()\n\n    WmfImagePlugin.register_handler(wmf_handler)\n\n    im = Image.open(\"sample.wmf\")\n\nXPM\n^^^\n\nPillow reads X pixmap files (mode ``P``) with 256 colors or less.\n\n.. _xpm-opening:\n\nOpening\n~~~~~~~\n\nThe :py:meth:`~PIL.Image.open` method sets the following\n:py:attr:`~PIL.Image.Image.info` properties:\n\n**transparency**\n    Transparency color index. This key is omitted if the image is not\n    transparent.\n\nWrite-only formats\n------------------\n\nPALM\n^^^^\n\nPillow provides write-only support for PALM pixmap files.\n\nThe format code is ``Palm``, the extension is ``.palm``.\n\nPDF\n^^^\n\nPillow can write PDF (Acrobat) images. Such images are written as binary PDF 1.4\nfiles. Different encoding methods are used, depending on the image mode.\n\n* 1 mode images are saved using TIFF encoding, or JPEG encoding if libtiff support is\n  unavailable\n* L, RGB and CMYK mode images use JPEG encoding\n* P mode images use HEX encoding\n* LA and RGBA mode images use JPEG2000 encoding\n\n.. _pdf-saving:\n\nSaving\n~~~~~~\n\nThe :py:meth:`~PIL.Image.Image.save` method can take the following keyword arguments:\n\n**save_all**\n    If a multiframe image is used, by default, only the first image will be saved.\n    To save all frames, each frame to a separate page of the PDF, the ``save_all``\n    parameter must be present and set to ``True``.\n\n    .. versionadded:: 3.0.0\n\n**append_images**\n    A list of :py:class:`PIL.Image.Image` objects to append as additional pages. Each\n    of the images in the list can be single or multiframe images. The ``save_all``\n    parameter must be present and set to ``True`` in conjunction with\n    ``append_images``.\n\n    .. versionadded:: 4.2.0\n\n**append**\n    Set to True to append pages to an existing PDF file. If the file doesn't\n    exist, an :py:exc:`OSError` will be raised.\n\n    .. versionadded:: 5.1.0\n\n**resolution**\n    Image resolution in DPI. This, together with the number of pixels in the\n    image, will determine the physical dimensions of the page that will be\n    saved in the PDF.\n\n**dpi**\n    A tuple of ``(x_resolution, y_resolution)``, with inches as the resolution\n    unit. If both the ``resolution`` parameter and the ``dpi`` parameter are\n    present, ``resolution`` will be ignored.\n\n**title**\n    The document’s title. If not appending to an existing PDF file, this will\n    default to the filename.\n\n    .. versionadded:: 5.1.0\n\n**author**\n    The name of the person who created the document.\n\n    .. versionadded:: 5.1.0\n\n**subject**\n    The subject of the document.\n\n    .. versionadded:: 5.1.0\n\n**keywords**\n    Keywords associated with the document.\n\n    .. versionadded:: 5.1.0\n\n**creator**\n    If the document was converted to PDF from another format, the name of the\n    conforming product that created the original document from which it was\n    converted.\n\n    .. versionadded:: 5.1.0\n\n**producer**\n    If the document was converted to PDF from another format, the name of the\n    conforming product that converted it to PDF.\n\n    .. versionadded:: 5.1.0\n\n**creationDate**\n    The creation date of the document. If not appending to an existing PDF\n    file, this will default to the current time.\n\n    .. versionadded:: 5.3.0\n\n**modDate**\n    The modification date of the document. If not appending to an existing PDF\n    file, this will default to the current time.\n\n    .. versionadded:: 5.3.0\n\nXV Thumbnails\n^^^^^^^^^^^^^\n\nPillow can read XV thumbnail files.\n\nIdentify-only formats\n---------------------\n\nBUFR\n^^^^\n\n.. versionadded:: 1.1.3\n\nPillow provides a stub driver for BUFR files.\n\nTo add read or write support to your application, use\n:py:func:`PIL.BufrStubImagePlugin.register_handler`.\n\nGRIB\n^^^^\n\n.. versionadded:: 1.1.5\n\nPillow provides a stub driver for GRIB files.\n\nThe driver requires the file to start with a GRIB header. If you have files\nwith embedded GRIB data, or files with multiple GRIB fields, your application\nhas to seek to the header before passing the file handle to Pillow.\n\nTo add read or write support to your application, use\n:py:func:`PIL.GribStubImagePlugin.register_handler`.\n\nHDF5\n^^^^\n\n.. versionadded:: 1.1.5\n\nPillow provides a stub driver for HDF5 files.\n\nTo add read or write support to your application, use\n:py:func:`PIL.Hdf5StubImagePlugin.register_handler`.\n\nMPEG\n^^^^\n\nPillow identifies MPEG files.\n",
            "header": {
                "file": {
                    "path": "docs/handbook/image-file-formats.rst"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "ca0e05eb6",
                "new_commit_hash": "a5fbc8053",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/docs/handbook/image-file-formats.rst"
            },
            "plus_file": {
                "path": "b/docs/handbook/image-file-formats.rst"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 331,
                            "length": 6
                        },
                        "new_range": {
                            "start": 331,
                            "length": 18
                        },
                        "section": "sets the following :py:attr:`~PIL.Image.Image.info` property:"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "    ask for ``(512, 512, 2)``, the final value of",
                                "type": "context"
                            },
                            {
                                "content": "    :py:attr:`~PIL.Image.Image.size` will be ``(1024, 1024)``).",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": ".. _icns-loading:",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "Loading",
                                "type": "added"
                            },
                            {
                                "content": "~~~~~~~",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "You can call the :py:meth:`~PIL.Image.Image.load` method with the following parameter.",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "**scale**",
                                "type": "added"
                            },
                            {
                                "content": "    Affects the scale of the resultant image. If the size is set to ``(512, 512)``,",
                                "type": "added"
                            },
                            {
                                "content": "    after loading at scale 2, the final value of :py:attr:`~PIL.Image.Image.size` will",
                                "type": "added"
                            },
                            {
                                "content": "    be ``(1024, 1024)``.",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": ".. _icns-saving:",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "Saving",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "#\n# The Python Imaging Library.\n# $Id$\n#\n# macOS icns file decoder, based on icns.py by Bob Ippolito.\n#\n# history:\n# 2004-10-09 fl   Turned into a PIL plugin; removed 2.3 dependencies.\n# 2020-04-04      Allow saving on all operating systems.\n#\n# Copyright (c) 2004 by Bob Ippolito.\n# Copyright (c) 2004 by Secret Labs.\n# Copyright (c) 2004 by Fredrik Lundh.\n# Copyright (c) 2014 by Alastair Houghton.\n# Copyright (c) 2020 by Pan Jing.\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nimport io\nimport os\nimport struct\nimport sys\nfrom typing import IO\n\nfrom . import Image, ImageFile, PngImagePlugin, features\n\nenable_jpeg2k = features.check_codec(\"jpg_2000\")\nif enable_jpeg2k:\n    from . import Jpeg2KImagePlugin\n\nMAGIC = b\"icns\"\nHEADERSIZE = 8\n\n\ndef nextheader(fobj: IO[bytes]) -> tuple[bytes, int]:\n    return struct.unpack(\">4sI\", fobj.read(HEADERSIZE))\n\n\ndef read_32t(\n    fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int]\n) -> dict[str, Image.Image]:\n    # The 128x128 icon seems to have an extra header for some reason.\n    (start, length) = start_length\n    fobj.seek(start)\n    sig = fobj.read(4)\n    if sig != b\"\\x00\\x00\\x00\\x00\":\n        msg = \"Unknown signature, expecting 0x00000000\"\n        raise SyntaxError(msg)\n    return read_32(fobj, (start + 4, length - 4), size)\n\n\ndef read_32(\n    fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int]\n) -> dict[str, Image.Image]:\n    \"\"\"\n    Read a 32bit RGB icon resource.  Seems to be either uncompressed or\n    an RLE packbits-like scheme.\n    \"\"\"\n    (start, length) = start_length\n    fobj.seek(start)\n    pixel_size = (size[0] * size[2], size[1] * size[2])\n    sizesq = pixel_size[0] * pixel_size[1]\n    if length == sizesq * 3:\n        # uncompressed (\"RGBRGBGB\")\n        indata = fobj.read(length)\n        im = Image.frombuffer(\"RGB\", pixel_size, indata, \"raw\", \"RGB\", 0, 1)\n    else:\n        # decode image\n        im = Image.new(\"RGB\", pixel_size, None)\n        for band_ix in range(3):\n            data = []\n            bytesleft = sizesq\n            while bytesleft > 0:\n                byte = fobj.read(1)\n                if not byte:\n                    break\n                byte_int = byte[0]\n                if byte_int & 0x80:\n                    blocksize = byte_int - 125\n                    byte = fobj.read(1)\n                    for i in range(blocksize):\n                        data.append(byte)\n                else:\n                    blocksize = byte_int + 1\n                    data.append(fobj.read(blocksize))\n                bytesleft -= blocksize\n                if bytesleft <= 0:\n                    break\n            if bytesleft != 0:\n                msg = f\"Error reading channel [{repr(bytesleft)} left]\"\n                raise SyntaxError(msg)\n            band = Image.frombuffer(\"L\", pixel_size, b\"\".join(data), \"raw\", \"L\", 0, 1)\n            im.im.putband(band.im, band_ix)\n    return {\"RGB\": im}\n\n\ndef read_mk(\n    fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int]\n) -> dict[str, Image.Image]:\n    # Alpha masks seem to be uncompressed\n    start = start_length[0]\n    fobj.seek(start)\n    pixel_size = (size[0] * size[2], size[1] * size[2])\n    sizesq = pixel_size[0] * pixel_size[1]\n    band = Image.frombuffer(\"L\", pixel_size, fobj.read(sizesq), \"raw\", \"L\", 0, 1)\n    return {\"A\": band}\n\n\ndef read_png_or_jpeg2000(\n    fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int]\n) -> dict[str, Image.Image]:\n    (start, length) = start_length\n    fobj.seek(start)\n    sig = fobj.read(12)\n\n    im: Image.Image\n    if sig[:8] == b\"\\x89PNG\\x0d\\x0a\\x1a\\x0a\":\n        fobj.seek(start)\n        im = PngImagePlugin.PngImageFile(fobj)\n        Image._decompression_bomb_check(im.size)\n        return {\"RGBA\": im}\n    elif (\n        sig[:4] == b\"\\xff\\x4f\\xff\\x51\"\n        or sig[:4] == b\"\\x0d\\x0a\\x87\\x0a\"\n        or sig == b\"\\x00\\x00\\x00\\x0cjP  \\x0d\\x0a\\x87\\x0a\"\n    ):\n        if not enable_jpeg2k:\n            msg = (\n                \"Unsupported icon subimage format (rebuild PIL \"\n                \"with JPEG 2000 support to fix this)\"\n            )\n            raise ValueError(msg)\n        # j2k, jpc or j2c\n        fobj.seek(start)\n        jp2kstream = fobj.read(length)\n        f = io.BytesIO(jp2kstream)\n        im = Jpeg2KImagePlugin.Jpeg2KImageFile(f)\n        Image._decompression_bomb_check(im.size)\n        if im.mode != \"RGBA\":\n            im = im.convert(\"RGBA\")\n        return {\"RGBA\": im}\n    else:\n        msg = \"Unsupported icon subimage format\"\n        raise ValueError(msg)\n\n\nclass IcnsFile:\n    SIZES = {\n        (512, 512, 2): [(b\"ic10\", read_png_or_jpeg2000)],\n        (512, 512, 1): [(b\"ic09\", read_png_or_jpeg2000)],\n        (256, 256, 2): [(b\"ic14\", read_png_or_jpeg2000)],\n        (256, 256, 1): [(b\"ic08\", read_png_or_jpeg2000)],\n        (128, 128, 2): [(b\"ic13\", read_png_or_jpeg2000)],\n        (128, 128, 1): [\n            (b\"ic07\", read_png_or_jpeg2000),\n            (b\"it32\", read_32t),\n            (b\"t8mk\", read_mk),\n        ],\n        (64, 64, 1): [(b\"icp6\", read_png_or_jpeg2000)],\n        (32, 32, 2): [(b\"ic12\", read_png_or_jpeg2000)],\n        (48, 48, 1): [(b\"ih32\", read_32), (b\"h8mk\", read_mk)],\n        (32, 32, 1): [\n            (b\"icp5\", read_png_or_jpeg2000),\n            (b\"il32\", read_32),\n            (b\"l8mk\", read_mk),\n        ],\n        (16, 16, 2): [(b\"ic11\", read_png_or_jpeg2000)],\n        (16, 16, 1): [\n            (b\"icp4\", read_png_or_jpeg2000),\n            (b\"is32\", read_32),\n            (b\"s8mk\", read_mk),\n        ],\n    }\n\n    def __init__(self, fobj: IO[bytes]) -> None:\n        \"\"\"\n        fobj is a file-like object as an icns resource\n        \"\"\"\n        # signature : (start, length)\n        self.dct = {}\n        self.fobj = fobj\n        sig, filesize = nextheader(fobj)\n        if not _accept(sig):\n            msg = \"not an icns file\"\n            raise SyntaxError(msg)\n        i = HEADERSIZE\n        while i < filesize:\n            sig, blocksize = nextheader(fobj)\n            if blocksize <= 0:\n                msg = \"invalid block header\"\n                raise SyntaxError(msg)\n            i += HEADERSIZE\n            blocksize -= HEADERSIZE\n            self.dct[sig] = (i, blocksize)\n            fobj.seek(blocksize, io.SEEK_CUR)\n            i += blocksize\n\n    def itersizes(self) -> list[tuple[int, int, int]]:\n        sizes = []\n        for size, fmts in self.SIZES.items():\n            for fmt, reader in fmts:\n                if fmt in self.dct:\n                    sizes.append(size)\n                    break\n        return sizes\n\n    def bestsize(self) -> tuple[int, int, int]:\n        sizes = self.itersizes()\n        if not sizes:\n            msg = \"No 32bit icon resources found\"\n            raise SyntaxError(msg)\n        return max(sizes)\n\n    def dataforsize(self, size: tuple[int, int, int]) -> dict[str, Image.Image]:\n        \"\"\"\n        Get an icon resource as {channel: array}.  Note that\n        the arrays are bottom-up like windows bitmaps and will likely\n        need to be flipped or transposed in some way.\n        \"\"\"\n        dct = {}\n        for code, reader in self.SIZES[size]:\n            desc = self.dct.get(code)\n            if desc is not None:\n                dct.update(reader(self.fobj, desc, size))\n        return dct\n\n    def getimage(\n        self, size: tuple[int, int] | tuple[int, int, int] | None = None\n    ) -> Image.Image:\n        if size is None:\n            size = self.bestsize()\n        elif len(size) == 2:\n            size = (size[0], size[1], 1)\n        channels = self.dataforsize(size)\n\n        im = channels.get(\"RGBA\")\n        if im:\n            return im\n\n        im = channels[\"RGB\"].copy()\n        try:\n            im.putalpha(channels[\"A\"])\n        except KeyError:\n            pass\n        return im\n\n\n##\n# Image plugin for Mac OS icons.\n\n\nclass IcnsImageFile(ImageFile.ImageFile):\n    \"\"\"\n    PIL image support for Mac OS .icns files.\n    Chooses the best resolution, but will possibly load\n    a different size image if you mutate the size attribute\n    before calling 'load'.\n\n    The info dictionary has a key 'sizes' that is a list\n    of sizes that the icns file has.\n    \"\"\"\n\n    format = \"ICNS\"\n    format_description = \"Mac OS icns resource\"\n\n    def _open(self) -> None:\n        self.icns = IcnsFile(self.fp)\n        self._mode = \"RGBA\"\n        self.info[\"sizes\"] = self.icns.itersizes()\n        self.best_size = self.icns.bestsize()\n        self.size = (\n            self.best_size[0] * self.best_size[2],\n            self.best_size[1] * self.best_size[2],\n        )\n\n    @property\n    def size(self):\n        return self._size\n\n    @size.setter\n    def size(self, value) -> None:\n        info_size = value\n        if info_size not in self.info[\"sizes\"] and len(info_size) == 2:\n            info_size = (info_size[0], info_size[1], 1)\n        if (\n            info_size not in self.info[\"sizes\"]\n            and len(info_size) == 3\n            and info_size[2] == 1\n        ):\n            simple_sizes = [\n                (size[0] * size[2], size[1] * size[2]) for size in self.info[\"sizes\"]\n            ]\n            if value in simple_sizes:\n                info_size = self.info[\"sizes\"][simple_sizes.index(value)]\n        if info_size not in self.info[\"sizes\"]:\n            msg = \"This is not one of the allowed sizes of this image\"\n            raise ValueError(msg)\n        self._size = value\n\n    def load(self) -> Image.core.PixelAccess | None:\n        if len(self.size) == 3:\n            self.best_size = self.size\n            self.size = (\n                self.best_size[0] * self.best_size[2],\n                self.best_size[1] * self.best_size[2],\n            )\n\n        px = Image.Image.load(self)\n        if self._im is not None and self.im.size == self.size:\n            # Already loaded\n            return px\n        self.load_prepare()\n        # This is likely NOT the best way to do it, but whatever.\n        im = self.icns.getimage(self.best_size)\n\n        # If this is a PNG or JPEG 2000, it won't be loaded yet\n        px = im.load()\n\n        self.im = im.im\n        self._mode = im.mode\n        self.size = im.size\n\n        return px\n\n\ndef _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:\n    \"\"\"\n    Saves the image as a series of PNG files,\n    that are then combined into a .icns file.\n    \"\"\"\n    if hasattr(fp, \"flush\"):\n        fp.flush()\n\n    sizes = {\n        b\"ic07\": 128,\n        b\"ic08\": 256,\n        b\"ic09\": 512,\n        b\"ic10\": 1024,\n        b\"ic11\": 32,\n        b\"ic12\": 64,\n        b\"ic13\": 256,\n        b\"ic14\": 512,\n    }\n    provided_images = {im.width: im for im in im.encoderinfo.get(\"append_images\", [])}\n    size_streams = {}\n    for size in set(sizes.values()):\n        image = (\n            provided_images[size]\n            if size in provided_images\n            else im.resize((size, size))\n        )\n\n        temp = io.BytesIO()\n        image.save(temp, \"png\")\n        size_streams[size] = temp.getvalue()\n\n    entries = []\n    for type, size in sizes.items():\n        stream = size_streams[size]\n        entries.append((type, HEADERSIZE + len(stream), stream))\n\n    # Header\n    fp.write(MAGIC)\n    file_length = HEADERSIZE  # Header\n    file_length += HEADERSIZE + 8 * len(entries)  # TOC\n    file_length += sum(entry[1] for entry in entries)\n    fp.write(struct.pack(\">i\", file_length))\n\n    # TOC\n    fp.write(b\"TOC \")\n    fp.write(struct.pack(\">i\", HEADERSIZE + len(entries) * HEADERSIZE))\n    for entry in entries:\n        fp.write(entry[0])\n        fp.write(struct.pack(\">i\", entry[1]))\n\n    # Data\n    for entry in entries:\n        fp.write(entry[0])\n        fp.write(struct.pack(\">i\", entry[1]))\n        fp.write(entry[2])\n\n    if hasattr(fp, \"flush\"):\n        fp.flush()\n\n\ndef _accept(prefix: bytes) -> bool:\n    return prefix[:4] == MAGIC\n\n\nImage.register_open(IcnsImageFile.format, IcnsImageFile, _accept)\nImage.register_extension(IcnsImageFile.format, \".icns\")\n\nImage.register_save(IcnsImageFile.format, _save)\nImage.register_mime(IcnsImageFile.format, \"image/icns\")\n\nif __name__ == \"__main__\":\n    if len(sys.argv) < 2:\n        print(\"Syntax: python3 IcnsImagePlugin.py [file]\")\n        sys.exit()\n\n    with open(sys.argv[1], \"rb\") as fp:\n        imf = IcnsImageFile(fp)\n        for size in imf.info[\"sizes\"]:\n            width, height, scale = imf.size = size\n            imf.save(f\"out-{width}-{height}-{scale}.png\")\n        with Image.open(sys.argv[1]) as im:\n            im.save(\"out.png\")\n        if sys.platform == \"windows\":\n            os.startfile(\"out.png\")\n",
            "new_file_content": "#\n# The Python Imaging Library.\n# $Id$\n#\n# macOS icns file decoder, based on icns.py by Bob Ippolito.\n#\n# history:\n# 2004-10-09 fl   Turned into a PIL plugin; removed 2.3 dependencies.\n# 2020-04-04      Allow saving on all operating systems.\n#\n# Copyright (c) 2004 by Bob Ippolito.\n# Copyright (c) 2004 by Secret Labs.\n# Copyright (c) 2004 by Fredrik Lundh.\n# Copyright (c) 2014 by Alastair Houghton.\n# Copyright (c) 2020 by Pan Jing.\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nimport io\nimport os\nimport struct\nimport sys\nfrom typing import IO\n\nfrom . import Image, ImageFile, PngImagePlugin, features\n\nenable_jpeg2k = features.check_codec(\"jpg_2000\")\nif enable_jpeg2k:\n    from . import Jpeg2KImagePlugin\n\nMAGIC = b\"icns\"\nHEADERSIZE = 8\n\n\ndef nextheader(fobj: IO[bytes]) -> tuple[bytes, int]:\n    return struct.unpack(\">4sI\", fobj.read(HEADERSIZE))\n\n\ndef read_32t(\n    fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int]\n) -> dict[str, Image.Image]:\n    # The 128x128 icon seems to have an extra header for some reason.\n    (start, length) = start_length\n    fobj.seek(start)\n    sig = fobj.read(4)\n    if sig != b\"\\x00\\x00\\x00\\x00\":\n        msg = \"Unknown signature, expecting 0x00000000\"\n        raise SyntaxError(msg)\n    return read_32(fobj, (start + 4, length - 4), size)\n\n\ndef read_32(\n    fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int]\n) -> dict[str, Image.Image]:\n    \"\"\"\n    Read a 32bit RGB icon resource.  Seems to be either uncompressed or\n    an RLE packbits-like scheme.\n    \"\"\"\n    (start, length) = start_length\n    fobj.seek(start)\n    pixel_size = (size[0] * size[2], size[1] * size[2])\n    sizesq = pixel_size[0] * pixel_size[1]\n    if length == sizesq * 3:\n        # uncompressed (\"RGBRGBGB\")\n        indata = fobj.read(length)\n        im = Image.frombuffer(\"RGB\", pixel_size, indata, \"raw\", \"RGB\", 0, 1)\n    else:\n        # decode image\n        im = Image.new(\"RGB\", pixel_size, None)\n        for band_ix in range(3):\n            data = []\n            bytesleft = sizesq\n            while bytesleft > 0:\n                byte = fobj.read(1)\n                if not byte:\n                    break\n                byte_int = byte[0]\n                if byte_int & 0x80:\n                    blocksize = byte_int - 125\n                    byte = fobj.read(1)\n                    for i in range(blocksize):\n                        data.append(byte)\n                else:\n                    blocksize = byte_int + 1\n                    data.append(fobj.read(blocksize))\n                bytesleft -= blocksize\n                if bytesleft <= 0:\n                    break\n            if bytesleft != 0:\n                msg = f\"Error reading channel [{repr(bytesleft)} left]\"\n                raise SyntaxError(msg)\n            band = Image.frombuffer(\"L\", pixel_size, b\"\".join(data), \"raw\", \"L\", 0, 1)\n            im.im.putband(band.im, band_ix)\n    return {\"RGB\": im}\n\n\ndef read_mk(\n    fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int]\n) -> dict[str, Image.Image]:\n    # Alpha masks seem to be uncompressed\n    start = start_length[0]\n    fobj.seek(start)\n    pixel_size = (size[0] * size[2], size[1] * size[2])\n    sizesq = pixel_size[0] * pixel_size[1]\n    band = Image.frombuffer(\"L\", pixel_size, fobj.read(sizesq), \"raw\", \"L\", 0, 1)\n    return {\"A\": band}\n\n\ndef read_png_or_jpeg2000(\n    fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int]\n) -> dict[str, Image.Image]:\n    (start, length) = start_length\n    fobj.seek(start)\n    sig = fobj.read(12)\n\n    im: Image.Image\n    if sig[:8] == b\"\\x89PNG\\x0d\\x0a\\x1a\\x0a\":\n        fobj.seek(start)\n        im = PngImagePlugin.PngImageFile(fobj)\n        Image._decompression_bomb_check(im.size)\n        return {\"RGBA\": im}\n    elif (\n        sig[:4] == b\"\\xff\\x4f\\xff\\x51\"\n        or sig[:4] == b\"\\x0d\\x0a\\x87\\x0a\"\n        or sig == b\"\\x00\\x00\\x00\\x0cjP  \\x0d\\x0a\\x87\\x0a\"\n    ):\n        if not enable_jpeg2k:\n            msg = (\n                \"Unsupported icon subimage format (rebuild PIL \"\n                \"with JPEG 2000 support to fix this)\"\n            )\n            raise ValueError(msg)\n        # j2k, jpc or j2c\n        fobj.seek(start)\n        jp2kstream = fobj.read(length)\n        f = io.BytesIO(jp2kstream)\n        im = Jpeg2KImagePlugin.Jpeg2KImageFile(f)\n        Image._decompression_bomb_check(im.size)\n        if im.mode != \"RGBA\":\n            im = im.convert(\"RGBA\")\n        return {\"RGBA\": im}\n    else:\n        msg = \"Unsupported icon subimage format\"\n        raise ValueError(msg)\n\n\nclass IcnsFile:\n    SIZES = {\n        (512, 512, 2): [(b\"ic10\", read_png_or_jpeg2000)],\n        (512, 512, 1): [(b\"ic09\", read_png_or_jpeg2000)],\n        (256, 256, 2): [(b\"ic14\", read_png_or_jpeg2000)],\n        (256, 256, 1): [(b\"ic08\", read_png_or_jpeg2000)],\n        (128, 128, 2): [(b\"ic13\", read_png_or_jpeg2000)],\n        (128, 128, 1): [\n            (b\"ic07\", read_png_or_jpeg2000),\n            (b\"it32\", read_32t),\n            (b\"t8mk\", read_mk),\n        ],\n        (64, 64, 1): [(b\"icp6\", read_png_or_jpeg2000)],\n        (32, 32, 2): [(b\"ic12\", read_png_or_jpeg2000)],\n        (48, 48, 1): [(b\"ih32\", read_32), (b\"h8mk\", read_mk)],\n        (32, 32, 1): [\n            (b\"icp5\", read_png_or_jpeg2000),\n            (b\"il32\", read_32),\n            (b\"l8mk\", read_mk),\n        ],\n        (16, 16, 2): [(b\"ic11\", read_png_or_jpeg2000)],\n        (16, 16, 1): [\n            (b\"icp4\", read_png_or_jpeg2000),\n            (b\"is32\", read_32),\n            (b\"s8mk\", read_mk),\n        ],\n    }\n\n    def __init__(self, fobj: IO[bytes]) -> None:\n        \"\"\"\n        fobj is a file-like object as an icns resource\n        \"\"\"\n        # signature : (start, length)\n        self.dct = {}\n        self.fobj = fobj\n        sig, filesize = nextheader(fobj)\n        if not _accept(sig):\n            msg = \"not an icns file\"\n            raise SyntaxError(msg)\n        i = HEADERSIZE\n        while i < filesize:\n            sig, blocksize = nextheader(fobj)\n            if blocksize <= 0:\n                msg = \"invalid block header\"\n                raise SyntaxError(msg)\n            i += HEADERSIZE\n            blocksize -= HEADERSIZE\n            self.dct[sig] = (i, blocksize)\n            fobj.seek(blocksize, io.SEEK_CUR)\n            i += blocksize\n\n    def itersizes(self) -> list[tuple[int, int, int]]:\n        sizes = []\n        for size, fmts in self.SIZES.items():\n            for fmt, reader in fmts:\n                if fmt in self.dct:\n                    sizes.append(size)\n                    break\n        return sizes\n\n    def bestsize(self) -> tuple[int, int, int]:\n        sizes = self.itersizes()\n        if not sizes:\n            msg = \"No 32bit icon resources found\"\n            raise SyntaxError(msg)\n        return max(sizes)\n\n    def dataforsize(self, size: tuple[int, int, int]) -> dict[str, Image.Image]:\n        \"\"\"\n        Get an icon resource as {channel: array}.  Note that\n        the arrays are bottom-up like windows bitmaps and will likely\n        need to be flipped or transposed in some way.\n        \"\"\"\n        dct = {}\n        for code, reader in self.SIZES[size]:\n            desc = self.dct.get(code)\n            if desc is not None:\n                dct.update(reader(self.fobj, desc, size))\n        return dct\n\n    def getimage(\n        self, size: tuple[int, int] | tuple[int, int, int] | None = None\n    ) -> Image.Image:\n        if size is None:\n            size = self.bestsize()\n        elif len(size) == 2:\n            size = (size[0], size[1], 1)\n        channels = self.dataforsize(size)\n\n        im = channels.get(\"RGBA\")\n        if im:\n            return im\n\n        im = channels[\"RGB\"].copy()\n        try:\n            im.putalpha(channels[\"A\"])\n        except KeyError:\n            pass\n        return im\n\n\n##\n# Image plugin for Mac OS icons.\n\n\nclass IcnsImageFile(ImageFile.ImageFile):\n    \"\"\"\n    PIL image support for Mac OS .icns files.\n    Chooses the best resolution, but will possibly load\n    a different size image if you mutate the size attribute\n    before calling 'load'.\n\n    The info dictionary has a key 'sizes' that is a list\n    of sizes that the icns file has.\n    \"\"\"\n\n    format = \"ICNS\"\n    format_description = \"Mac OS icns resource\"\n\n    def _open(self) -> None:\n        self.icns = IcnsFile(self.fp)\n        self._mode = \"RGBA\"\n        self.info[\"sizes\"] = self.icns.itersizes()\n        self.best_size = self.icns.bestsize()\n        self.size = (\n            self.best_size[0] * self.best_size[2],\n            self.best_size[1] * self.best_size[2],\n        )\n\n    @property\n    def size(self):\n        return self._size\n\n    @size.setter\n    def size(self, value) -> None:\n        if len(value) == 3:\n            if value in self.info[\"sizes\"]:\n                self._size = value\n                return\n        else:\n            # Check that a matching size exists,\n            # or that there is a scale that would create a size that matches\n            for size in self.info[\"sizes\"]:\n                simple_size = size[0] * size[2], size[1] * size[2]\n                scale = simple_size[0] // value[0]\n                if simple_size[1] / value[1] == scale:\n                    self._size = value\n                    return\n        msg = \"This is not one of the allowed sizes of this image\"\n        raise ValueError(msg)\n\n    def load(self, scale: int | None = None) -> Image.core.PixelAccess | None:\n        if scale is not None or len(self.size) == 3:\n            if scale is None and len(self.size) == 3:\n                scale = self.size[2]\n            assert scale is not None\n            width, height = self.size[:2]\n            self.size = width * scale, height * scale\n            self.best_size = width, height, scale\n\n        px = Image.Image.load(self)\n        if self._im is not None and self.im.size == self.size:\n            # Already loaded\n            return px\n        self.load_prepare()\n        # This is likely NOT the best way to do it, but whatever.\n        im = self.icns.getimage(self.best_size)\n\n        # If this is a PNG or JPEG 2000, it won't be loaded yet\n        px = im.load()\n\n        self.im = im.im\n        self._mode = im.mode\n        self.size = im.size\n\n        return px\n\n\ndef _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:\n    \"\"\"\n    Saves the image as a series of PNG files,\n    that are then combined into a .icns file.\n    \"\"\"\n    if hasattr(fp, \"flush\"):\n        fp.flush()\n\n    sizes = {\n        b\"ic07\": 128,\n        b\"ic08\": 256,\n        b\"ic09\": 512,\n        b\"ic10\": 1024,\n        b\"ic11\": 32,\n        b\"ic12\": 64,\n        b\"ic13\": 256,\n        b\"ic14\": 512,\n    }\n    provided_images = {im.width: im for im in im.encoderinfo.get(\"append_images\", [])}\n    size_streams = {}\n    for size in set(sizes.values()):\n        image = (\n            provided_images[size]\n            if size in provided_images\n            else im.resize((size, size))\n        )\n\n        temp = io.BytesIO()\n        image.save(temp, \"png\")\n        size_streams[size] = temp.getvalue()\n\n    entries = []\n    for type, size in sizes.items():\n        stream = size_streams[size]\n        entries.append((type, HEADERSIZE + len(stream), stream))\n\n    # Header\n    fp.write(MAGIC)\n    file_length = HEADERSIZE  # Header\n    file_length += HEADERSIZE + 8 * len(entries)  # TOC\n    file_length += sum(entry[1] for entry in entries)\n    fp.write(struct.pack(\">i\", file_length))\n\n    # TOC\n    fp.write(b\"TOC \")\n    fp.write(struct.pack(\">i\", HEADERSIZE + len(entries) * HEADERSIZE))\n    for entry in entries:\n        fp.write(entry[0])\n        fp.write(struct.pack(\">i\", entry[1]))\n\n    # Data\n    for entry in entries:\n        fp.write(entry[0])\n        fp.write(struct.pack(\">i\", entry[1]))\n        fp.write(entry[2])\n\n    if hasattr(fp, \"flush\"):\n        fp.flush()\n\n\ndef _accept(prefix: bytes) -> bool:\n    return prefix[:4] == MAGIC\n\n\nImage.register_open(IcnsImageFile.format, IcnsImageFile, _accept)\nImage.register_extension(IcnsImageFile.format, \".icns\")\n\nImage.register_save(IcnsImageFile.format, _save)\nImage.register_mime(IcnsImageFile.format, \"image/icns\")\n\nif __name__ == \"__main__\":\n    if len(sys.argv) < 2:\n        print(\"Syntax: python3 IcnsImagePlugin.py [file]\")\n        sys.exit()\n\n    with open(sys.argv[1], \"rb\") as fp:\n        imf = IcnsImageFile(fp)\n        for size in imf.info[\"sizes\"]:\n            width, height, scale = imf.size = size\n            imf.save(f\"out-{width}-{height}-{scale}.png\")\n        with Image.open(sys.argv[1]) as im:\n            im.save(\"out.png\")\n        if sys.platform == \"windows\":\n            os.startfile(\"out.png\")\n",
            "header": {
                "file": {
                    "path": "src/PIL/IcnsImagePlugin.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "ca66aa0fd",
                "new_commit_hash": "e4f486a4f",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/src/PIL/IcnsImagePlugin.py"
            },
            "plus_file": {
                "path": "b/src/PIL/IcnsImagePlugin.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 281,
                            "length": 31
                        },
                        "new_range": {
                            "start": 281,
                            "length": 30
                        },
                        "section": "class IcnsImageFile(ImageFile.ImageFile):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    @size.setter",
                                "type": "context"
                            },
                            {
                                "content": "    def size(self, value) -> None:",
                                "type": "context"
                            },
                            {
                                "content": "        info_size = value",
                                "type": "deleted"
                            },
                            {
                                "content": "        if info_size not in self.info[\"sizes\"] and len(info_size) == 2:",
                                "type": "deleted"
                            },
                            {
                                "content": "            info_size = (info_size[0], info_size[1], 1)",
                                "type": "deleted"
                            },
                            {
                                "content": "        if (",
                                "type": "deleted"
                            },
                            {
                                "content": "            info_size not in self.info[\"sizes\"]",
                                "type": "deleted"
                            },
                            {
                                "content": "            and len(info_size) == 3",
                                "type": "deleted"
                            },
                            {
                                "content": "            and info_size[2] == 1",
                                "type": "deleted"
                            },
                            {
                                "content": "        ):",
                                "type": "deleted"
                            },
                            {
                                "content": "            simple_sizes = [",
                                "type": "deleted"
                            },
                            {
                                "content": "                (size[0] * size[2], size[1] * size[2]) for size in self.info[\"sizes\"]",
                                "type": "deleted"
                            },
                            {
                                "content": "            ]",
                                "type": "deleted"
                            },
                            {
                                "content": "            if value in simple_sizes:",
                                "type": "deleted"
                            },
                            {
                                "content": "                info_size = self.info[\"sizes\"][simple_sizes.index(value)]",
                                "type": "deleted"
                            },
                            {
                                "content": "        if info_size not in self.info[\"sizes\"]:",
                                "type": "deleted"
                            },
                            {
                                "content": "            msg = \"This is not one of the allowed sizes of this image\"",
                                "type": "deleted"
                            },
                            {
                                "content": "            raise ValueError(msg)",
                                "type": "deleted"
                            },
                            {
                                "content": "        self._size = value",
                                "type": "deleted"
                            },
                            {
                                "content": "",
                                "type": "deleted"
                            },
                            {
                                "content": "    def load(self) -> Image.core.PixelAccess | None:",
                                "type": "deleted"
                            },
                            {
                                "content": "        if len(self.size) == 3:",
                                "type": "deleted"
                            },
                            {
                                "content": "            self.best_size = self.size",
                                "type": "deleted"
                            },
                            {
                                "content": "            self.size = (",
                                "type": "deleted"
                            },
                            {
                                "content": "                self.best_size[0] * self.best_size[2],",
                                "type": "deleted"
                            },
                            {
                                "content": "                self.best_size[1] * self.best_size[2],",
                                "type": "deleted"
                            },
                            {
                                "content": "            )",
                                "type": "deleted"
                            },
                            {
                                "content": "        if len(value) == 3:",
                                "type": "added"
                            },
                            {
                                "content": "            if value in self.info[\"sizes\"]:",
                                "type": "added"
                            },
                            {
                                "content": "                self._size = value",
                                "type": "added"
                            },
                            {
                                "content": "                return",
                                "type": "added"
                            },
                            {
                                "content": "        else:",
                                "type": "added"
                            },
                            {
                                "content": "            # Check that a matching size exists,",
                                "type": "added"
                            },
                            {
                                "content": "            # or that there is a scale that would create a size that matches",
                                "type": "added"
                            },
                            {
                                "content": "            for size in self.info[\"sizes\"]:",
                                "type": "added"
                            },
                            {
                                "content": "                simple_size = size[0] * size[2], size[1] * size[2]",
                                "type": "added"
                            },
                            {
                                "content": "                scale = simple_size[0] // value[0]",
                                "type": "added"
                            },
                            {
                                "content": "                if simple_size[1] / value[1] == scale:",
                                "type": "added"
                            },
                            {
                                "content": "                    self._size = value",
                                "type": "added"
                            },
                            {
                                "content": "                    return",
                                "type": "added"
                            },
                            {
                                "content": "        msg = \"This is not one of the allowed sizes of this image\"",
                                "type": "added"
                            },
                            {
                                "content": "        raise ValueError(msg)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def load(self, scale: int | None = None) -> Image.core.PixelAccess | None:",
                                "type": "added"
                            },
                            {
                                "content": "        if scale is not None or len(self.size) == 3:",
                                "type": "added"
                            },
                            {
                                "content": "            if scale is None and len(self.size) == 3:",
                                "type": "added"
                            },
                            {
                                "content": "                scale = self.size[2]",
                                "type": "added"
                            },
                            {
                                "content": "            assert scale is not None",
                                "type": "added"
                            },
                            {
                                "content": "            width, height = self.size[:2]",
                                "type": "added"
                            },
                            {
                                "content": "            self.size = width * scale, height * scale",
                                "type": "added"
                            },
                            {
                                "content": "            self.best_size = width, height, scale",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        px = Image.Image.load(self)",
                                "type": "context"
                            },
                            {
                                "content": "        if self._im is not None and self.im.size == self.size:",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "src/PIL/IcnsImagePlugin.py",
                            "type": "class",
                            "name": "IcnsImageFile",
                            "content": "class IcnsImageFile(ImageFile.ImageFile):\n    \"\"\"\n    PIL image support for Mac OS .icns files.\n    Chooses the best resolution, but will possibly load\n    a different size image if you mutate the size attribute\n    before calling 'load'.\n\n    The info dictionary has a key 'sizes' that is a list\n    of sizes that the icns file has.\n    \"\"\"\n\n    format = \"ICNS\"\n    format_description = \"Mac OS icns resource\"\n\n    def _open(self) -> None:\n        self.icns = IcnsFile(self.fp)\n        self._mode = \"RGBA\"\n        self.info[\"sizes\"] = self.icns.itersizes()\n        self.best_size = self.icns.bestsize()\n        self.size = (\n            self.best_size[0] * self.best_size[2],\n            self.best_size[1] * self.best_size[2],\n        )\n\n    @property\n    def size(self):\n        return self._size\n\n    @size.setter\n    def size(self, value) -> None:\n        info_size = value\n        if info_size not in self.info[\"sizes\"] and len(info_size) == 2:\n            info_size = (info_size[0], info_size[1], 1)\n        if (\n            info_size not in self.info[\"sizes\"]\n            and len(info_size) == 3\n            and info_size[2] == 1\n        ):\n            simple_sizes = [\n                (size[0] * size[2], size[1] * size[2]) for size in self.info[\"sizes\"]\n            ]\n            if value in simple_sizes:\n                info_size = self.info[\"sizes\"][simple_sizes.index(value)]\n        if info_size not in self.info[\"sizes\"]:\n            msg = \"This is not one of the allowed sizes of this image\"\n            raise ValueError(msg)\n        self._size = value\n\n    def load(self) -> Image.core.PixelAccess | None:\n        if len(self.size) == 3:\n            self.best_size = self.size\n            self.size = (\n                self.best_size[0] * self.best_size[2],\n                self.best_size[1] * self.best_size[2],\n            )\n\n        px = Image.Image.load(self)\n        if self._im is not None and self.im.size == self.size:\n            # Already loaded\n            return px\n        self.load_prepare()\n        # This is likely NOT the best way to do it, but whatever.\n        im = self.icns.getimage(self.best_size)\n\n        # If this is a PNG or JPEG 2000, it won't be loaded yet\n        px = im.load()\n\n        self.im = im.im\n        self._mode = im.mode\n        self.size = im.size\n\n        return px",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 254,
                            "end_lineno": 325,
                            "parent": null
                        },
                        {
                            "file_name": "src/PIL/IcnsImagePlugin.py",
                            "type": "method",
                            "name": "IcnsImageFile.size",
                            "content": "class IcnsImageFile(ImageFile.ImageFile):\n    \"\"\"\n    PIL image support for Mac OS .icns files.\n    Chooses the best resolution, but will possibly load\n    a different size image if you mutate the size attribute\n    before calling 'load'.\n\n    The info dictionary has a key 'sizes' that is a list\n    of sizes that the icns file has.\n    \"\"\"\n\n    format = \"ICNS\"\n    format_description = \"Mac OS icns resource\"\n\n    def _open(self) -> None:\n        self.icns = IcnsFile(self.fp)\n        self._mode = \"RGBA\"\n        self.info[\"sizes\"] = self.icns.itersizes()\n        self.best_size = self.icns.bestsize()\n        self.size = (\n            self.best_size[0] * self.best_size[2],\n            self.best_size[1] * self.best_size[2],\n        )\n\n    @property\n    def size(self):\n        return self._size\n\n    @size.setter\n    def size(self, value) -> None:\n        info_size = value\n        if info_size not in self.info[\"sizes\"] and len(info_size) == 2:\n            info_size = (info_size[0], info_size[1], 1)\n        if (\n            info_size not in self.info[\"sizes\"]\n            and len(info_size) == 3\n            and info_size[2] == 1\n        ):\n            simple_sizes = [\n                (size[0] * size[2], size[1] * size[2]) for size in self.info[\"sizes\"]\n            ]\n            if value in simple_sizes:\n                info_size = self.info[\"sizes\"][simple_sizes.index(value)]\n        if info_size not in self.info[\"sizes\"]:\n            msg = \"This is not one of the allowed sizes of this image\"\n            raise ValueError(msg)\n        self._size = value\n\n    def load(self) -> Image.core.PixelAccess | None:\n        if len(self.size) == 3:\n            self.best_size = self.size\n            self.size = (\n                self.best_size[0] * self.best_size[2],\n                self.best_size[1] * self.best_size[2],\n            )\n\n        px = Image.Image.load(self)\n        if self._im is not None and self.im.size == self.size:\n            # Already loaded\n            return px\n        self.load_prepare()\n        # This is likely NOT the best way to do it, but whatever.\n        im = self.icns.getimage(self.best_size)\n\n        # If this is a PNG or JPEG 2000, it won't be loaded yet\n        px = im.load()\n\n        self.im = im.im\n        self._mode = im.mode\n        self.size = im.size\n\n        return px",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 283,
                            "end_lineno": 300,
                            "parent": {
                                "file_name": "src/PIL/IcnsImagePlugin.py",
                                "type": "class",
                                "name": "IcnsImageFile",
                                "content": "class IcnsImageFile(ImageFile.ImageFile):\n    \"\"\"\n    PIL image support for Mac OS .icns files.\n    Chooses the best resolution, but will possibly load\n    a different size image if you mutate the size attribute\n    before calling 'load'.\n\n    The info dictionary has a key 'sizes' that is a list\n    of sizes that the icns file has.\n    \"\"\"\n\n    format = \"ICNS\"\n    format_description = \"Mac OS icns resource\"\n\n    def _open(self) -> None:\n        self.icns = IcnsFile(self.fp)\n        self._mode = \"RGBA\"\n        self.info[\"sizes\"] = self.icns.itersizes()\n        self.best_size = self.icns.bestsize()\n        self.size = (\n            self.best_size[0] * self.best_size[2],\n            self.best_size[1] * self.best_size[2],\n        )\n\n    @property\n    def size(self):\n        return self._size\n\n    @size.setter\n    def size(self, value) -> None:\n        info_size = value\n        if info_size not in self.info[\"sizes\"] and len(info_size) == 2:\n            info_size = (info_size[0], info_size[1], 1)\n        if (\n            info_size not in self.info[\"sizes\"]\n            and len(info_size) == 3\n            and info_size[2] == 1\n        ):\n            simple_sizes = [\n                (size[0] * size[2], size[1] * size[2]) for size in self.info[\"sizes\"]\n            ]\n            if value in simple_sizes:\n                info_size = self.info[\"sizes\"][simple_sizes.index(value)]\n        if info_size not in self.info[\"sizes\"]:\n            msg = \"This is not one of the allowed sizes of this image\"\n            raise ValueError(msg)\n        self._size = value\n\n    def load(self) -> Image.core.PixelAccess | None:\n        if len(self.size) == 3:\n            self.best_size = self.size\n            self.size = (\n                self.best_size[0] * self.best_size[2],\n                self.best_size[1] * self.best_size[2],\n            )\n\n        px = Image.Image.load(self)\n        if self._im is not None and self.im.size == self.size:\n            # Already loaded\n            return px\n        self.load_prepare()\n        # This is likely NOT the best way to do it, but whatever.\n        im = self.icns.getimage(self.best_size)\n\n        # If this is a PNG or JPEG 2000, it won't be loaded yet\n        px = im.load()\n\n        self.im = im.im\n        self._mode = im.mode\n        self.size = im.size\n\n        return px",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 254,
                                "end_lineno": 325,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "src/PIL/IcnsImagePlugin.py",
                            "type": "method",
                            "name": "IcnsImageFile.load",
                            "content": "class IcnsImageFile(ImageFile.ImageFile):\n    \"\"\"\n    PIL image support for Mac OS .icns files.\n    Chooses the best resolution, but will possibly load\n    a different size image if you mutate the size attribute\n    before calling 'load'.\n\n    The info dictionary has a key 'sizes' that is a list\n    of sizes that the icns file has.\n    \"\"\"\n\n    format = \"ICNS\"\n    format_description = \"Mac OS icns resource\"\n\n    def _open(self) -> None:\n        self.icns = IcnsFile(self.fp)\n        self._mode = \"RGBA\"\n        self.info[\"sizes\"] = self.icns.itersizes()\n        self.best_size = self.icns.bestsize()\n        self.size = (\n            self.best_size[0] * self.best_size[2],\n            self.best_size[1] * self.best_size[2],\n        )\n\n    @property\n    def size(self):\n        return self._size\n\n    @size.setter\n    def size(self, value) -> None:\n        info_size = value\n        if info_size not in self.info[\"sizes\"] and len(info_size) == 2:\n            info_size = (info_size[0], info_size[1], 1)\n        if (\n            info_size not in self.info[\"sizes\"]\n            and len(info_size) == 3\n            and info_size[2] == 1\n        ):\n            simple_sizes = [\n                (size[0] * size[2], size[1] * size[2]) for size in self.info[\"sizes\"]\n            ]\n            if value in simple_sizes:\n                info_size = self.info[\"sizes\"][simple_sizes.index(value)]\n        if info_size not in self.info[\"sizes\"]:\n            msg = \"This is not one of the allowed sizes of this image\"\n            raise ValueError(msg)\n        self._size = value\n\n    def load(self) -> Image.core.PixelAccess | None:\n        if len(self.size) == 3:\n            self.best_size = self.size\n            self.size = (\n                self.best_size[0] * self.best_size[2],\n                self.best_size[1] * self.best_size[2],\n            )\n\n        px = Image.Image.load(self)\n        if self._im is not None and self.im.size == self.size:\n            # Already loaded\n            return px\n        self.load_prepare()\n        # This is likely NOT the best way to do it, but whatever.\n        im = self.icns.getimage(self.best_size)\n\n        # If this is a PNG or JPEG 2000, it won't be loaded yet\n        px = im.load()\n\n        self.im = im.im\n        self._mode = im.mode\n        self.size = im.size\n\n        return px",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 302,
                            "end_lineno": 325,
                            "parent": {
                                "file_name": "src/PIL/IcnsImagePlugin.py",
                                "type": "class",
                                "name": "IcnsImageFile",
                                "content": "class IcnsImageFile(ImageFile.ImageFile):\n    \"\"\"\n    PIL image support for Mac OS .icns files.\n    Chooses the best resolution, but will possibly load\n    a different size image if you mutate the size attribute\n    before calling 'load'.\n\n    The info dictionary has a key 'sizes' that is a list\n    of sizes that the icns file has.\n    \"\"\"\n\n    format = \"ICNS\"\n    format_description = \"Mac OS icns resource\"\n\n    def _open(self) -> None:\n        self.icns = IcnsFile(self.fp)\n        self._mode = \"RGBA\"\n        self.info[\"sizes\"] = self.icns.itersizes()\n        self.best_size = self.icns.bestsize()\n        self.size = (\n            self.best_size[0] * self.best_size[2],\n            self.best_size[1] * self.best_size[2],\n        )\n\n    @property\n    def size(self):\n        return self._size\n\n    @size.setter\n    def size(self, value) -> None:\n        info_size = value\n        if info_size not in self.info[\"sizes\"] and len(info_size) == 2:\n            info_size = (info_size[0], info_size[1], 1)\n        if (\n            info_size not in self.info[\"sizes\"]\n            and len(info_size) == 3\n            and info_size[2] == 1\n        ):\n            simple_sizes = [\n                (size[0] * size[2], size[1] * size[2]) for size in self.info[\"sizes\"]\n            ]\n            if value in simple_sizes:\n                info_size = self.info[\"sizes\"][simple_sizes.index(value)]\n        if info_size not in self.info[\"sizes\"]:\n            msg = \"This is not one of the allowed sizes of this image\"\n            raise ValueError(msg)\n        self._size = value\n\n    def load(self) -> Image.core.PixelAccess | None:\n        if len(self.size) == 3:\n            self.best_size = self.size\n            self.size = (\n                self.best_size[0] * self.best_size[2],\n                self.best_size[1] * self.best_size[2],\n            )\n\n        px = Image.Image.load(self)\n        if self._im is not None and self.im.size == self.size:\n            # Already loaded\n            return px\n        self.load_prepare()\n        # This is likely NOT the best way to do it, but whatever.\n        im = self.icns.getimage(self.best_size)\n\n        # If this is a PNG or JPEG 2000, it won't be loaded yet\n        px = im.load()\n\n        self.im = im.im\n        self._mode = im.mode\n        self.size = im.size\n\n        return px",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 254,
                                "end_lineno": 325,
                                "parent": null
                            }
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "e625f7311965abd0a88992ca215d8ad61a27715e^",
    "new_commit_hash": "e625f7311965abd0a88992ca215d8ad61a27715e",
    "commit_message": "Added scale argument to IcnsImageFile load()",
    "commit_date": "2024-09-06T11:40:45+10:00",
    "metadata": {}
}
{
    "repo_name": "pillow",
    "new_commit_hash": "e625f7311965abd0a88992ca215d8ad61a27715e",
    "test_file_codes": [
        "from __future__ import annotations\n\nimport io\nimport os\nimport warnings\nfrom pathlib import Path\n\nimport pytest\n\nfrom PIL import IcnsImagePlugin, Image, _binary\n\nfrom .helper import assert_image_equal, assert_image_similar_tofile, skip_unless_feature\n\n# sample icon file\nTEST_FILE = \"Tests/images/pillow.icns\"\n\n\ndef test_sanity() -> None:\n    # Loading this icon by default should result in the largest size\n    # (512x512@2x) being loaded\n    with Image.open(TEST_FILE) as im:\n        # Assert that there is no unclosed file warning\n        with warnings.catch_warnings():\n            im.load()\n\n        assert im.mode == \"RGBA\"\n        assert im.size == (1024, 1024)\n        assert im.format == \"ICNS\"\n\n\ndef test_load() -> None:\n    with Image.open(TEST_FILE) as im:\n        assert im.load()[0, 0] == (0, 0, 0, 0)\n\n        # Test again now that it has already been loaded once\n        assert im.load()[0, 0] == (0, 0, 0, 0)\n\n\ndef test_save(tmp_path: Path) -> None:\n    temp_file = str(tmp_path / \"temp.icns\")\n\n    with Image.open(TEST_FILE) as im:\n        im.save(temp_file)\n\n    with Image.open(temp_file) as reread:\n        assert reread.mode == \"RGBA\"\n        assert reread.size == (1024, 1024)\n        assert reread.format == \"ICNS\"\n\n    file_length = os.path.getsize(temp_file)\n    with open(temp_file, \"rb\") as fp:\n        fp.seek(4)\n        assert _binary.i32be(fp.read(4)) == file_length\n\n\ndef test_save_append_images(tmp_path: Path) -> None:\n    temp_file = str(tmp_path / \"temp.icns\")\n    provided_im = Image.new(\"RGBA\", (32, 32), (255, 0, 0, 128))\n\n    with Image.open(TEST_FILE) as im:\n        im.save(temp_file, append_images=[provided_im])\n\n        assert_image_similar_tofile(im, temp_file, 1)\n\n        with Image.open(temp_file) as reread:\n            reread.size = (16, 16)\n            reread.load(2)\n            assert_image_equal(reread, provided_im)\n\n\ndef test_save_fp() -> None:\n    fp = io.BytesIO()\n\n    with Image.open(TEST_FILE) as im:\n        im.save(fp, format=\"ICNS\")\n\n    with Image.open(fp) as reread:\n        assert reread.mode == \"RGBA\"\n        assert reread.size == (1024, 1024)\n        assert reread.format == \"ICNS\"\n\n\ndef test_sizes() -> None:\n    # Check that we can load all of the sizes, and that the final pixel\n    # dimensions are as expected\n    with Image.open(TEST_FILE) as im:\n        for w, h, r in im.info[\"sizes\"]:\n            wr = w * r\n            hr = h * r\n            im.size = (w, h, r)\n            im.load()\n            assert im.mode == \"RGBA\"\n            assert im.size == (wr, hr)\n\n            # Test using load() with scale\n            im.size = (w, h)\n            im.load(scale=r)\n            assert im.mode == \"RGBA\"\n            assert im.size == (wr, hr)\n\n        # Check that we cannot load an incorrect size\n        with pytest.raises(ValueError):\n            im.size = (1, 2)\n\n\ndef test_older_icon() -> None:\n    # This icon was made with Icon Composer rather than iconutil; it still\n    # uses PNG rather than JP2, however (since it was made on 10.9).\n    with Image.open(\"Tests/images/pillow2.icns\") as im:\n        for w, h, r in im.info[\"sizes\"]:\n            wr = w * r\n            hr = h * r\n            with Image.open(\"Tests/images/pillow2.icns\") as im2:\n                im2.size = (w, h)\n                im2.load(r)\n                assert im2.mode == \"RGBA\"\n                assert im2.size == (wr, hr)\n\n\n@skip_unless_feature(\"jpg_2000\")\ndef test_jp2_icon() -> None:\n    # This icon uses JPEG 2000 images instead of the PNG images.\n    # The advantage of doing this is that OS X 10.5 supports JPEG 2000\n    # but not PNG; some commercial software therefore does just this.\n\n    with Image.open(\"Tests/images/pillow3.icns\") as im:\n        for w, h, r in im.info[\"sizes\"]:\n            wr = w * r\n            hr = h * r\n            with Image.open(\"Tests/images/pillow3.icns\") as im2:\n                im2.size = (w, h)\n                im2.load(r)\n                assert im2.mode == \"RGBA\"\n                assert im2.size == (wr, hr)\n\n\ndef test_getimage() -> None:\n    with open(TEST_FILE, \"rb\") as fp:\n        icns_file = IcnsImagePlugin.IcnsFile(fp)\n\n        im = icns_file.getimage()\n        assert im.mode == \"RGBA\"\n        assert im.size == (1024, 1024)\n\n        im = icns_file.getimage((512, 512))\n        assert im.mode == \"RGBA\"\n        assert im.size == (512, 512)\n\n\ndef test_not_an_icns_file() -> None:\n    with io.BytesIO(b\"invalid\\n\") as fp:\n        with pytest.raises(SyntaxError):\n            IcnsImagePlugin.IcnsFile(fp)\n\n\n@skip_unless_feature(\"jpg_2000\")\ndef test_icns_decompression_bomb() -> None:\n    with Image.open(\n        \"Tests/images/oom-8ed3316a4109213ca96fb8a256a0bfefdece1461.icns\"\n    ) as im:\n        with pytest.raises(Image.DecompressionBombError):\n            im.load()\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": "warning: `VIRTUAL_ENV=/home/gcpuser/r2e-edits-internal/.venv` does not match the project environment path `.venv` and will be ignored\nUsing CPython 3.9.21\nCreating virtual environment at: .venv\nActivate with: source .venv/bin/activate\nResolved 12 packages in 19ms\nInstalled 12 packages in 144ms\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 1.36s\nPrepared 1 package in 36.24s\nInstalled 1 package in 1ms\n + pillow==11.0.0.dev0 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/pillow_e625f7311965abd0a88992ca215d8ad61a27715e)\n",
    "new_commit_res_code": 0,
    "new_commit_res_stdout": "\u001b[1m============================= test session starts ==============================\u001b[0m\nplatform linux -- Python 3.9.21, pytest-8.3.4, pluggy-1.5.0\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/pillow_e625f7311965abd0a88992ca215d8ad61a27715e\nconfigfile: pyproject.toml\nplugins: cov-6.0.0\ncollected 11 items\n\nr2e_tests/test_1.py \u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[33ms\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[33ms\u001b[0m\u001b[32m                                          [100%]\u001b[0m\n\n==================================== PASSES ====================================\n\u001b[36m\u001b[1m=========================== short test summary info ============================\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_sanity\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_load\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_save\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_save_append_images\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_save_fp\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_sizes\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_older_icon\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_getimage\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_not_an_icns_file\u001b[0m\n\u001b[33mSKIPPED\u001b[0m [1] r2e_tests/test_1.py:120: jpg_2000 not available\n\u001b[33mSKIPPED\u001b[0m [1] r2e_tests/test_1.py:156: jpg_2000 not available\n\u001b[32m========================= \u001b[32m\u001b[1m9 passed\u001b[0m, \u001b[33m2 skipped\u001b[0m\u001b[32m in 1.49s\u001b[0m\u001b[32m =========================\u001b[0m\n",
    "new_commit_res_stderr": "",
    "old_commit_res_code": 1,
    "old_commit_res_stdout": "\u001b[1m============================= test session starts ==============================\u001b[0m\nplatform linux -- Python 3.9.21, pytest-8.3.4, pluggy-1.5.0\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/pillow_e625f7311965abd0a88992ca215d8ad61a27715e\nconfigfile: pyproject.toml\nplugins: cov-6.0.0\ncollected 11 items\n\nr2e_tests/test_1.py \u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[31mF\u001b[0m\u001b[32m.\u001b[0m\u001b[31mF\u001b[0m\u001b[31mF\u001b[0m\u001b[33ms\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[33ms\u001b[0m\u001b[31m                                          [100%]\u001b[0m\n\n=================================== FAILURES ===================================\n\u001b[31m\u001b[1m___________________________ test_save_append_images ____________________________\u001b[0m\n\ntmp_path = PosixPath('/tmp/pytest-of-gcpuser/pytest-703/test_save_append_images0')\n\n    def test_save_append_images(tmp_path: Path) -> None:\n        temp_file = str(tmp_path / \"temp.icns\")\n        provided_im = Image.new(\"RGBA\", (32, 32), (255, 0, 0, 128))\n    \n        with Image.open(TEST_FILE) as im:\n            im.save(temp_file, append_images=[provided_im])\n    \n            assert_image_similar_tofile(im, temp_file, 1)\n    \n            with Image.open(temp_file) as reread:\n>               reread.size = (16, 16)\n\n\u001b[1m\u001b[31mr2e_tests/test_1.py\u001b[0m:66: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <PIL.IcnsImagePlugin.IcnsImageFile image mode=RGBA size=1024x1024 at 0x7FC202768940>\nvalue = (16, 16)\n\n    @size.setter\n    def size(self, value) -> None:\n        info_size = value\n        if info_size not in self.info[\"sizes\"] and len(info_size) == 2:\n            info_size = (info_size[0], info_size[1], 1)\n        if (\n            info_size not in self.info[\"sizes\"]\n            and len(info_size) == 3\n            and info_size[2] == 1\n        ):\n            simple_sizes = [\n                (size[0] * size[2], size[1] * size[2]) for size in self.info[\"sizes\"]\n            ]\n            if value in simple_sizes:\n                info_size = self.info[\"sizes\"][simple_sizes.index(value)]\n        if info_size not in self.info[\"sizes\"]:\n            msg = \"This is not one of the allowed sizes of this image\"\n>           raise ValueError(msg)\n\u001b[1m\u001b[31mE           ValueError: This is not one of the allowed sizes of this image\u001b[0m\n\n\u001b[1m\u001b[31msrc/PIL/IcnsImagePlugin.py\u001b[0m:299: ValueError\n\u001b[31m\u001b[1m__________________________________ test_sizes __________________________________\u001b[0m\n\n    def test_sizes() -> None:\n        # Check that we can load all of the sizes, and that the final pixel\n        # dimensions are as expected\n        with Image.open(TEST_FILE) as im:\n            for w, h, r in im.info[\"sizes\"]:\n                wr = w * r\n                hr = h * r\n                im.size = (w, h, r)\n                im.load()\n                assert im.mode == \"RGBA\"\n                assert im.size == (wr, hr)\n    \n                # Test using load() with scale\n                im.size = (w, h)\n>               im.load(scale=r)\n\u001b[1m\u001b[31mE               TypeError: load() got an unexpected keyword argument 'scale'\u001b[0m\n\n\u001b[1m\u001b[31mr2e_tests/test_1.py\u001b[0m:97: TypeError\n\u001b[31m\u001b[1m_______________________________ test_older_icon ________________________________\u001b[0m\n\n    def test_older_icon() -> None:\n        # This icon was made with Icon Composer rather than iconutil; it still\n        # uses PNG rather than JP2, however (since it was made on 10.9).\n        with Image.open(\"Tests/images/pillow2.icns\") as im:\n            for w, h, r in im.info[\"sizes\"]:\n                wr = w * r\n                hr = h * r\n                with Image.open(\"Tests/images/pillow2.icns\") as im2:\n                    im2.size = (w, h)\n>                   im2.load(r)\n\u001b[1m\u001b[31mE                   TypeError: load() takes 1 positional argument but 2 were given\u001b[0m\n\n\u001b[1m\u001b[31mr2e_tests/test_1.py\u001b[0m:115: TypeError\n==================================== PASSES ====================================\n\u001b[36m\u001b[1m=========================== short test summary info ============================\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_sanity\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_load\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_save\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_save_fp\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_getimage\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_not_an_icns_file\u001b[0m\n\u001b[33mSKIPPED\u001b[0m [1] r2e_tests/test_1.py:120: jpg_2000 not available\n\u001b[33mSKIPPED\u001b[0m [1] r2e_tests/test_1.py:156: jpg_2000 not available\n\u001b[31mFAILED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_save_append_images\u001b[0m - ValueError: This is not one of the allowed sizes of this image\n\u001b[31mFAILED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_sizes\u001b[0m - TypeError: load() got an unexpected keyword argument 'scale'\n\u001b[31mFAILED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_older_icon\u001b[0m - TypeError: load() takes 1 positional argument but 2 were given\n\u001b[31m==================== \u001b[31m\u001b[1m3 failed\u001b[0m, \u001b[32m6 passed\u001b[0m, \u001b[33m2 skipped\u001b[0m\u001b[31m in 1.44s\u001b[0m\u001b[31m ====================\u001b[0m\n",
    "old_commit_res_stderr": ""
}
Tests/test_file_icns.py docs/handbook/image-file-formats.rst src/PIL/IcnsImagePlugin.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** `IcnsImageFile.load()` Raises Errors When Handling Scaled Sizes

**Description:**
When attempting to load an ICNS image with specific scaling parameters, the `load()` method in `IcnsImageFile` raises errors. This behavior occurs because the method does not accept a `scale` argument and fails to handle image sizes that include scaling factors.

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

# Attempt to set size without scale and load with scale argument
with Image.open("example.icns") as im:
    im.size = (16, 16)
    im.load(scale=2)
```

**Expected Behavior:**
The image should load successfully with the specified scale without raising any errors.

**Actual Behavior:**
A `TypeError` is raised indicating that the `load()` method received an unexpected keyword argument `scale`:
```
TypeError: load() got an unexpected keyword argument 'scale'
```

---

**Another Scenario:**

```python
from PIL import Image

# Attempt to set size with scale and load without scale argument
with Image.open("example.icns") as im:
    im.size = (16, 16, 1)
    im.load()
```

**Expected Behavior:**
The image size should be set correctly, and `load()` should process the image without issues.

**Actual Behavior:**
A `ValueError` is raised stating that the provided size is not allowed:
```
ValueError: This is not one of the allowed sizes of this image
```
[/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/IcnsImagePlugin.py
#
# The Python Imaging Library.
# $Id$
#
# macOS icns file decoder, based on icns.py by Bob Ippolito.
#
# history:
# 2004-10-09 fl   Turned into a PIL plugin; removed 2.3 dependencies.
# 2020-04-04      Allow saving on all operating systems.
#
# Copyright (c) 2004 by Bob Ippolito.
# Copyright (c) 2004 by Secret Labs.
# Copyright (c) 2004 by Fredrik Lundh.
# Copyright (c) 2014 by Alastair Houghton.
# Copyright (c) 2020 by Pan Jing.
#
# See the README file for information on usage and redistribution.
#
from __future__ import annotations

import io
import os
import struct
import sys
from typing import IO

from . import Image, ImageFile, PngImagePlugin, features

enable_jpeg2k = features.check_codec("jpg_2000")
if enable_jpeg2k:
    from . import Jpeg2KImagePlugin

MAGIC = b"icns"
HEADERSIZE = 8


def nextheader(fobj: IO[bytes]) -> tuple[bytes, int]:
    return struct.unpack(">4sI", fobj.read(HEADERSIZE))


def read_32t(
    fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int]
) -> dict[str, Image.Image]:
    # The 128x128 icon seems to have an extra header for some reason.
    (start, length) = start_length
    fobj.seek(start)
    sig = fobj.read(4)
    if sig != b"\x00\x00\x00\x00":
        msg = "Unknown signature, expecting 0x00000000"
        raise SyntaxError(msg)
    return read_32(fobj, (start + 4, length - 4), size)


def read_32(
    fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int]
) -> dict[str, Image.Image]:
    """
    Read a 32bit RGB icon resource.  Seems to be either uncompressed or
    an RLE packbits-like scheme.
    """
    (start, length) = start_length
    fobj.seek(start)
    pixel_size = (size[0] * size[2], size[1] * size[2])
    sizesq = pixel_size[0] * pixel_size[1]
    if length == sizesq * 3:
        # uncompressed ("RGBRGBGB")
        indata = fobj.read(length)
        im = Image.frombuffer("RGB", pixel_size, indata, "raw", "RGB", 0, 1)
    else:
        # decode image
        im = Image.new("RGB", pixel_size, None)
        for band_ix in range(3):
            data = []
            bytesleft = sizesq
            while bytesleft > 0:
                byte = fobj.read(1)
                if not byte:
                    break
                byte_int = byte[0]
                if byte_int & 0x80:
                    blocksize = byte_int - 125
                    byte = fobj.read(1)
                    for i in range(blocksize):
                        data.append(byte)
                else:
                    blocksize = byte_int + 1
                    data.append(fobj.read(blocksize))
                bytesleft -= blocksize
                if bytesleft <= 0:
                    break
            if bytesleft != 0:
                msg = f"Error reading channel [{repr(bytesleft)} left]"
                raise SyntaxError(msg)
            band = Image.frombuffer("L", pixel_size, b"".join(data), "raw", "L", 0, 1)
            im.im.putband(band.im, band_ix)
    return {"RGB": im}


def read_mk(
    fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int]
) -> dict[str, Image.Image]:
    # Alpha masks seem to be uncompressed
    start = start_length[0]
    fobj.seek(start)
    pixel_size = (size[0] * size[2], size[1] * size[2])
    sizesq = pixel_size[0] * pixel_size[1]
    band = Image.frombuffer("L", pixel_size, fobj.read(sizesq), "raw", "L", 0, 1)
    return {"A": band}


def read_png_or_jpeg2000(
    fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int]
) -> dict[str, Image.Image]:
    (start, length) = start_length
    fobj.seek(start)
    sig = fobj.read(12)

    im: Image.Image
    if sig[:8] == b"\x89PNG\x0d\x0a\x1a\x0a":
        fobj.seek(start)
        im = PngImagePlugin.PngImageFile(fobj)
        Image._decompression_bomb_check(im.size)
        return {"RGBA": im}
    elif (
        sig[:4] == b"\xff\x4f\xff\x51"
        or sig[:4] == b"\x0d\x0a\x87\x0a"
        or sig == b"\x00\x00\x00\x0cjP  \x0d\x0a\x87\x0a"
    ):
        if not enable_jpeg2k:
            msg = (
                "Unsupported icon subimage format (rebuild PIL "
                "with JPEG 2000 support to fix this)"
            )
            raise ValueError(msg)
        # j2k, jpc or j2c
        fobj.seek(start)
        jp2kstream = fobj.read(length)
        f = io.BytesIO(jp2kstream)
        im = Jpeg2KImagePlugin.Jpeg2KImageFile(f)
        Image._decompression_bomb_check(im.size)
        if im.mode != "RGBA":
            im = im.convert("RGBA")
        return {"RGBA": im}
    else:
        msg = "Unsupported icon subimage format"
        raise ValueError(msg)


class IcnsFile:
    SIZES = {
        (512, 512, 2): [(b"ic10", read_png_or_jpeg2000)],
        (512, 512, 1): [(b"ic09", read_png_or_jpeg2000)],
        (256, 256, 2): [(b"ic14", read_png_or_jpeg2000)],
        (256, 256, 1): [(b"ic08", read_png_or_jpeg2000)],
        (128, 128, 2): [(b"ic13", read_png_or_jpeg2000)],
        (128, 128, 1): [
            (b"ic07", read_png_or_jpeg2000),
            (b"it32", read_32t),
            (b"t8mk", read_mk),
        ],
        (64, 64, 1): [(b"icp6", read_png_or_jpeg2000)],
        (32, 32, 2): [(b"ic12", read_png_or_jpeg2000)],
        (48, 48, 1): [(b"ih32", read_32), (b"h8mk", read_mk)],
        (32, 32, 1): [
            (b"icp5", read_png_or_jpeg2000),
            (b"il32", read_32),
            (b"l8mk", read_mk),
        ],
        (16, 16, 2): [(b"ic11", read_png_or_jpeg2000)],
        (16, 16, 1): [
            (b"icp4", read_png_or_jpeg2000),
            (b"is32", read_32),
            (b"s8mk", read_mk),
        ],
    }

    def __init__(self, fobj: IO[bytes]) -> None:
        """
        fobj is a file-like object as an icns resource
        """
        # signature : (start, length)
        self.dct = {}
        self.fobj = fobj
        sig, filesize = nextheader(fobj)
        if not _accept(sig):
            msg = "not an icns file"
            raise SyntaxError(msg)
        i = HEADERSIZE
        while i < filesize:
            sig, blocksize = nextheader(fobj)
            if blocksize <= 0:
                msg = "invalid block header"
                raise SyntaxError(msg)
            i += HEADERSIZE
            blocksize -= HEADERSIZE
            self.dct[sig] = (i, blocksize)
            fobj.seek(blocksize, io.SEEK_CUR)
            i += blocksize

    def itersizes(self) -> list[tuple[int, int, int]]:
        sizes = []
        for size, fmts in self.SIZES.items():
            for fmt, reader in fmts:
                if fmt in self.dct:
                    sizes.append(size)
                    break
        return sizes

    def bestsize(self) -> tuple[int, int, int]:
        sizes = self.itersizes()
        if not sizes:
            msg = "No 32bit icon resources found"
            raise SyntaxError(msg)
        return max(sizes)

    def dataforsize(self, size: tuple[int, int, int]) -> dict[str, Image.Image]:
        """
        Get an icon resource as {channel: array}.  Note that
        the arrays are bottom-up like windows bitmaps and will likely
        need to be flipped or transposed in some way.
        """
        dct = {}
        for code, reader in self.SIZES[size]:
            desc = self.dct.get(code)
            if desc is not None:
                dct.update(reader(self.fobj, desc, size))
        return dct

    def getimage(
        self, size: tuple[int, int] | tuple[int, int, int] | None = None
    ) -> Image.Image:
        if size is None:
            size = self.bestsize()
        elif len(size) == 2:
            size = (size[0], size[1], 1)
        channels = self.dataforsize(size)

        im = channels.get("RGBA")
        if im:
            return im

        im = channels["RGB"].copy()
        try:
            im.putalpha(channels["A"])
        except KeyError:
            pass
        return im


##
# Image plugin for Mac OS icons.


class IcnsImageFile(ImageFile.ImageFile):
    """
    PIL image support for Mac OS .icns files.
    Chooses the best resolution, but will possibly load
    a different size image if you mutate the size attribute
    before calling 'load'.

    The info dictionary has a key 'sizes' that is a list
    of sizes that the icns file has.
    """

    format = "ICNS"
    format_description = "Mac OS icns resource"

    def _open(self) -> None:
        self.icns = IcnsFile(self.fp)
        self._mode = "RGBA"
        self.info["sizes"] = self.icns.itersizes()
        self.best_size = self.icns.bestsize()
        self.size = (
            self.best_size[0] * self.best_size[2],
            self.best_size[1] * self.best_size[2],
        )

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

    @size.setter
    def size(self, value) -> None:
        info_size = value
        if info_size not in self.info["sizes"] and len(info_size) == 2:
            info_size = (info_size[0], info_size[1], 1)
        if (
            info_size not in self.info["sizes"]
            and len(info_size) == 3
            and info_size[2] == 1
        ):
            simple_sizes = [
                (size[0] * size[2], size[1] * size[2]) for size in self.info["sizes"]
            ]
            if value in simple_sizes:
                info_size = self.info["sizes"][simple_sizes.index(value)]
        if info_size not in self.info["sizes"]:
            msg = "This is not one of the allowed sizes of this image"
            raise ValueError(msg)
        self._size = value

    def load(self) -> Image.core.PixelAccess | None:
        if len(self.size) == 3:
            self.best_size = self.size
            self.size = (
                self.best_size[0] * self.best_size[2],
                self.best_size[1] * self.best_size[2],
            )

        px = Image.Image.load(self)
        if self._im is not None and self.im.size == self.size:
            # Already loaded
            return px
        self.load_prepare()
        # This is likely NOT the best way to do it, but whatever.
        im = self.icns.getimage(self.best_size)

        # If this is a PNG or JPEG 2000, it won't be loaded yet
        px = im.load()

        self.im = im.im
        self._mode = im.mode
        self.size = im.size

        return px


def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
    """
    Saves the image as a series of PNG files,
    that are then combined into a .icns file.
    """
    if hasattr(fp, "flush"):
        fp.flush()

    sizes = {
        b"ic07": 128,
        b"ic08": 256,
        b"ic09": 512,
        b"ic10": 1024,
        b"ic11": 32,
        b"ic12": 64,
        b"ic13": 256,
        b"ic14": 512,
    }
    provided_images = {im.width: im for im in im.encoderinfo.get("append_images", [])}
    size_streams = {}
    for size in set(sizes.values()):
        image = (
            provided_images[size]
            if size in provided_images
            else im.resize((size, size))
        )

        temp = io.BytesIO()
        image.save(temp, "png")
        size_streams[size] = temp.getvalue()

    entries = []
    for type, size in sizes.items():
        stream = size_streams[size]
        entries.append((type, HEADERSIZE + len(stream), stream))

    # Header
    fp.write(MAGIC)
    file_length = HEADERSIZE  # Header
    file_length += HEADERSIZE + 8 * len(entries)  # TOC
    file_length += sum(entry[1] for entry in entries)
    fp.write(struct.pack(">i", file_length))

    # TOC
    fp.write(b"TOC ")
    fp.write(struct.pack(">i", HEADERSIZE + len(entries) * HEADERSIZE))
    for entry in entries:
        fp.write(entry[0])
        fp.write(struct.pack(">i", entry[1]))

    # Data
    for entry in entries:
        fp.write(entry[0])
        fp.write(struct.pack(">i", entry[1]))
        fp.write(entry[2])

    if hasattr(fp, "flush"):
        fp.flush()


def _accept(prefix: bytes) -> bool:
    return prefix[:4] == MAGIC


Image.register_open(IcnsImageFile.format, IcnsImageFile, _accept)
Image.register_extension(IcnsImageFile.format, ".icns")

Image.register_save(IcnsImageFile.format, _save)
Image.register_mime(IcnsImageFile.format, "image/icns")

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Syntax: python3 IcnsImagePlugin.py [file]")
        sys.exit()

    with open(sys.argv[1], "rb") as fp:
        imf = IcnsImageFile(fp)
        for size in imf.info["sizes"]:
            width, height, scale = imf.size = size
            imf.save(f"out-{width}-{height}-{scale}.png")
        with Image.open(sys.argv[1]) as im:
            im.save("out.png")
        if sys.platform == "windows":
            os.startfile("out.png")

```
--- 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:** `IcnsImageFile.load()` Raises Errors When Handling Scaled Sizes

**Description:**
When attempting to load an ICNS image with specific scaling parameters, the `load()` method in `IcnsImageFile` raises errors. This behavior occurs because the method does not accept a `scale` argument and fails to handle image sizes that include scaling factors.

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

# Attempt to set size without scale and load with scale argument
with Image.open("example.icns") as im:
    im.size = (16, 16)
    im.load(scale=2)
```

**Expected Behavior:**
The image should load successfully with the specified scale without raising any errors.

**Actual Behavior:**
A `TypeError` is raised indicating that the `load()` method received an unexpected keyword argument `scale`:
```
TypeError: load() got an unexpected keyword argument 'scale'
```

---

**Another Scenario:**

```python
from PIL import Image

# Attempt to set size with scale and load without scale argument
with Image.open("example.icns") as im:
    im.size = (16, 16, 1)
    im.load()
```

**Expected Behavior:**
The image size should be set correctly, and `load()` should process the image without issues.

**Actual Behavior:**
A `ValueError` is raised stating that the provided size is not allowed:
```
ValueError: This is not one of the allowed sizes of this image
```
[/ISSUE]
{
    "\u001b[1mtest_sanity\u001b[0m": "PASSED",
    "\u001b[1mtest_load\u001b[0m": "PASSED",
    "\u001b[1mtest_save\u001b[0m": "PASSED",
    "\u001b[1mtest_save_append_images\u001b[0m": "PASSED",
    "\u001b[1mtest_save_fp\u001b[0m": "PASSED",
    "\u001b[1mtest_sizes\u001b[0m": "PASSED",
    "\u001b[1mtest_older_icon\u001b[0m": "PASSED",
    "\u001b[1mtest_getimage\u001b[0m": "PASSED",
    "\u001b[1mtest_not_an_icns_file\u001b[0m": "PASSED"
}
diff --git a/src/PIL/IcnsImagePlugin.py b/src/PIL/IcnsImagePlugin.py
index ca66aa0fd..e4f486a4f 100644
--- a/src/PIL/IcnsImagePlugin.py
+++ b/src/PIL/IcnsImagePlugin.py
@@ -281,31 +281,30 @@ class IcnsImageFile(ImageFile.ImageFile):
 
     @size.setter
     def size(self, value) -> None:
-        info_size = value
-        if info_size not in self.info["sizes"] and len(info_size) == 2:
-            info_size = (info_size[0], info_size[1], 1)
-        if (
-            info_size not in self.info["sizes"]
-            and len(info_size) == 3
-            and info_size[2] == 1
-        ):
-            simple_sizes = [
-                (size[0] * size[2], size[1] * size[2]) for size in self.info["sizes"]
-            ]
-            if value in simple_sizes:
-                info_size = self.info["sizes"][simple_sizes.index(value)]
-        if info_size not in self.info["sizes"]:
-            msg = "This is not one of the allowed sizes of this image"
-            raise ValueError(msg)
-        self._size = value
-
-    def load(self) -> Image.core.PixelAccess | None:
-        if len(self.size) == 3:
-            self.best_size = self.size
-            self.size = (
-                self.best_size[0] * self.best_size[2],
-                self.best_size[1] * self.best_size[2],
-            )
+        if len(value) == 3:
+            if value in self.info["sizes"]:
+                self._size = value
+                return
+        else:
+            # Check that a matching size exists,
+            # or that there is a scale that would create a size that matches
+            for size in self.info["sizes"]:
+                simple_size = size[0] * size[2], size[1] * size[2]
+                scale = simple_size[0] // value[0]
+                if simple_size[1] / value[1] == scale:
+                    self._size = value
+                    return
+        msg = "This is not one of the allowed sizes of this image"
+        raise ValueError(msg)
+
+    def load(self, scale: int | None = None) -> Image.core.PixelAccess | None:
+        if scale is not None or len(self.size) == 3:
+            if scale is None and len(self.size) == 3:
+                scale = self.size[2]
+            assert scale is not None
+            width, height = self.size[:2]
+            self.size = width * scale, height * scale
+            self.best_size = width, height, scale
 
         px = Image.Image.load(self)
         if self._im is not None and self.im.size == self.size:
 

{"src/PIL/IcnsImagePlugin.py": "#\n# The Python Imaging Library.\n# $Id$\n#\n# macOS icns file decoder, based on icns.py by Bob Ippolito.\n#\n# history:\n# 2004-10-09 fl   Turned into a PIL plugin; removed 2.3 dependencies.\n# 2020-04-04      Allow saving on all operating systems.\n#\n# Copyright (c) 2004 by Bob Ippolito.\n# Copyright (c) 2004 by Secret Labs.\n# Copyright (c) 2004 by Fredrik Lundh.\n# Copyright (c) 2014 by Alastair Houghton.\n# Copyright (c) 2020 by Pan Jing.\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nimport io\nimport os\nimport struct\nimport sys\nfrom typing import IO\n\nfrom . import Image, ImageFile, PngImagePlugin, features\n\nenable_jpeg2k = features.check_codec(\"jpg_2000\")\nif enable_jpeg2k:\n    from . import Jpeg2KImagePlugin\n\nMAGIC = b\"icns\"\nHEADERSIZE = 8\n\n\ndef nextheader(fobj: IO[bytes]) -> tuple[bytes, int]:\n    return struct.unpack(\">4sI\", fobj.read(HEADERSIZE))\n\n\ndef read_32t(\n    fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int]\n) -> dict[str, Image.Image]:\n    # The 128x128 icon seems to have an extra header for some reason.\n    (start, length) = start_length\n    fobj.seek(start)\n    sig = fobj.read(4)\n    if sig != b\"\\x00\\x00\\x00\\x00\":\n        msg = \"Unknown signature, expecting 0x00000000\"\n        raise SyntaxError(msg)\n    return read_32(fobj, (start + 4, length - 4), size)\n\n\ndef read_32(\n    fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int]\n) -> dict[str, Image.Image]:\n    \"\"\"\n    Read a 32bit RGB icon resource.  Seems to be either uncompressed or\n    an RLE packbits-like scheme.\n    \"\"\"\n    (start, length) = start_length\n    fobj.seek(start)\n    pixel_size = (size[0] * size[2], size[1] * size[2])\n    sizesq = pixel_size[0] * pixel_size[1]\n    if length == sizesq * 3:\n        # uncompressed (\"RGBRGBGB\")\n        indata = fobj.read(length)\n        im = Image.frombuffer(\"RGB\", pixel_size, indata, \"raw\", \"RGB\", 0, 1)\n    else:\n        # decode image\n        im = Image.new(\"RGB\", pixel_size, None)\n        for band_ix in range(3):\n            data = []\n            bytesleft = sizesq\n            while bytesleft > 0:\n                byte = fobj.read(1)\n                if not byte:\n                    break\n                byte_int = byte[0]\n                if byte_int & 0x80:\n                    blocksize = byte_int - 125\n                    byte = fobj.read(1)\n                    for i in range(blocksize):\n                        data.append(byte)\n                else:\n                    blocksize = byte_int + 1\n                    data.append(fobj.read(blocksize))\n                bytesleft -= blocksize\n                if bytesleft <= 0:\n                    break\n            if bytesleft != 0:\n                msg = f\"Error reading channel [{repr(bytesleft)} left]\"\n                raise SyntaxError(msg)\n            band = Image.frombuffer(\"L\", pixel_size, b\"\".join(data), \"raw\", \"L\", 0, 1)\n            im.im.putband(band.im, band_ix)\n    return {\"RGB\": im}\n\n\ndef read_mk(\n    fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int]\n) -> dict[str, Image.Image]:\n    # Alpha masks seem to be uncompressed\n    start = start_length[0]\n    fobj.seek(start)\n    pixel_size = (size[0] * size[2], size[1] * size[2])\n    sizesq = pixel_size[0] * pixel_size[1]\n    band = Image.frombuffer(\"L\", pixel_size, fobj.read(sizesq), \"raw\", \"L\", 0, 1)\n    return {\"A\": band}\n\n\ndef read_png_or_jpeg2000(\n    fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int]\n) -> dict[str, Image.Image]:\n    (start, length) = start_length\n    fobj.seek(start)\n    sig = fobj.read(12)\n\n    im: Image.Image\n    if sig[:8] == b\"\\x89PNG\\x0d\\x0a\\x1a\\x0a\":\n        fobj.seek(start)\n        im = PngImagePlugin.PngImageFile(fobj)\n        Image._decompression_bomb_check(im.size)\n        return {\"RGBA\": im}\n    elif (\n        sig[:4] == b\"\\xff\\x4f\\xff\\x51\"\n        or sig[:4] == b\"\\x0d\\x0a\\x87\\x0a\"\n        or sig == b\"\\x00\\x00\\x00\\x0cjP  \\x0d\\x0a\\x87\\x0a\"\n    ):\n        if not enable_jpeg2k:\n            msg = (\n                \"Unsupported icon subimage format (rebuild PIL \"\n                \"with JPEG 2000 support to fix this)\"\n            )\n            raise ValueError(msg)\n        # j2k, jpc or j2c\n        fobj.seek(start)\n        jp2kstream = fobj.read(length)\n        f = io.BytesIO(jp2kstream)\n        im = Jpeg2KImagePlugin.Jpeg2KImageFile(f)\n        Image._decompression_bomb_check(im.size)\n        if im.mode != \"RGBA\":\n            im = im.convert(\"RGBA\")\n        return {\"RGBA\": im}\n    else:\n        msg = \"Unsupported icon subimage format\"\n        raise ValueError(msg)\n\n\nclass IcnsFile:\n    SIZES = {\n        (512, 512, 2): [(b\"ic10\", read_png_or_jpeg2000)],\n        (512, 512, 1): [(b\"ic09\", read_png_or_jpeg2000)],\n        (256, 256, 2): [(b\"ic14\", read_png_or_jpeg2000)],\n        (256, 256, 1): [(b\"ic08\", read_png_or_jpeg2000)],\n        (128, 128, 2): [(b\"ic13\", read_png_or_jpeg2000)],\n        (128, 128, 1): [\n            (b\"ic07\", read_png_or_jpeg2000),\n            (b\"it32\", read_32t),\n            (b\"t8mk\", read_mk),\n        ],\n        (64, 64, 1): [(b\"icp6\", read_png_or_jpeg2000)],\n        (32, 32, 2): [(b\"ic12\", read_png_or_jpeg2000)],\n        (48, 48, 1): [(b\"ih32\", read_32), (b\"h8mk\", read_mk)],\n        (32, 32, 1): [\n            (b\"icp5\", read_png_or_jpeg2000),\n            (b\"il32\", read_32),\n            (b\"l8mk\", read_mk),\n        ],\n        (16, 16, 2): [(b\"ic11\", read_png_or_jpeg2000)],\n        (16, 16, 1): [\n            (b\"icp4\", read_png_or_jpeg2000),\n            (b\"is32\", read_32),\n            (b\"s8mk\", read_mk),\n        ],\n    }\n\n    def __init__(self, fobj: IO[bytes]) -> None:\n        \"\"\"\n        fobj is a file-like object as an icns resource\n        \"\"\"\n        # signature : (start, length)\n        self.dct = {}\n        self.fobj = fobj\n        sig, filesize = nextheader(fobj)\n        if not _accept(sig):\n            msg = \"not an icns file\"\n            raise SyntaxError(msg)\n        i = HEADERSIZE\n        while i < filesize:\n            sig, blocksize = nextheader(fobj)\n            if blocksize <= 0:\n                msg = \"invalid block header\"\n                raise SyntaxError(msg)\n            i += HEADERSIZE\n            blocksize -= HEADERSIZE\n            self.dct[sig] = (i, blocksize)\n            fobj.seek(blocksize, io.SEEK_CUR)\n            i += blocksize\n\n    def itersizes(self) -> list[tuple[int, int, int]]:\n        sizes = []\n        for size, fmts in self.SIZES.items():\n            for fmt, reader in fmts:\n                if fmt in self.dct:\n                    sizes.append(size)\n                    break\n        return sizes\n\n    def bestsize(self) -> tuple[int, int, int]:\n        sizes = self.itersizes()\n        if not sizes:\n            msg = \"No 32bit icon resources found\"\n            raise SyntaxError(msg)\n        return max(sizes)\n\n    def dataforsize(self, size: tuple[int, int, int]) -> dict[str, Image.Image]:\n        \"\"\"\n        Get an icon resource as {channel: array}.  Note that\n        the arrays are bottom-up like windows bitmaps and will likely\n        need to be flipped or transposed in some way.\n        \"\"\"\n        dct = {}\n        for code, reader in self.SIZES[size]:\n            desc = self.dct.get(code)\n            if desc is not None:\n                dct.update(reader(self.fobj, desc, size))\n        return dct\n\n    def getimage(\n        self, size: tuple[int, int] | tuple[int, int, int] | None = None\n    ) -> Image.Image:\n        if size is None:\n            size = self.bestsize()\n        elif len(size) == 2:\n            size = (size[0], size[1], 1)\n        channels = self.dataforsize(size)\n\n        im = channels.get(\"RGBA\")\n        if im:\n            return im\n\n        im = channels[\"RGB\"].copy()\n        try:\n            im.putalpha(channels[\"A\"])\n        except KeyError:\n            pass\n        return im\n\n\n##\n# Image plugin for Mac OS icons.\n\n\nclass IcnsImageFile(ImageFile.ImageFile):\n    \"\"\"\n    PIL image support for Mac OS .icns files.\n    Chooses the best resolution, but will possibly load\n    a different size image if you mutate the size attribute\n    before calling 'load'.\n\n    The info dictionary has a key 'sizes' that is a list\n    of sizes that the icns file has.\n    \"\"\"\n\n    format = \"ICNS\"\n    format_description = \"Mac OS icns resource\"\n\n    def _open(self) -> None:\n        self.icns = IcnsFile(self.fp)\n        self._mode = \"RGBA\"\n        self.info[\"sizes\"] = self.icns.itersizes()\n        self.best_size = self.icns.bestsize()\n        self.size = (\n            self.best_size[0] * self.best_size[2],\n            self.best_size[1] * self.best_size[2],\n        )\n\n    @property\n    def size(self):\n        return self._size\n\n    @size.setter\n    def size(self, value) -> None:\n        info_size = value\n        if info_size not in self.info[\"sizes\"] and len(info_size) == 2:\n            info_size = (info_size[0], info_size[1], 1)\n        if (\n            info_size not in self.info[\"sizes\"]\n            and len(info_size) == 3\n            and info_size[2] == 1\n        ):\n            simple_sizes = [\n                (size[0] * size[2], size[1] * size[2]) for size in self.info[\"sizes\"]\n            ]\n            if value in simple_sizes:\n                info_size = self.info[\"sizes\"][simple_sizes.index(value)]\n        if info_size not in self.info[\"sizes\"]:\n            msg = \"This is not one of the allowed sizes of this image\"\n            raise ValueError(msg)\n        self._size = value\n\n    def load(self) -> Image.core.PixelAccess | None:\n        if len(self.size) == 3:\n            self.best_size = self.size\n            self.size = (\n                self.best_size[0] * self.best_size[2],\n                self.best_size[1] * self.best_size[2],\n            )\n\n        px = Image.Image.load(self)\n        if self._im is not None and self.im.size == self.size:\n            # Already loaded\n            return px\n        self.load_prepare()\n        # This is likely NOT the best way to do it, but whatever.\n        im = self.icns.getimage(self.best_size)\n\n        # If this is a PNG or JPEG 2000, it won't be loaded yet\n        px = im.load()\n\n        self.im = im.im\n        self._mode = im.mode\n        self.size = im.size\n\n        return px\n\n\ndef _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:\n    \"\"\"\n    Saves the image as a series of PNG files,\n    that are then combined into a .icns file.\n    \"\"\"\n    if hasattr(fp, \"flush\"):\n        fp.flush()\n\n    sizes = {\n        b\"ic07\": 128,\n        b\"ic08\": 256,\n        b\"ic09\": 512,\n        b\"ic10\": 1024,\n        b\"ic11\": 32,\n        b\"ic12\": 64,\n        b\"ic13\": 256,\n        b\"ic14\": 512,\n    }\n    provided_images = {im.width: im for im in im.encoderinfo.get(\"append_images\", [])}\n    size_streams = {}\n    for size in set(sizes.values()):\n        image = (\n            provided_images[size]\n            if size in provided_images\n            else im.resize((size, size))\n        )\n\n        temp = io.BytesIO()\n        image.save(temp, \"png\")\n        size_streams[size] = temp.getvalue()\n\n    entries = []\n    for type, size in sizes.items():\n        stream = size_streams[size]\n        entries.append((type, HEADERSIZE + len(stream), stream))\n\n    # Header\n    fp.write(MAGIC)\n    file_length = HEADERSIZE  # Header\n    file_length += HEADERSIZE + 8 * len(entries)  # TOC\n    file_length += sum(entry[1] for entry in entries)\n    fp.write(struct.pack(\">i\", file_length))\n\n    # TOC\n    fp.write(b\"TOC \")\n    fp.write(struct.pack(\">i\", HEADERSIZE + len(entries) * HEADERSIZE))\n    for entry in entries:\n        fp.write(entry[0])\n        fp.write(struct.pack(\">i\", entry[1]))\n\n    # Data\n    for entry in entries:\n        fp.write(entry[0])\n        fp.write(struct.pack(\">i\", entry[1]))\n        fp.write(entry[2])\n\n    if hasattr(fp, \"flush\"):\n        fp.flush()\n\n\ndef _accept(prefix: bytes) -> bool:\n    return prefix[:4] == MAGIC\n\n\nImage.register_open(IcnsImageFile.format, IcnsImageFile, _accept)\nImage.register_extension(IcnsImageFile.format, \".icns\")\n\nImage.register_save(IcnsImageFile.format, _save)\nImage.register_mime(IcnsImageFile.format, \"image/icns\")\n\nif __name__ == \"__main__\":\n    if len(sys.argv) < 2:\n        print(\"Syntax: python3 IcnsImagePlugin.py [file]\")\n        sys.exit()\n\n    with open(sys.argv[1], \"rb\") as fp:\n        imf = IcnsImageFile(fp)\n        for size in imf.info[\"sizes\"]:\n            width, height, scale = imf.size = size\n            imf.save(f\"out-{width}-{height}-{scale}.png\")\n        with Image.open(sys.argv[1]) as im:\n            im.save(\"out.png\")\n        if sys.platform == \"windows\":\n            os.startfile(\"out.png\")\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:** `IcnsImageFile.load()` Raises Errors When Handling Scaled Sizes

**Description:**
When attempting to load an ICNS image with specific scaling parameters, the `load()` method in `IcnsImageFile` raises errors. This behavior occurs because the method does not accept a `scale` argument and fails to handle image sizes that include scaling factors.

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

# Attempt to set size without scale and load with scale argument
with Image.open("example.icns") as im:
    im.size = (16, 16)
    im.load(scale=2)
```

**Expected Behavior:**
The image should load successfully with the specified scale without raising any errors.

**Actual Behavior:**
A `TypeError` is raised indicating that the `load()` method received an unexpected keyword argument `scale`:
```
TypeError: load() got an unexpected keyword argument 'scale'
```

---

**Another Scenario:**

```python
from PIL import Image

# Attempt to set size with scale and load without scale argument
with Image.open("example.icns") as im:
    im.size = (16, 16, 1)
    im.load()
```

**Expected Behavior:**
The image size should be set correctly, and `load()` should process the image without issues.

**Actual Behavior:**
A `ValueError` is raised stating that the provided size is not allowed:
```
ValueError: This is not one of the allowed sizes of this image
```
[/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/IcnsImagePlugin.py
#
# The Python Imaging Library.
# $Id$
#
# macOS icns file decoder, based on icns.py by Bob Ippolito.
#
# history:
# 2004-10-09 fl   Turned into a PIL plugin; removed 2.3 dependencies.
# 2020-04-04      Allow saving on all operating systems.
#
# Copyright (c) 2004 by Bob Ippolito.
# Copyright (c) 2004 by Secret Labs.
# Copyright (c) 2004 by Fredrik Lundh.
# Copyright (c) 2014 by Alastair Houghton.
# Copyright (c) 2020 by Pan Jing.
#
# See the README file for information on usage and redistribution.
#
from __future__ import annotations

import io
import os
import struct
import sys
from typing import IO

from . import Image, ImageFile, PngImagePlugin, features

enable_jpeg2k = features.check_codec("jpg_2000")
if enable_jpeg2k:
    from . import Jpeg2KImagePlugin

MAGIC = b"icns"
HEADERSIZE = 8


def nextheader(fobj: IO[bytes]) -> tuple[bytes, int]:
    return struct.unpack(">4sI", fobj.read(HEADERSIZE))


def read_32t(
    fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int]
) -> dict[str, Image.Image]:
    # The 128x128 icon seems to have an extra header for some reason.
    (start, length) = start_length
    fobj.seek(start)
    sig = fobj.read(4)
    if sig != b"\x00\x00\x00\x00":
        msg = "Unknown signature, expecting 0x00000000"
        raise SyntaxError(msg)
    return read_32(fobj, (start + 4, length - 4), size)


def read_32(
    fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int]
) -> dict[str, Image.Image]:
    """
    Read a 32bit RGB icon resource.  Seems to be either uncompressed or
    an RLE packbits-like scheme.
    """
    (start, length) = start_length
    fobj.seek(start)
    pixel_size = (size[0] * size[2], size[1] * size[2])
    sizesq = pixel_size[0] * pixel_size[1]
    if length == sizesq * 3:
        # uncompressed ("RGBRGBGB")
        indata = fobj.read(length)
        im = Image.frombuffer("RGB", pixel_size, indata, "raw", "RGB", 0, 1)
    else:
        # decode image
        im = Image.new("RGB", pixel_size, None)
        for band_ix in range(3):
            data = []
            bytesleft = sizesq
            while bytesleft > 0:
                byte = fobj.read(1)
                if not byte:
                    break
                byte_int = byte[0]
                if byte_int & 0x80:
                    blocksize = byte_int - 125
                    byte = fobj.read(1)
                    for i in range(blocksize):
                        data.append(byte)
                else:
                    blocksize = byte_int + 1
                    data.append(fobj.read(blocksize))
                bytesleft -= blocksize
                if bytesleft <= 0:
                    break
            if bytesleft != 0:
                msg = f"Error reading channel [{repr(bytesleft)} left]"
                raise SyntaxError(msg)
            band = Image.frombuffer("L", pixel_size, b"".join(data), "raw", "L", 0, 1)
            im.im.putband(band.im, band_ix)
    return {"RGB": im}


def read_mk(
    fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int]
) -> dict[str, Image.Image]:
    # Alpha masks seem to be uncompressed
    start = start_length[0]
    fobj.seek(start)
    pixel_size = (size[0] * size[2], size[1] * size[2])
    sizesq = pixel_size[0] * pixel_size[1]
    band = Image.frombuffer("L", pixel_size, fobj.read(sizesq), "raw", "L", 0, 1)
    return {"A": band}


def read_png_or_jpeg2000(
    fobj: IO[bytes], start_length: tuple[int, int], size: tuple[int, int, int]
) -> dict[str, Image.Image]:
    (start, length) = start_length
    fobj.seek(start)
    sig = fobj.read(12)

    im: Image.Image
    if sig[:8] == b"\x89PNG\x0d\x0a\x1a\x0a":
        fobj.seek(start)
        im = PngImagePlugin.PngImageFile(fobj)
        Image._decompression_bomb_check(im.size)
        return {"RGBA": im}
    elif (
        sig[:4] == b"\xff\x4f\xff\x51"
        or sig[:4] == b"\x0d\x0a\x87\x0a"
        or sig == b"\x00\x00\x00\x0cjP  \x0d\x0a\x87\x0a"
    ):
        if not enable_jpeg2k:
            msg = (
                "Unsupported icon subimage format (rebuild PIL "
                "with JPEG 2000 support to fix this)"
            )
            raise ValueError(msg)
        # j2k, jpc or j2c
        fobj.seek(start)
        jp2kstream = fobj.read(length)
        f = io.BytesIO(jp2kstream)
        im = Jpeg2KImagePlugin.Jpeg2KImageFile(f)
        Image._decompression_bomb_check(im.size)
        if im.mode != "RGBA":
            im = im.convert("RGBA")
        return {"RGBA": im}
    else:
        msg = "Unsupported icon subimage format"
        raise ValueError(msg)


class IcnsFile:
    SIZES = {
        (512, 512, 2): [(b"ic10", read_png_or_jpeg2000)],
        (512, 512, 1): [(b"ic09", read_png_or_jpeg2000)],
        (256, 256, 2): [(b"ic14", read_png_or_jpeg2000)],
        (256, 256, 1): [(b"ic08", read_png_or_jpeg2000)],
        (128, 128, 2): [(b"ic13", read_png_or_jpeg2000)],
        (128, 128, 1): [
            (b"ic07", read_png_or_jpeg2000),
            (b"it32", read_32t),
            (b"t8mk", read_mk),
        ],
        (64, 64, 1): [(b"icp6", read_png_or_jpeg2000)],
        (32, 32, 2): [(b"ic12", read_png_or_jpeg2000)],
        (48, 48, 1): [(b"ih32", read_32), (b"h8mk", read_mk)],
        (32, 32, 1): [
            (b"icp5", read_png_or_jpeg2000),
            (b"il32", read_32),
            (b"l8mk", read_mk),
        ],
        (16, 16, 2): [(b"ic11", read_png_or_jpeg2000)],
        (16, 16, 1): [
            (b"icp4", read_png_or_jpeg2000),
            (b"is32", read_32),
            (b"s8mk", read_mk),
        ],
    }

    def __init__(self, fobj: IO[bytes]) -> None:
        """
        fobj is a file-like object as an icns resource
        """
        # signature : (start, length)
        self.dct = {}
        self.fobj = fobj
        sig, filesize = nextheader(fobj)
        if not _accept(sig):
            msg = "not an icns file"
            raise SyntaxError(msg)
        i = HEADERSIZE
        while i < filesize:
            sig, blocksize = nextheader(fobj)
            if blocksize <= 0:
                msg = "invalid block header"
                raise SyntaxError(msg)
            i += HEADERSIZE
            blocksize -= HEADERSIZE
            self.dct[sig] = (i, blocksize)
            fobj.seek(blocksize, io.SEEK_CUR)
            i += blocksize

    def itersizes(self) -> list[tuple[int, int, int]]:
        sizes = []
        for size, fmts in self.SIZES.items():
            for fmt, reader in fmts:
                if fmt in self.dct:
                    sizes.append(size)
                    break
        return sizes

    def bestsize(self) -> tuple[int, int, int]:
        sizes = self.itersizes()
        if not sizes:
            msg = "No 32bit icon resources found"
            raise SyntaxError(msg)
        return max(sizes)

    def dataforsize(self, size: tuple[int, int, int]) -> dict[str, Image.Image]:
        """
        Get an icon resource as {channel: array}.  Note that
        the arrays are bottom-up like windows bitmaps and will likely
        need to be flipped or transposed in some way.
        """
        dct = {}
        for code, reader in self.SIZES[size]:
            desc = self.dct.get(code)
            if desc is not None:
                dct.update(reader(self.fobj, desc, size))
        return dct

    def getimage(
        self, size: tuple[int, int] | tuple[int, int, int] | None = None
    ) -> Image.Image:
        if size is None:
            size = self.bestsize()
        elif len(size) == 2:
            size = (size[0], size[1], 1)
        channels = self.dataforsize(size)

        im = channels.get("RGBA")
        if im:
            return im

        im = channels["RGB"].copy()
        try:
            im.putalpha(channels["A"])
        except KeyError:
            pass
        return im


##
# Image plugin for Mac OS icons.


class IcnsImageFile(ImageFile.ImageFile):
    """
    PIL image support for Mac OS .icns files.
    Chooses the best resolution, but will possibly load
    a different size image if you mutate the size attribute
    before calling 'load'.

    The info dictionary has a key 'sizes' that is a list
    of sizes that the icns file has.
    """

    format = "ICNS"
    format_description = "Mac OS icns resource"

    def _open(self) -> None:
        self.icns = IcnsFile(self.fp)
        self._mode = "RGBA"
        self.info["sizes"] = self.icns.itersizes()
        self.best_size = self.icns.bestsize()
        self.size = (
            self.best_size[0] * self.best_size[2],
            self.best_size[1] * self.best_size[2],
        )

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

    @size.setter
    def size(self, value) -> None:
        info_size = value
        if info_size not in self.info["sizes"] and len(info_size) == 2:
            info_size = (info_size[0], info_size[1], 1)
        if (
            info_size not in self.info["sizes"]
            and len(info_size) == 3
            and info_size[2] == 1
        ):
            simple_sizes = [
                (size[0] * size[2], size[1] * size[2]) for size in self.info["sizes"]
            ]
            if value in simple_sizes:
                info_size = self.info["sizes"][simple_sizes.index(value)]
        if info_size not in self.info["sizes"]:
            msg = "This is not one of the allowed sizes of this image"
            raise ValueError(msg)
        self._size = value

    def load(self) -> Image.core.PixelAccess | None:
        if len(self.size) == 3:
            self.best_size = self.size
            self.size = (
                self.best_size[0] * self.best_size[2],
                self.best_size[1] * self.best_size[2],
            )

        px = Image.Image.load(self)
        if self._im is not None and self.im.size == self.size:
            # Already loaded
            return px
        self.load_prepare()
        # This is likely NOT the best way to do it, but whatever.
        im = self.icns.getimage(self.best_size)

        # If this is a PNG or JPEG 2000, it won't be loaded yet
        px = im.load()

        self.im = im.im
        self._mode = im.mode
        self.size = im.size

        return px


def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
    """
    Saves the image as a series of PNG files,
    that are then combined into a .icns file.
    """
    if hasattr(fp, "flush"):
        fp.flush()

    sizes = {
        b"ic07": 128,
        b"ic08": 256,
        b"ic09": 512,
        b"ic10": 1024,
        b"ic11": 32,
        b"ic12": 64,
        b"ic13": 256,
        b"ic14": 512,
    }
    provided_images = {im.width: im for im in im.encoderinfo.get("append_images", [])}
    size_streams = {}
    for size in set(sizes.values()):
        image = (
            provided_images[size]
            if size in provided_images
            else im.resize((size, size))
        )

        temp = io.BytesIO()
        image.save(temp, "png")
        size_streams[size] = temp.getvalue()

    entries = []
    for type, size in sizes.items():
        stream = size_streams[size]
        entries.append((type, HEADERSIZE + len(stream), stream))

    # Header
    fp.write(MAGIC)
    file_length = HEADERSIZE  # Header
    file_length += HEADERSIZE + 8 * len(entries)  # TOC
    file_length += sum(entry[1] for entry in entries)
    fp.write(struct.pack(">i", file_length))

    # TOC
    fp.write(b"TOC ")
    fp.write(struct.pack(">i", HEADERSIZE + len(entries) * HEADERSIZE))
    for entry in entries:
        fp.write(entry[0])
        fp.write(struct.pack(">i", entry[1]))

    # Data
    for entry in entries:
        fp.write(entry[0])
        fp.write(struct.pack(">i", entry[1]))
        fp.write(entry[2])

    if hasattr(fp, "flush"):
        fp.flush()


def _accept(prefix: bytes) -> bool:
    return prefix[:4] == MAGIC


Image.register_open(IcnsImageFile.format, IcnsImageFile, _accept)
Image.register_extension(IcnsImageFile.format, ".icns")

Image.register_save(IcnsImageFile.format, _save)
Image.register_mime(IcnsImageFile.format, "image/icns")

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Syntax: python3 IcnsImagePlugin.py [file]")
        sys.exit()

    with open(sys.argv[1], "rb") as fp:
        imf = IcnsImageFile(fp)
        for size in imf.info["sizes"]:
            width, height, scale = imf.size = size
            imf.save(f"out-{width}-{height}-{scale}.png")
        with Image.open(sys.argv[1]) as im:
            im.save("out.png")
        if sys.platform == "windows":
            os.startfile("out.png")

```
--- 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