{
    "file_diffs": [
        {
            "old_file_content": "import io\n\nimport pytest\n\nfrom PIL import IcoImagePlugin, Image, ImageDraw\n\nfrom .helper import assert_image_equal, assert_image_equal_tofile, hopper\n\nTEST_ICO_FILE = \"Tests/images/hopper.ico\"\n\n\ndef test_sanity():\n    with Image.open(TEST_ICO_FILE) as im:\n        im.load()\n    assert im.mode == \"RGBA\"\n    assert im.size == (16, 16)\n    assert im.format == \"ICO\"\n    assert im.get_format_mimetype() == \"image/x-icon\"\n\n\ndef test_black_and_white():\n    with Image.open(\"Tests/images/black_and_white.ico\") as im:\n        assert im.mode == \"RGBA\"\n        assert im.size == (16, 16)\n\n\ndef test_invalid_file():\n    with open(\"Tests/images/flower.jpg\", \"rb\") as fp:\n        with pytest.raises(SyntaxError):\n            IcoImagePlugin.IcoImageFile(fp)\n\n\ndef test_save_to_bytes():\n    output = io.BytesIO()\n    im = hopper()\n    im.save(output, \"ico\", sizes=[(32, 32), (64, 64)])\n\n    # The default image\n    output.seek(0)\n    with Image.open(output) as reloaded:\n        assert reloaded.info[\"sizes\"] == {(32, 32), (64, 64)}\n\n        assert im.mode == reloaded.mode\n        assert (64, 64) == reloaded.size\n        assert reloaded.format == \"ICO\"\n        assert_image_equal(reloaded, hopper().resize((64, 64), Image.LANCZOS))\n\n    # The other one\n    output.seek(0)\n    with Image.open(output) as reloaded:\n        reloaded.size = (32, 32)\n\n        assert im.mode == reloaded.mode\n        assert (32, 32) == reloaded.size\n        assert reloaded.format == \"ICO\"\n        assert_image_equal(reloaded, hopper().resize((32, 32), Image.LANCZOS))\n\n\ndef test_incorrect_size():\n    with Image.open(TEST_ICO_FILE) as im:\n        with pytest.raises(ValueError):\n            im.size = (1, 1)\n\n\ndef test_save_256x256(tmp_path):\n    \"\"\"Issue #2264 https://github.com/python-pillow/Pillow/issues/2264\"\"\"\n    # Arrange\n    with Image.open(\"Tests/images/hopper_256x256.ico\") as im:\n        outfile = str(tmp_path / \"temp_saved_hopper_256x256.ico\")\n\n        # Act\n        im.save(outfile)\n    with Image.open(outfile) as im_saved:\n\n        # Assert\n        assert im_saved.size == (256, 256)\n\n\ndef test_only_save_relevant_sizes(tmp_path):\n    \"\"\"Issue #2266 https://github.com/python-pillow/Pillow/issues/2266\n    Should save in 16x16, 24x24, 32x32, 48x48 sizes\n    and not in 16x16, 24x24, 32x32, 48x48, 48x48, 48x48, 48x48 sizes\n    \"\"\"\n    # Arrange\n    with Image.open(\"Tests/images/python.ico\") as im:  # 16x16, 32x32, 48x48\n        outfile = str(tmp_path / \"temp_saved_python.ico\")\n        # Act\n        im.save(outfile)\n\n    with Image.open(outfile) as im_saved:\n        # Assert\n        assert im_saved.info[\"sizes\"] == {(16, 16), (24, 24), (32, 32), (48, 48)}\n\n\ndef test_save_append_images(tmp_path):\n    # append_images should be used for scaled down versions of the image\n    im = hopper(\"RGBA\")\n    provided_im = Image.new(\"RGBA\", (32, 32), (255, 0, 0))\n    outfile = str(tmp_path / \"temp_saved_multi_icon.ico\")\n    im.save(outfile, sizes=[(32, 32), (128, 128)], append_images=[provided_im])\n\n    with Image.open(outfile) as reread:\n        assert_image_equal(reread, hopper(\"RGBA\"))\n\n        reread.size = (32, 32)\n        assert_image_equal(reread, provided_im)\n\n\ndef test_unexpected_size():\n    # This image has been manually hexedited to state that it is 16x32\n    # while the image within is still 16x16\n    def open():\n        with Image.open(\"Tests/images/hopper_unexpected.ico\") as im:\n            assert im.size == (16, 16)\n\n    pytest.warns(UserWarning, open)\n\n\ndef test_draw_reloaded(tmp_path):\n    with Image.open(TEST_ICO_FILE) as im:\n        outfile = str(tmp_path / \"temp_saved_hopper_draw.ico\")\n\n        draw = ImageDraw.Draw(im)\n        draw.line((0, 0) + im.size, \"#f00\")\n        im.save(outfile)\n\n    with Image.open(outfile) as im:\n        assert_image_equal_tofile(im, \"Tests/images/hopper_draw.ico\")\n",
            "new_file_content": "import io\n\nimport pytest\n\nfrom PIL import IcoImagePlugin, Image, ImageDraw\n\nfrom .helper import assert_image_equal, assert_image_equal_tofile, hopper\n\nTEST_ICO_FILE = \"Tests/images/hopper.ico\"\n\n\ndef test_sanity():\n    with Image.open(TEST_ICO_FILE) as im:\n        im.load()\n    assert im.mode == \"RGBA\"\n    assert im.size == (16, 16)\n    assert im.format == \"ICO\"\n    assert im.get_format_mimetype() == \"image/x-icon\"\n\n\ndef test_black_and_white():\n    with Image.open(\"Tests/images/black_and_white.ico\") as im:\n        assert im.mode == \"RGBA\"\n        assert im.size == (16, 16)\n\n\ndef test_invalid_file():\n    with open(\"Tests/images/flower.jpg\", \"rb\") as fp:\n        with pytest.raises(SyntaxError):\n            IcoImagePlugin.IcoImageFile(fp)\n\n\ndef test_save_to_bytes():\n    output = io.BytesIO()\n    im = hopper()\n    im.save(output, \"ico\", sizes=[(32, 32), (64, 64)])\n\n    # The default image\n    output.seek(0)\n    with Image.open(output) as reloaded:\n        assert reloaded.info[\"sizes\"] == {(32, 32), (64, 64)}\n\n        assert im.mode == reloaded.mode\n        assert (64, 64) == reloaded.size\n        assert reloaded.format == \"ICO\"\n        assert_image_equal(reloaded, hopper().resize((64, 64), Image.LANCZOS))\n\n    # The other one\n    output.seek(0)\n    with Image.open(output) as reloaded:\n        reloaded.size = (32, 32)\n\n        assert im.mode == reloaded.mode\n        assert (32, 32) == reloaded.size\n        assert reloaded.format == \"ICO\"\n        assert_image_equal(reloaded, hopper().resize((32, 32), Image.LANCZOS))\n\n\n@pytest.mark.parametrize(\"mode\", (\"1\", \"L\", \"P\", \"RGB\", \"RGBA\"))\ndef test_save_to_bytes_bmp(mode):\n    output = io.BytesIO()\n    im = hopper(mode)\n    im.save(output, \"ico\", bitmap_format=\"bmp\", sizes=[(32, 32), (64, 64)])\n\n    # The default image\n    output.seek(0)\n    with Image.open(output) as reloaded:\n        assert reloaded.info[\"sizes\"] == {(32, 32), (64, 64)}\n\n        assert \"RGBA\" == reloaded.mode\n        assert (64, 64) == reloaded.size\n        assert reloaded.format == \"ICO\"\n        im = hopper(mode).resize((64, 64), Image.LANCZOS).convert(\"RGBA\")\n        assert_image_equal(reloaded, im)\n\n    # The other one\n    output.seek(0)\n    with Image.open(output) as reloaded:\n        reloaded.size = (32, 32)\n\n        assert \"RGBA\" == reloaded.mode\n        assert (32, 32) == reloaded.size\n        assert reloaded.format == \"ICO\"\n        im = hopper(mode).resize((32, 32), Image.LANCZOS).convert(\"RGBA\")\n        assert_image_equal(reloaded, im)\n\n\ndef test_incorrect_size():\n    with Image.open(TEST_ICO_FILE) as im:\n        with pytest.raises(ValueError):\n            im.size = (1, 1)\n\n\ndef test_save_256x256(tmp_path):\n    \"\"\"Issue #2264 https://github.com/python-pillow/Pillow/issues/2264\"\"\"\n    # Arrange\n    with Image.open(\"Tests/images/hopper_256x256.ico\") as im:\n        outfile = str(tmp_path / \"temp_saved_hopper_256x256.ico\")\n\n        # Act\n        im.save(outfile)\n    with Image.open(outfile) as im_saved:\n\n        # Assert\n        assert im_saved.size == (256, 256)\n\n\ndef test_only_save_relevant_sizes(tmp_path):\n    \"\"\"Issue #2266 https://github.com/python-pillow/Pillow/issues/2266\n    Should save in 16x16, 24x24, 32x32, 48x48 sizes\n    and not in 16x16, 24x24, 32x32, 48x48, 48x48, 48x48, 48x48 sizes\n    \"\"\"\n    # Arrange\n    with Image.open(\"Tests/images/python.ico\") as im:  # 16x16, 32x32, 48x48\n        outfile = str(tmp_path / \"temp_saved_python.ico\")\n        # Act\n        im.save(outfile)\n\n    with Image.open(outfile) as im_saved:\n        # Assert\n        assert im_saved.info[\"sizes\"] == {(16, 16), (24, 24), (32, 32), (48, 48)}\n\n\ndef test_save_append_images(tmp_path):\n    # append_images should be used for scaled down versions of the image\n    im = hopper(\"RGBA\")\n    provided_im = Image.new(\"RGBA\", (32, 32), (255, 0, 0))\n    outfile = str(tmp_path / \"temp_saved_multi_icon.ico\")\n    im.save(outfile, sizes=[(32, 32), (128, 128)], append_images=[provided_im])\n\n    with Image.open(outfile) as reread:\n        assert_image_equal(reread, hopper(\"RGBA\"))\n\n        reread.size = (32, 32)\n        assert_image_equal(reread, provided_im)\n\n\ndef test_unexpected_size():\n    # This image has been manually hexedited to state that it is 16x32\n    # while the image within is still 16x16\n    def open():\n        with Image.open(\"Tests/images/hopper_unexpected.ico\") as im:\n            assert im.size == (16, 16)\n\n    pytest.warns(UserWarning, open)\n\n\ndef test_draw_reloaded(tmp_path):\n    with Image.open(TEST_ICO_FILE) as im:\n        outfile = str(tmp_path / \"temp_saved_hopper_draw.ico\")\n\n        draw = ImageDraw.Draw(im)\n        draw.line((0, 0) + im.size, \"#f00\")\n        im.save(outfile)\n\n    with Image.open(outfile) as im:\n        assert_image_equal_tofile(im, \"Tests/images/hopper_draw.ico\")\n",
            "header": {
                "file": {
                    "path": "Tests/test_file_ico.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "7b9e4e698",
                "new_commit_hash": "8060d1b76",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/Tests/test_file_ico.py"
            },
            "plus_file": {
                "path": "b/Tests/test_file_ico.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 56,
                            "length": 6
                        },
                        "new_range": {
                            "start": 56,
                            "length": 35
                        },
                        "section": "def test_save_to_bytes():"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        assert_image_equal(reloaded, hopper().resize((32, 32), Image.LANCZOS))",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "@pytest.mark.parametrize(\"mode\", (\"1\", \"L\", \"P\", \"RGB\", \"RGBA\"))",
                                "type": "added"
                            },
                            {
                                "content": "def test_save_to_bytes_bmp(mode):",
                                "type": "added"
                            },
                            {
                                "content": "    output = io.BytesIO()",
                                "type": "added"
                            },
                            {
                                "content": "    im = hopper(mode)",
                                "type": "added"
                            },
                            {
                                "content": "    im.save(output, \"ico\", bitmap_format=\"bmp\", sizes=[(32, 32), (64, 64)])",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    # The default image",
                                "type": "added"
                            },
                            {
                                "content": "    output.seek(0)",
                                "type": "added"
                            },
                            {
                                "content": "    with Image.open(output) as reloaded:",
                                "type": "added"
                            },
                            {
                                "content": "        assert reloaded.info[\"sizes\"] == {(32, 32), (64, 64)}",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        assert \"RGBA\" == reloaded.mode",
                                "type": "added"
                            },
                            {
                                "content": "        assert (64, 64) == reloaded.size",
                                "type": "added"
                            },
                            {
                                "content": "        assert reloaded.format == \"ICO\"",
                                "type": "added"
                            },
                            {
                                "content": "        im = hopper(mode).resize((64, 64), Image.LANCZOS).convert(\"RGBA\")",
                                "type": "added"
                            },
                            {
                                "content": "        assert_image_equal(reloaded, im)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    # The other one",
                                "type": "added"
                            },
                            {
                                "content": "    output.seek(0)",
                                "type": "added"
                            },
                            {
                                "content": "    with Image.open(output) as reloaded:",
                                "type": "added"
                            },
                            {
                                "content": "        reloaded.size = (32, 32)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        assert \"RGBA\" == reloaded.mode",
                                "type": "added"
                            },
                            {
                                "content": "        assert (32, 32) == reloaded.size",
                                "type": "added"
                            },
                            {
                                "content": "        assert reloaded.format == \"ICO\"",
                                "type": "added"
                            },
                            {
                                "content": "        im = hopper(mode).resize((32, 32), Image.LANCZOS).convert(\"RGBA\")",
                                "type": "added"
                            },
                            {
                                "content": "        assert_image_equal(reloaded, im)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "def test_incorrect_size():",
                                "type": "context"
                            },
                            {
                                "content": "    with Image.open(TEST_ICO_FILE) as im:",
                                "type": "context"
                            },
                            {
                                "content": "        with pytest.raises(ValueError):",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "Tests/test_file_ico.py",
                            "type": "function",
                            "name": "test_save_to_bytes_bmp",
                            "content": "def test_save_to_bytes_bmp(mode):\n    output = io.BytesIO()\n    im = hopper(mode)\n    im.save(output, \"ico\", bitmap_format=\"bmp\", sizes=[(32, 32), (64, 64)])\n\n    # The default image\n    output.seek(0)\n    with Image.open(output) as reloaded:\n        assert reloaded.info[\"sizes\"] == {(32, 32), (64, 64)}\n\n        assert \"RGBA\" == reloaded.mode\n        assert (64, 64) == reloaded.size\n        assert reloaded.format == \"ICO\"\n        im = hopper(mode).resize((64, 64), Image.LANCZOS).convert(\"RGBA\")\n        assert_image_equal(reloaded, im)\n\n    # The other one\n    output.seek(0)\n    with Image.open(output) as reloaded:\n        reloaded.size = (32, 32)\n\n        assert \"RGBA\" == reloaded.mode\n        assert (32, 32) == reloaded.size\n        assert reloaded.format == \"ICO\"\n        im = hopper(mode).resize((32, 32), Image.LANCZOS).convert(\"RGBA\")\n        assert_image_equal(reloaded, im)",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 60,
                            "end_lineno": 85,
                            "parent": null
                        }
                    ],
                    "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\nFully supported formats\n-----------------------\n\n.. contents::\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. Run-length encoding\nis not supported.\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 ``bmp_rle`` if the file is run-length encoded.\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\nIf Ghostscript is available, you can call the :py:meth:`~PIL.Image.Image.load`\nmethod with the following parameter 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\nGIF\n^^^\n\nPillow reads GIF87a and GIF89a versions of the GIF file format. The library\nwrites run-length encoded files in GIF87a by default, unless GIF89a features\nare used or GIF89a is already in use.\n\nNote that GIF files are always read as grayscale (``L``)\nor palette mode (``P``) images.\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.\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\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    If present and true, attempt to compress the palette by\n    eliminating unused colors. This is only useful if the palette can\n    be compressed to the next smaller power of 2 elements.\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. By default, 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 manipulate the\n:py:attr:`~PIL.Image.Image.size` and :py:attr:`~PIL.ImageFile.ImageFile.tile`\nattributes before loading the file::\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        tag, (x0, y0, x1, y1), offset, extra = im.tile[0]\n        im.size = (x1 - x0, y1 - y0)\n        im.tile = [(tag, (0, 0) + im.size, offset, extra)]\n\nICNS\n^^^^\n\nPillow reads and (macOS only) 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**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\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\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\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\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\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). The default is\n    75. Values above 95 should be avoided; 100 disables portions of the JPEG\n    compression algorithm, and results in large files with hardly any gain in\n    image quality.\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**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    * ``-1``: equivalent to ``keep``\n    * ``0``: equivalent to ``4:4:4``\n    * ``1``: equivalent to ``4:2:2``\n    * ``2``: equivalent to ``4: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\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`` or\n``RGBA`` data.  It can also read files containing ``YCbCr`` data, which it\nconverts on read into ``RGB`` or ``RGBA`` depending on whether or not there is\nan alpha channel.  Pillow supports JPEG 2000 raw codestreams (``.j2k`` files),\nas well as boxed JPEG 2000 files (``.j2p`` or ``.jpx`` files).  Pillow does\n*not* support files whose components have different sampling frequencies.\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\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 Irreversible Color Transformation\n    followed by DWT 9-7.  Defaults to ``False``, which means to use the\n    Reversible Color Transformation with DWT 5-3.\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**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.. 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\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\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\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.APNG_DISPOSE_OP_NONE`, default) -\n      No disposal is done on this frame before rendering the next frame.\n    * 1 (:py:data:`PIL.PngImagePlugin.APNG_DISPOSE_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.APNG_DISPOSE_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.APNG_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.APNG_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`` or\n``RGB`` data.\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\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\nWriting files in SPIDER format\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 the\n`SPIDER homepage`_ at `Wadsworth Center`_.\n\n.. _SPIDER homepage: https://spider.wadsworth.org/spider_doc/spider/docs/spider.html\n.. _Wadsworth Center: https://www.wadsworth.org/\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\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\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.num_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\nSaving Tiff Images\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**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. The specifics of Pillow's capabilities with\nthis format are currently undocumented.\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, 1-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**method**\n    Quality/speed trade-off (0=fast, 6=slower-better). Defaults to 4.\n\n**icc_profile**\n    The ICC Profile to include in the saved file. Only supported if\n    the system WebP library was built with webpmux support.\n\n**exif**\n    The exif data to include in the saved file. Only supported if\n    the system WebP library was built with webpmux support.\n\nSaving sequences\n~~~~~~~~~~~~~~~~~\n\n.. note::\n\n    Support for animated WebP files will only be enabled if the system WebP\n    library is v0.5.0 or later. You can check webp animation support at\n    runtime by calling ``features.check(\"webp_anim\")``.\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\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\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\n\nDDS\n^^^\n\nDDS is a popular container texture format used in video games and natively\nsupported by DirectX.\nCurrently, uncompressed RGB data and DXT1, DXT3, and DXT5 pixel formats are\nsupported, and only in ``RGBA`` mode.\n\n.. versionadded:: 3.4.0 DXT3\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. In the current version, only the highest\nresolution image is read from the file, and the viewing transform is not taken\ninto account.\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\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\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\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\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\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 putpalette method.\n\nWMF\n^^^\n\nPillow can identify WMF files.\n\nOn Windows, it can read WMF files. By default, it will load the image at 72\ndpi. To load it at another resolution:\n\n.. code-block:: python\n\n    from PIL import Image\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 handler.\n\n.. code-block:: python\n\n    from PIL import Image\n    from PIL import WmfImagePlugin\n\n    class WmfHandler:\n        def open(self, im):\n            ...\n        def load(self, im):\n            ...\n            return image\n        def save(self, im, fp, filename):\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\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, using either JPEG or HEX encoding depending on the image mode (and\nwhether JPEG support is available or not).\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**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\nFITS\n^^^^\n\n.. versionadded:: 1.1.5\n\nPillow provides a stub driver for FITS files.\n\nTo add read or write support to your application, use\n:py:func:`PIL.FitsStubImagePlugin.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\nFully supported formats\n-----------------------\n\n.. contents::\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. Run-length encoding\nis not supported.\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 ``bmp_rle`` if the file is run-length encoded.\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\nIf Ghostscript is available, you can call the :py:meth:`~PIL.Image.Image.load`\nmethod with the following parameter 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\nGIF\n^^^\n\nPillow reads GIF87a and GIF89a versions of the GIF file format. The library\nwrites run-length encoded files in GIF87a by default, unless GIF89a features\nare used or GIF89a is already in use.\n\nNote that GIF files are always read as grayscale (``L``)\nor palette mode (``P``) images.\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.\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\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    If present and true, attempt to compress the palette by\n    eliminating unused colors. This is only useful if the palette can\n    be compressed to the next smaller power of 2 elements.\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. By default, 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 manipulate the\n:py:attr:`~PIL.Image.Image.size` and :py:attr:`~PIL.ImageFile.ImageFile.tile`\nattributes before loading the file::\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        tag, (x0, y0, x1, y1), offset, extra = im.tile[0]\n        im.size = (x1 - x0, y1 - y0)\n        im.tile = [(tag, (0, 0) + im.size, offset, extra)]\n\nICNS\n^^^^\n\nPillow reads and (macOS only) 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**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\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\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\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\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). The default is\n    75. Values above 95 should be avoided; 100 disables portions of the JPEG\n    compression algorithm, and results in large files with hardly any gain in\n    image quality.\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**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    * ``-1``: equivalent to ``keep``\n    * ``0``: equivalent to ``4:4:4``\n    * ``1``: equivalent to ``4:2:2``\n    * ``2``: equivalent to ``4: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\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`` or\n``RGBA`` data.  It can also read files containing ``YCbCr`` data, which it\nconverts on read into ``RGB`` or ``RGBA`` depending on whether or not there is\nan alpha channel.  Pillow supports JPEG 2000 raw codestreams (``.j2k`` files),\nas well as boxed JPEG 2000 files (``.j2p`` or ``.jpx`` files).  Pillow does\n*not* support files whose components have different sampling frequencies.\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\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 Irreversible Color Transformation\n    followed by DWT 9-7.  Defaults to ``False``, which means to use the\n    Reversible Color Transformation with DWT 5-3.\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**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.. 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\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\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\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.APNG_DISPOSE_OP_NONE`, default) -\n      No disposal is done on this frame before rendering the next frame.\n    * 1 (:py:data:`PIL.PngImagePlugin.APNG_DISPOSE_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.APNG_DISPOSE_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.APNG_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.APNG_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`` or\n``RGB`` data.\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\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\nWriting files in SPIDER format\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 the\n`SPIDER homepage`_ at `Wadsworth Center`_.\n\n.. _SPIDER homepage: https://spider.wadsworth.org/spider_doc/spider/docs/spider.html\n.. _Wadsworth Center: https://www.wadsworth.org/\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\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\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.num_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\nSaving Tiff Images\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**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. The specifics of Pillow's capabilities with\nthis format are currently undocumented.\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, 1-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**method**\n    Quality/speed trade-off (0=fast, 6=slower-better). Defaults to 4.\n\n**icc_profile**\n    The ICC Profile to include in the saved file. Only supported if\n    the system WebP library was built with webpmux support.\n\n**exif**\n    The exif data to include in the saved file. Only supported if\n    the system WebP library was built with webpmux support.\n\nSaving sequences\n~~~~~~~~~~~~~~~~~\n\n.. note::\n\n    Support for animated WebP files will only be enabled if the system WebP\n    library is v0.5.0 or later. You can check webp animation support at\n    runtime by calling ``features.check(\"webp_anim\")``.\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\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\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\n\nDDS\n^^^\n\nDDS is a popular container texture format used in video games and natively\nsupported by DirectX.\nCurrently, uncompressed RGB data and DXT1, DXT3, and DXT5 pixel formats are\nsupported, and only in ``RGBA`` mode.\n\n.. versionadded:: 3.4.0 DXT3\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. In the current version, only the highest\nresolution image is read from the file, and the viewing transform is not taken\ninto account.\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\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\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\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\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\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 putpalette method.\n\nWMF\n^^^\n\nPillow can identify WMF files.\n\nOn Windows, it can read WMF files. By default, it will load the image at 72\ndpi. To load it at another resolution:\n\n.. code-block:: python\n\n    from PIL import Image\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 handler.\n\n.. code-block:: python\n\n    from PIL import Image\n    from PIL import WmfImagePlugin\n\n    class WmfHandler:\n        def open(self, im):\n            ...\n        def load(self, im):\n            ...\n            return image\n        def save(self, im, fp, filename):\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\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, using either JPEG or HEX encoding depending on the image mode (and\nwhether JPEG support is available or not).\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**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\nFITS\n^^^^\n\n.. versionadded:: 1.1.5\n\nPillow provides a stub driver for FITS files.\n\nTo add read or write support to your application, use\n:py:func:`PIL.FitsStubImagePlugin.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": "ea40ef6d7",
                "new_commit_hash": "b990e9cc0",
                "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": 247,
                            "length": 6
                        },
                        "new_range": {
                            "start": 247,
                            "length": 12
                        },
                        "section": "The :py:meth:`~PIL.Image.Image.save` method can take the following keyword argum"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    .. versionadded:: 8.1.0",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "**bitmap_format**",
                                "type": "added"
                            },
                            {
                                "content": "    By default, the image data will be saved in PNG format. With a bitmap format of",
                                "type": "added"
                            },
                            {
                                "content": "    \"bmp\", image data will be saved in BMP format instead.",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    .. versionadded:: 8.3.0",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "IM",
                                "type": "context"
                            },
                            {
                                "content": "^^",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "8.3.0\n-----\n\nDeprecations\n============\n\nTODO\n^^^^\n\nTODO\n\nAPI Changes\n===========\n\nChanged WebP default \"method\" value when saving\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nPreviously, it was 0, for the best speed. The default has now been changed to 4, to\nmatch WebP's default, for higher quality with still some speed optimisation.\n\nDefault resampling filter for special image modes\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nPillow 7.0 changed the default resampling filter to ``Image.BICUBIC``. However, as this\nis not supported yet for images with a custom number of bits, the default filter for\nthose modes has been reverted to ``Image.NEAREST``.\n\nImageMorph incorrect mode errors\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nFor ``apply()``, ``match()`` and ``get_on_pixels()``, if the image mode is not L, an\n:py:exc:`Exception` was thrown. This has now been changed to a :py:exc:`ValueError`.\n\nAPI Additions\n=============\n\nImageOps.contain\n^^^^^^^^^^^^^^^^\n\nReturns a resized version of the image, set to the maximum width and height within\n``size``, while maintaining the original aspect ratio.\n\nTo compare it to other ImageOps methods:\n\n- :py:meth:`~PIL.ImageOps.fit` expands an image until is fills ``size``, cropping the\n  parts of the image that do not fit.\n- :py:meth:`~PIL.ImageOps.pad` expands an image to fill ``size``, without cropping, but\n  instead filling the extra space with ``color``.\n- :py:meth:`~PIL.ImageOps.contain` is similar to :py:meth:`~PIL.ImageOps.pad`, but it\n  does not fill the extra space. Instead, the original aspect ratio is maintained. So\n  unlike the other two methods, it is not guaranteed to return an image of ``size``.\n\nSecurity\n========\n\nTODO\n\nOther Changes\n=============\n\nTODO\n^^^^\n\nTODO\n",
            "new_file_content": "8.3.0\n-----\n\nDeprecations\n============\n\nTODO\n^^^^\n\nTODO\n\nAPI Changes\n===========\n\nChanged WebP default \"method\" value when saving\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nPreviously, it was 0, for the best speed. The default has now been changed to 4, to\nmatch WebP's default, for higher quality with still some speed optimisation.\n\nDefault resampling filter for special image modes\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nPillow 7.0 changed the default resampling filter to ``Image.BICUBIC``. However, as this\nis not supported yet for images with a custom number of bits, the default filter for\nthose modes has been reverted to ``Image.NEAREST``.\n\nImageMorph incorrect mode errors\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nFor ``apply()``, ``match()`` and ``get_on_pixels()``, if the image mode is not L, an\n:py:exc:`Exception` was thrown. This has now been changed to a :py:exc:`ValueError`.\n\nAPI Additions\n=============\n\nImageOps.contain\n^^^^^^^^^^^^^^^^\n\nReturns a resized version of the image, set to the maximum width and height within\n``size``, while maintaining the original aspect ratio.\n\nTo compare it to other ImageOps methods:\n\n- :py:meth:`~PIL.ImageOps.fit` expands an image until is fills ``size``, cropping the\n  parts of the image that do not fit.\n- :py:meth:`~PIL.ImageOps.pad` expands an image to fill ``size``, without cropping, but\n  instead filling the extra space with ``color``.\n- :py:meth:`~PIL.ImageOps.contain` is similar to :py:meth:`~PIL.ImageOps.pad`, but it\n  does not fill the extra space. Instead, the original aspect ratio is maintained. So\n  unlike the other two methods, it is not guaranteed to return an image of ``size``.\n\nICO saving: bitmap_format argument\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nBy default, Pillow saves ICO files in the PNG format. They can now also be saved in BMP\nformat, through the new ``bitmap_format`` argument::\n\n    im.save(\"out.ico\", bitmap_format=\"bmp\")\n\nSecurity\n========\n\nTODO\n\nOther Changes\n=============\n\nTODO\n^^^^\n\nTODO\n",
            "header": {
                "file": {
                    "path": "docs/releasenotes/8.3.0.rst"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "a4b8cb88c",
                "new_commit_hash": "412f5a2e7",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/docs/releasenotes/8.3.0.rst"
            },
            "plus_file": {
                "path": "b/docs/releasenotes/8.3.0.rst"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 50,
                            "length": 6
                        },
                        "new_range": {
                            "start": 50,
                            "length": 14
                        },
                        "section": "To compare it to other ImageOps methods:"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "  does not fill the extra space. Instead, the original aspect ratio is maintained. So",
                                "type": "context"
                            },
                            {
                                "content": "  unlike the other two methods, it is not guaranteed to return an image of ``size``.",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "ICO saving: bitmap_format argument",
                                "type": "added"
                            },
                            {
                                "content": "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "By default, Pillow saves ICO files in the PNG format. They can now also be saved in BMP",
                                "type": "added"
                            },
                            {
                                "content": "format, through the new ``bitmap_format`` argument::",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    im.save(\"out.ico\", bitmap_format=\"bmp\")",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "Security",
                                "type": "context"
                            },
                            {
                                "content": "========",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "#\n# The Python Imaging Library.\n# $Id$\n#\n# Windows Icon support for PIL\n#\n# History:\n#       96-05-27 fl     Created\n#\n# Copyright (c) Secret Labs AB 1997.\n# Copyright (c) Fredrik Lundh 1996.\n#\n# See the README file for information on usage and redistribution.\n#\n\n# This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis\n# <casadebender@gmail.com>.\n# https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki\n#\n# Icon format references:\n#   * https://en.wikipedia.org/wiki/ICO_(file_format)\n#   * https://msdn.microsoft.com/en-us/library/ms997538.aspx\n\n\nimport struct\nimport warnings\nfrom io import BytesIO\nfrom math import ceil, log\n\nfrom . import BmpImagePlugin, Image, ImageFile, PngImagePlugin\nfrom ._binary import i16le as i16\nfrom ._binary import i32le as i32\n\n#\n# --------------------------------------------------------------------\n\n_MAGIC = b\"\\0\\0\\1\\0\"\n\n\ndef _save(im, fp, filename):\n    fp.write(_MAGIC)  # (2+2)\n    sizes = im.encoderinfo.get(\n        \"sizes\",\n        [(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)],\n    )\n    width, height = im.size\n    sizes = filter(\n        lambda x: False\n        if (x[0] > width or x[1] > height or x[0] > 256 or x[1] > 256)\n        else True,\n        sizes,\n    )\n    sizes = list(sizes)\n    fp.write(struct.pack(\"<H\", len(sizes)))  # idCount(2)\n    offset = fp.tell() + len(sizes) * 16\n    provided_images = {im.size: im for im in im.encoderinfo.get(\"append_images\", [])}\n    for size in sizes:\n        width, height = size\n        # 0 means 256\n        fp.write(struct.pack(\"B\", width if width < 256 else 0))  # bWidth(1)\n        fp.write(struct.pack(\"B\", height if height < 256 else 0))  # bHeight(1)\n        fp.write(b\"\\0\")  # bColorCount(1)\n        fp.write(b\"\\0\")  # bReserved(1)\n        fp.write(b\"\\0\\0\")  # wPlanes(2)\n        fp.write(struct.pack(\"<H\", 32))  # wBitCount(2)\n\n        image_io = BytesIO()\n        tmp = provided_images.get(size)\n        if not tmp:\n            # TODO: invent a more convenient method for proportional scalings\n            tmp = im.copy()\n            tmp.thumbnail(size, Image.LANCZOS, reducing_gap=None)\n        tmp.save(image_io, \"png\")\n        image_io.seek(0)\n        image_bytes = image_io.read()\n        bytes_len = len(image_bytes)\n        fp.write(struct.pack(\"<I\", bytes_len))  # dwBytesInRes(4)\n        fp.write(struct.pack(\"<I\", offset))  # dwImageOffset(4)\n        current = fp.tell()\n        fp.seek(offset)\n        fp.write(image_bytes)\n        offset = offset + bytes_len\n        fp.seek(current)\n\n\ndef _accept(prefix):\n    return prefix[:4] == _MAGIC\n\n\nclass IcoFile:\n    def __init__(self, buf):\n        \"\"\"\n        Parse image from file-like object containing ico file data\n        \"\"\"\n\n        # check magic\n        s = buf.read(6)\n        if not _accept(s):\n            raise SyntaxError(\"not an ICO file\")\n\n        self.buf = buf\n        self.entry = []\n\n        # Number of items in file\n        self.nb_items = i16(s, 4)\n\n        # Get headers for each item\n        for i in range(self.nb_items):\n            s = buf.read(16)\n\n            icon_header = {\n                \"width\": s[0],\n                \"height\": s[1],\n                \"nb_color\": s[2],  # No. of colors in image (0 if >=8bpp)\n                \"reserved\": s[3],\n                \"planes\": i16(s, 4),\n                \"bpp\": i16(s, 6),\n                \"size\": i32(s, 8),\n                \"offset\": i32(s, 12),\n            }\n\n            # See Wikipedia\n            for j in (\"width\", \"height\"):\n                if not icon_header[j]:\n                    icon_header[j] = 256\n\n            # See Wikipedia notes about color depth.\n            # We need this just to differ images with equal sizes\n            icon_header[\"color_depth\"] = (\n                icon_header[\"bpp\"]\n                or (\n                    icon_header[\"nb_color\"] != 0\n                    and ceil(log(icon_header[\"nb_color\"], 2))\n                )\n                or 256\n            )\n\n            icon_header[\"dim\"] = (icon_header[\"width\"], icon_header[\"height\"])\n            icon_header[\"square\"] = icon_header[\"width\"] * icon_header[\"height\"]\n\n            self.entry.append(icon_header)\n\n        self.entry = sorted(self.entry, key=lambda x: x[\"color_depth\"])\n        # ICO images are usually squares\n        # self.entry = sorted(self.entry, key=lambda x: x['width'])\n        self.entry = sorted(self.entry, key=lambda x: x[\"square\"])\n        self.entry.reverse()\n\n    def sizes(self):\n        \"\"\"\n        Get a list of all available icon sizes and color depths.\n        \"\"\"\n        return {(h[\"width\"], h[\"height\"]) for h in self.entry}\n\n    def getentryindex(self, size, bpp=False):\n        for (i, h) in enumerate(self.entry):\n            if size == h[\"dim\"] and (bpp is False or bpp == h[\"color_depth\"]):\n                return i\n        return 0\n\n    def getimage(self, size, bpp=False):\n        \"\"\"\n        Get an image from the icon\n        \"\"\"\n        return self.frame(self.getentryindex(size, bpp))\n\n    def frame(self, idx):\n        \"\"\"\n        Get an image from frame idx\n        \"\"\"\n\n        header = self.entry[idx]\n\n        self.buf.seek(header[\"offset\"])\n        data = self.buf.read(8)\n        self.buf.seek(header[\"offset\"])\n\n        if data[:8] == PngImagePlugin._MAGIC:\n            # png frame\n            im = PngImagePlugin.PngImageFile(self.buf)\n            Image._decompression_bomb_check(im.size)\n        else:\n            # XOR + AND mask bmp frame\n            im = BmpImagePlugin.DibImageFile(self.buf)\n            Image._decompression_bomb_check(im.size)\n\n            # change tile dimension to only encompass XOR image\n            im._size = (im.size[0], int(im.size[1] / 2))\n            d, e, o, a = im.tile[0]\n            im.tile[0] = d, (0, 0) + im.size, o, a\n\n            # figure out where AND mask image starts\n            bpp = header[\"bpp\"]\n            if 32 == bpp:\n                # 32-bit color depth icon image allows semitransparent areas\n                # PIL's DIB format ignores transparency bits, recover them.\n                # The DIB is packed in BGRX byte order where X is the alpha\n                # channel.\n\n                # Back up to start of bmp data\n                self.buf.seek(o)\n                # extract every 4th byte (eg. 3,7,11,15,...)\n                alpha_bytes = self.buf.read(im.size[0] * im.size[1] * 4)[3::4]\n\n                # convert to an 8bpp grayscale image\n                mask = Image.frombuffer(\n                    \"L\",  # 8bpp\n                    im.size,  # (w, h)\n                    alpha_bytes,  # source chars\n                    \"raw\",  # raw decoder\n                    (\"L\", 0, -1),  # 8bpp inverted, unpadded, reversed\n                )\n            else:\n                # get AND image from end of bitmap\n                w = im.size[0]\n                if (w % 32) > 0:\n                    # bitmap row data is aligned to word boundaries\n                    w += 32 - (im.size[0] % 32)\n\n                # the total mask data is\n                # padded row size * height / bits per char\n\n                and_mask_offset = o + int(im.size[0] * im.size[1] * (bpp / 8.0))\n                total_bytes = int((w * im.size[1]) / 8)\n\n                self.buf.seek(and_mask_offset)\n                mask_data = self.buf.read(total_bytes)\n\n                # convert raw data to image\n                mask = Image.frombuffer(\n                    \"1\",  # 1 bpp\n                    im.size,  # (w, h)\n                    mask_data,  # source chars\n                    \"raw\",  # raw decoder\n                    (\"1;I\", int(w / 8), -1),  # 1bpp inverted, padded, reversed\n                )\n\n                # now we have two images, im is XOR image and mask is AND image\n\n            # apply mask image as alpha channel\n            im = im.convert(\"RGBA\")\n            im.putalpha(mask)\n\n        return im\n\n\n##\n# Image plugin for Windows Icon files.\n\n\nclass IcoImageFile(ImageFile.ImageFile):\n    \"\"\"\n    PIL read-only image support for Microsoft Windows .ico files.\n\n    By default the largest resolution image in the file will be loaded. This\n    can be changed by altering the 'size' attribute before calling 'load'.\n\n    The info dictionary has a key 'sizes' that is a list of the sizes available\n    in the icon file.\n\n    Handles classic, XP and Vista icon formats.\n\n    When saving, PNG compression is used. Support for this was only added in\n    Windows Vista. If you are unable to view the icon in Windows, convert the\n    image to \"RGBA\" mode before saving.\n\n    This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis\n    <casadebender@gmail.com>.\n    https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki\n    \"\"\"\n\n    format = \"ICO\"\n    format_description = \"Windows Icon\"\n\n    def _open(self):\n        self.ico = IcoFile(self.fp)\n        self.info[\"sizes\"] = self.ico.sizes()\n        self.size = self.ico.entry[0][\"dim\"]\n        self.load()\n\n    @property\n    def size(self):\n        return self._size\n\n    @size.setter\n    def size(self, value):\n        if value not in self.info[\"sizes\"]:\n            raise ValueError(\"This is not one of the allowed sizes of this image\")\n        self._size = value\n\n    def load(self):\n        if self.im and self.im.size == self.size:\n            # Already loaded\n            return\n        im = self.ico.getimage(self.size)\n        # if tile is PNG, it won't really be loaded yet\n        im.load()\n        self.im = im.im\n        self.mode = im.mode\n        if im.size != self.size:\n            warnings.warn(\"Image was not the expected size\")\n\n            index = self.ico.getentryindex(self.size)\n            sizes = list(self.info[\"sizes\"])\n            sizes[index] = im.size\n            self.info[\"sizes\"] = set(sizes)\n\n            self.size = im.size\n\n    def load_seek(self):\n        # Flag the ImageFile.Parser so that it\n        # just does all the decode at the end.\n        pass\n\n\n#\n# --------------------------------------------------------------------\n\n\nImage.register_open(IcoImageFile.format, IcoImageFile, _accept)\nImage.register_save(IcoImageFile.format, _save)\nImage.register_extension(IcoImageFile.format, \".ico\")\n\nImage.register_mime(IcoImageFile.format, \"image/x-icon\")\n",
            "new_file_content": "#\n# The Python Imaging Library.\n# $Id$\n#\n# Windows Icon support for PIL\n#\n# History:\n#       96-05-27 fl     Created\n#\n# Copyright (c) Secret Labs AB 1997.\n# Copyright (c) Fredrik Lundh 1996.\n#\n# See the README file for information on usage and redistribution.\n#\n\n# This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis\n# <casadebender@gmail.com>.\n# https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki\n#\n# Icon format references:\n#   * https://en.wikipedia.org/wiki/ICO_(file_format)\n#   * https://msdn.microsoft.com/en-us/library/ms997538.aspx\n\n\nimport struct\nimport warnings\nfrom io import BytesIO\nfrom math import ceil, log\n\nfrom . import BmpImagePlugin, Image, ImageFile, PngImagePlugin\nfrom ._binary import i16le as i16\nfrom ._binary import i32le as i32\nfrom ._binary import o32le as o32\n\n#\n# --------------------------------------------------------------------\n\n_MAGIC = b\"\\0\\0\\1\\0\"\n\n\ndef _save(im, fp, filename):\n    fp.write(_MAGIC)  # (2+2)\n    sizes = im.encoderinfo.get(\n        \"sizes\",\n        [(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)],\n    )\n    width, height = im.size\n    sizes = filter(\n        lambda x: False\n        if (x[0] > width or x[1] > height or x[0] > 256 or x[1] > 256)\n        else True,\n        sizes,\n    )\n    sizes = list(sizes)\n    fp.write(struct.pack(\"<H\", len(sizes)))  # idCount(2)\n    offset = fp.tell() + len(sizes) * 16\n    bmp = im.encoderinfo.get(\"bitmap_format\") == \"bmp\"\n    provided_images = {im.size: im for im in im.encoderinfo.get(\"append_images\", [])}\n    for size in sizes:\n        width, height = size\n        # 0 means 256\n        fp.write(struct.pack(\"B\", width if width < 256 else 0))  # bWidth(1)\n        fp.write(struct.pack(\"B\", height if height < 256 else 0))  # bHeight(1)\n        fp.write(b\"\\0\")  # bColorCount(1)\n        fp.write(b\"\\0\")  # bReserved(1)\n        fp.write(b\"\\0\\0\")  # wPlanes(2)\n\n        tmp = provided_images.get(size)\n        if not tmp:\n            # TODO: invent a more convenient method for proportional scalings\n            tmp = im.copy()\n            tmp.thumbnail(size, Image.LANCZOS, reducing_gap=None)\n        bits = BmpImagePlugin.SAVE[tmp.mode][1] if bmp else 32\n        fp.write(struct.pack(\"<H\", bits))  # wBitCount(2)\n\n        image_io = BytesIO()\n        if bmp:\n            tmp.save(image_io, \"dib\")\n\n            if bits != 32:\n                and_mask = Image.new(\"1\", tmp.size)\n                ImageFile._save(\n                    and_mask, image_io, [(\"raw\", (0, 0) + tmp.size, 0, (\"1\", 0, -1))]\n                )\n        else:\n            tmp.save(image_io, \"png\")\n        image_io.seek(0)\n        image_bytes = image_io.read()\n        if bmp:\n            image_bytes = image_bytes[:8] + o32(height * 2) + image_bytes[12:]\n        bytes_len = len(image_bytes)\n        fp.write(struct.pack(\"<I\", bytes_len))  # dwBytesInRes(4)\n        fp.write(struct.pack(\"<I\", offset))  # dwImageOffset(4)\n        current = fp.tell()\n        fp.seek(offset)\n        fp.write(image_bytes)\n        offset = offset + bytes_len\n        fp.seek(current)\n\n\ndef _accept(prefix):\n    return prefix[:4] == _MAGIC\n\n\nclass IcoFile:\n    def __init__(self, buf):\n        \"\"\"\n        Parse image from file-like object containing ico file data\n        \"\"\"\n\n        # check magic\n        s = buf.read(6)\n        if not _accept(s):\n            raise SyntaxError(\"not an ICO file\")\n\n        self.buf = buf\n        self.entry = []\n\n        # Number of items in file\n        self.nb_items = i16(s, 4)\n\n        # Get headers for each item\n        for i in range(self.nb_items):\n            s = buf.read(16)\n\n            icon_header = {\n                \"width\": s[0],\n                \"height\": s[1],\n                \"nb_color\": s[2],  # No. of colors in image (0 if >=8bpp)\n                \"reserved\": s[3],\n                \"planes\": i16(s, 4),\n                \"bpp\": i16(s, 6),\n                \"size\": i32(s, 8),\n                \"offset\": i32(s, 12),\n            }\n\n            # See Wikipedia\n            for j in (\"width\", \"height\"):\n                if not icon_header[j]:\n                    icon_header[j] = 256\n\n            # See Wikipedia notes about color depth.\n            # We need this just to differ images with equal sizes\n            icon_header[\"color_depth\"] = (\n                icon_header[\"bpp\"]\n                or (\n                    icon_header[\"nb_color\"] != 0\n                    and ceil(log(icon_header[\"nb_color\"], 2))\n                )\n                or 256\n            )\n\n            icon_header[\"dim\"] = (icon_header[\"width\"], icon_header[\"height\"])\n            icon_header[\"square\"] = icon_header[\"width\"] * icon_header[\"height\"]\n\n            self.entry.append(icon_header)\n\n        self.entry = sorted(self.entry, key=lambda x: x[\"color_depth\"])\n        # ICO images are usually squares\n        # self.entry = sorted(self.entry, key=lambda x: x['width'])\n        self.entry = sorted(self.entry, key=lambda x: x[\"square\"])\n        self.entry.reverse()\n\n    def sizes(self):\n        \"\"\"\n        Get a list of all available icon sizes and color depths.\n        \"\"\"\n        return {(h[\"width\"], h[\"height\"]) for h in self.entry}\n\n    def getentryindex(self, size, bpp=False):\n        for (i, h) in enumerate(self.entry):\n            if size == h[\"dim\"] and (bpp is False or bpp == h[\"color_depth\"]):\n                return i\n        return 0\n\n    def getimage(self, size, bpp=False):\n        \"\"\"\n        Get an image from the icon\n        \"\"\"\n        return self.frame(self.getentryindex(size, bpp))\n\n    def frame(self, idx):\n        \"\"\"\n        Get an image from frame idx\n        \"\"\"\n\n        header = self.entry[idx]\n\n        self.buf.seek(header[\"offset\"])\n        data = self.buf.read(8)\n        self.buf.seek(header[\"offset\"])\n\n        if data[:8] == PngImagePlugin._MAGIC:\n            # png frame\n            im = PngImagePlugin.PngImageFile(self.buf)\n            Image._decompression_bomb_check(im.size)\n        else:\n            # XOR + AND mask bmp frame\n            im = BmpImagePlugin.DibImageFile(self.buf)\n            Image._decompression_bomb_check(im.size)\n\n            # change tile dimension to only encompass XOR image\n            im._size = (im.size[0], int(im.size[1] / 2))\n            d, e, o, a = im.tile[0]\n            im.tile[0] = d, (0, 0) + im.size, o, a\n\n            # figure out where AND mask image starts\n            bpp = header[\"bpp\"]\n            if 32 == bpp:\n                # 32-bit color depth icon image allows semitransparent areas\n                # PIL's DIB format ignores transparency bits, recover them.\n                # The DIB is packed in BGRX byte order where X is the alpha\n                # channel.\n\n                # Back up to start of bmp data\n                self.buf.seek(o)\n                # extract every 4th byte (eg. 3,7,11,15,...)\n                alpha_bytes = self.buf.read(im.size[0] * im.size[1] * 4)[3::4]\n\n                # convert to an 8bpp grayscale image\n                mask = Image.frombuffer(\n                    \"L\",  # 8bpp\n                    im.size,  # (w, h)\n                    alpha_bytes,  # source chars\n                    \"raw\",  # raw decoder\n                    (\"L\", 0, -1),  # 8bpp inverted, unpadded, reversed\n                )\n            else:\n                # get AND image from end of bitmap\n                w = im.size[0]\n                if (w % 32) > 0:\n                    # bitmap row data is aligned to word boundaries\n                    w += 32 - (im.size[0] % 32)\n\n                # the total mask data is\n                # padded row size * height / bits per char\n\n                and_mask_offset = o + int(im.size[0] * im.size[1] * (bpp / 8.0))\n                total_bytes = int((w * im.size[1]) / 8)\n\n                self.buf.seek(and_mask_offset)\n                mask_data = self.buf.read(total_bytes)\n\n                # convert raw data to image\n                mask = Image.frombuffer(\n                    \"1\",  # 1 bpp\n                    im.size,  # (w, h)\n                    mask_data,  # source chars\n                    \"raw\",  # raw decoder\n                    (\"1;I\", int(w / 8), -1),  # 1bpp inverted, padded, reversed\n                )\n\n                # now we have two images, im is XOR image and mask is AND image\n\n            # apply mask image as alpha channel\n            im = im.convert(\"RGBA\")\n            im.putalpha(mask)\n\n        return im\n\n\n##\n# Image plugin for Windows Icon files.\n\n\nclass IcoImageFile(ImageFile.ImageFile):\n    \"\"\"\n    PIL read-only image support for Microsoft Windows .ico files.\n\n    By default the largest resolution image in the file will be loaded. This\n    can be changed by altering the 'size' attribute before calling 'load'.\n\n    The info dictionary has a key 'sizes' that is a list of the sizes available\n    in the icon file.\n\n    Handles classic, XP and Vista icon formats.\n\n    When saving, PNG compression is used. Support for this was only added in\n    Windows Vista. If you are unable to view the icon in Windows, convert the\n    image to \"RGBA\" mode before saving.\n\n    This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis\n    <casadebender@gmail.com>.\n    https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki\n    \"\"\"\n\n    format = \"ICO\"\n    format_description = \"Windows Icon\"\n\n    def _open(self):\n        self.ico = IcoFile(self.fp)\n        self.info[\"sizes\"] = self.ico.sizes()\n        self.size = self.ico.entry[0][\"dim\"]\n        self.load()\n\n    @property\n    def size(self):\n        return self._size\n\n    @size.setter\n    def size(self, value):\n        if value not in self.info[\"sizes\"]:\n            raise ValueError(\"This is not one of the allowed sizes of this image\")\n        self._size = value\n\n    def load(self):\n        if self.im and self.im.size == self.size:\n            # Already loaded\n            return\n        im = self.ico.getimage(self.size)\n        # if tile is PNG, it won't really be loaded yet\n        im.load()\n        self.im = im.im\n        self.mode = im.mode\n        if im.size != self.size:\n            warnings.warn(\"Image was not the expected size\")\n\n            index = self.ico.getentryindex(self.size)\n            sizes = list(self.info[\"sizes\"])\n            sizes[index] = im.size\n            self.info[\"sizes\"] = set(sizes)\n\n            self.size = im.size\n\n    def load_seek(self):\n        # Flag the ImageFile.Parser so that it\n        # just does all the decode at the end.\n        pass\n\n\n#\n# --------------------------------------------------------------------\n\n\nImage.register_open(IcoImageFile.format, IcoImageFile, _accept)\nImage.register_save(IcoImageFile.format, _save)\nImage.register_extension(IcoImageFile.format, \".ico\")\n\nImage.register_mime(IcoImageFile.format, \"image/x-icon\")\n",
            "header": {
                "file": {
                    "path": "src/PIL/IcoImagePlugin.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "dbc108d7b",
                "new_commit_hash": "ffb1e873d",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/src/PIL/IcoImagePlugin.py"
            },
            "plus_file": {
                "path": "b/src/PIL/IcoImagePlugin.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 30,
                            "length": 6
                        },
                        "new_range": {
                            "start": 30,
                            "length": 7
                        },
                        "section": "from math import ceil, log"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "from . import BmpImagePlugin, Image, ImageFile, PngImagePlugin",
                                "type": "context"
                            },
                            {
                                "content": "from ._binary import i16le as i16",
                                "type": "context"
                            },
                            {
                                "content": "from ._binary import i32le as i32",
                                "type": "context"
                            },
                            {
                                "content": "from ._binary import o32le as o32",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "#",
                                "type": "context"
                            },
                            {
                                "content": "# --------------------------------------------------------------------",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "src/PIL/IcoImagePlugin.py",
                            "type": "statement",
                            "name": "",
                            "content": "from ._binary import o32le as o32",
                            "ast_type_str": "ImportFrom",
                            "start_lineno": 33,
                            "end_lineno": 33,
                            "parent": null
                        }
                    ],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 53,
                            "length": 6
                        },
                        "new_range": {
                            "start": 54,
                            "length": 7
                        },
                        "section": "def _save(im, fp, filename):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "    sizes = list(sizes)",
                                "type": "context"
                            },
                            {
                                "content": "    fp.write(struct.pack(\"<H\", len(sizes)))  # idCount(2)",
                                "type": "context"
                            },
                            {
                                "content": "    offset = fp.tell() + len(sizes) * 16",
                                "type": "context"
                            },
                            {
                                "content": "    bmp = im.encoderinfo.get(\"bitmap_format\") == \"bmp\"",
                                "type": "added"
                            },
                            {
                                "content": "    provided_images = {im.size: im for im in im.encoderinfo.get(\"append_images\", [])}",
                                "type": "context"
                            },
                            {
                                "content": "    for size in sizes:",
                                "type": "context"
                            },
                            {
                                "content": "        width, height = size",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "src/PIL/IcoImagePlugin.py",
                            "type": "function",
                            "name": "_save",
                            "content": "def _save(im, fp, filename):\n    fp.write(_MAGIC)  # (2+2)\n    sizes = im.encoderinfo.get(\n        \"sizes\",\n        [(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)],\n    )\n    width, height = im.size\n    sizes = filter(\n        lambda x: False\n        if (x[0] > width or x[1] > height or x[0] > 256 or x[1] > 256)\n        else True,\n        sizes,\n    )\n    sizes = list(sizes)\n    fp.write(struct.pack(\"<H\", len(sizes)))  # idCount(2)\n    offset = fp.tell() + len(sizes) * 16\n    bmp = im.encoderinfo.get(\"bitmap_format\") == \"bmp\"\n    provided_images = {im.size: im for im in im.encoderinfo.get(\"append_images\", [])}\n    for size in sizes:\n        width, height = size\n        # 0 means 256\n        fp.write(struct.pack(\"B\", width if width < 256 else 0))  # bWidth(1)\n        fp.write(struct.pack(\"B\", height if height < 256 else 0))  # bHeight(1)\n        fp.write(b\"\\0\")  # bColorCount(1)\n        fp.write(b\"\\0\")  # bReserved(1)\n        fp.write(b\"\\0\\0\")  # wPlanes(2)\n\n        tmp = provided_images.get(size)\n        if not tmp:\n            # TODO: invent a more convenient method for proportional scalings\n            tmp = im.copy()\n            tmp.thumbnail(size, Image.LANCZOS, reducing_gap=None)\n        bits = BmpImagePlugin.SAVE[tmp.mode][1] if bmp else 32\n        fp.write(struct.pack(\"<H\", bits))  # wBitCount(2)\n\n        image_io = BytesIO()\n        if bmp:\n            tmp.save(image_io, \"dib\")\n\n            if bits != 32:\n                and_mask = Image.new(\"1\", tmp.size)\n                ImageFile._save(\n                    and_mask, image_io, [(\"raw\", (0, 0) + tmp.size, 0, (\"1\", 0, -1))]\n                )\n        else:\n            tmp.save(image_io, \"png\")\n        image_io.seek(0)\n        image_bytes = image_io.read()\n        if bmp:\n            image_bytes = image_bytes[:8] + o32(height * 2) + image_bytes[12:]\n        bytes_len = len(image_bytes)\n        fp.write(struct.pack(\"<I\", bytes_len))  # dwBytesInRes(4)\n        fp.write(struct.pack(\"<I\", offset))  # dwImageOffset(4)\n        current = fp.tell()\n        fp.seek(offset)\n        fp.write(image_bytes)\n        offset = offset + bytes_len\n        fp.seek(current)",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 41,
                            "end_lineno": 98,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 62,
                            "length": 17
                        },
                        "new_range": {
                            "start": 64,
                            "length": 30
                        },
                        "section": "def _save(im, fp, filename):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        fp.write(b\"\\0\")  # bColorCount(1)",
                                "type": "context"
                            },
                            {
                                "content": "        fp.write(b\"\\0\")  # bReserved(1)",
                                "type": "context"
                            },
                            {
                                "content": "        fp.write(b\"\\0\\0\")  # wPlanes(2)",
                                "type": "context"
                            },
                            {
                                "content": "        fp.write(struct.pack(\"<H\", 32))  # wBitCount(2)",
                                "type": "deleted"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        image_io = BytesIO()",
                                "type": "deleted"
                            },
                            {
                                "content": "        tmp = provided_images.get(size)",
                                "type": "context"
                            },
                            {
                                "content": "        if not tmp:",
                                "type": "context"
                            },
                            {
                                "content": "            # TODO: invent a more convenient method for proportional scalings",
                                "type": "context"
                            },
                            {
                                "content": "            tmp = im.copy()",
                                "type": "context"
                            },
                            {
                                "content": "            tmp.thumbnail(size, Image.LANCZOS, reducing_gap=None)",
                                "type": "context"
                            },
                            {
                                "content": "        tmp.save(image_io, \"png\")",
                                "type": "deleted"
                            },
                            {
                                "content": "        bits = BmpImagePlugin.SAVE[tmp.mode][1] if bmp else 32",
                                "type": "added"
                            },
                            {
                                "content": "        fp.write(struct.pack(\"<H\", bits))  # wBitCount(2)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        image_io = BytesIO()",
                                "type": "added"
                            },
                            {
                                "content": "        if bmp:",
                                "type": "added"
                            },
                            {
                                "content": "            tmp.save(image_io, \"dib\")",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "            if bits != 32:",
                                "type": "added"
                            },
                            {
                                "content": "                and_mask = Image.new(\"1\", tmp.size)",
                                "type": "added"
                            },
                            {
                                "content": "                ImageFile._save(",
                                "type": "added"
                            },
                            {
                                "content": "                    and_mask, image_io, [(\"raw\", (0, 0) + tmp.size, 0, (\"1\", 0, -1))]",
                                "type": "added"
                            },
                            {
                                "content": "                )",
                                "type": "added"
                            },
                            {
                                "content": "        else:",
                                "type": "added"
                            },
                            {
                                "content": "            tmp.save(image_io, \"png\")",
                                "type": "added"
                            },
                            {
                                "content": "        image_io.seek(0)",
                                "type": "context"
                            },
                            {
                                "content": "        image_bytes = image_io.read()",
                                "type": "context"
                            },
                            {
                                "content": "        if bmp:",
                                "type": "added"
                            },
                            {
                                "content": "            image_bytes = image_bytes[:8] + o32(height * 2) + image_bytes[12:]",
                                "type": "added"
                            },
                            {
                                "content": "        bytes_len = len(image_bytes)",
                                "type": "context"
                            },
                            {
                                "content": "        fp.write(struct.pack(\"<I\", bytes_len))  # dwBytesInRes(4)",
                                "type": "context"
                            },
                            {
                                "content": "        fp.write(struct.pack(\"<I\", offset))  # dwImageOffset(4)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "src/PIL/IcoImagePlugin.py",
                            "type": "function",
                            "name": "_save",
                            "content": "def _save(im, fp, filename):\n    fp.write(_MAGIC)  # (2+2)\n    sizes = im.encoderinfo.get(\n        \"sizes\",\n        [(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)],\n    )\n    width, height = im.size\n    sizes = filter(\n        lambda x: False\n        if (x[0] > width or x[1] > height or x[0] > 256 or x[1] > 256)\n        else True,\n        sizes,\n    )\n    sizes = list(sizes)\n    fp.write(struct.pack(\"<H\", len(sizes)))  # idCount(2)\n    offset = fp.tell() + len(sizes) * 16\n    provided_images = {im.size: im for im in im.encoderinfo.get(\"append_images\", [])}\n    for size in sizes:\n        width, height = size\n        # 0 means 256\n        fp.write(struct.pack(\"B\", width if width < 256 else 0))  # bWidth(1)\n        fp.write(struct.pack(\"B\", height if height < 256 else 0))  # bHeight(1)\n        fp.write(b\"\\0\")  # bColorCount(1)\n        fp.write(b\"\\0\")  # bReserved(1)\n        fp.write(b\"\\0\\0\")  # wPlanes(2)\n        fp.write(struct.pack(\"<H\", 32))  # wBitCount(2)\n\n        image_io = BytesIO()\n        tmp = provided_images.get(size)\n        if not tmp:\n            # TODO: invent a more convenient method for proportional scalings\n            tmp = im.copy()\n            tmp.thumbnail(size, Image.LANCZOS, reducing_gap=None)\n        tmp.save(image_io, \"png\")\n        image_io.seek(0)\n        image_bytes = image_io.read()\n        bytes_len = len(image_bytes)\n        fp.write(struct.pack(\"<I\", bytes_len))  # dwBytesInRes(4)\n        fp.write(struct.pack(\"<I\", offset))  # dwImageOffset(4)\n        current = fp.tell()\n        fp.seek(offset)\n        fp.write(image_bytes)\n        offset = offset + bytes_len\n        fp.seek(current)",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 40,
                            "end_lineno": 83,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "2a7eb5415ef20be08d60057623bde858310707fe^",
    "new_commit_hash": "2a7eb5415ef20be08d60057623bde858310707fe",
    "commit_message": "Merge pull request #5513 from radarhere/ico_bmp\n\nAdded ICO saving in BMP format",
    "commit_date": "2021-06-06T18:12:33+03:00",
    "metadata": {}
}
{
    "repo_name": "pillow",
    "new_commit_hash": "2a7eb5415ef20be08d60057623bde858310707fe",
    "test_file_codes": [
        "import io\n\nimport pytest\n\nfrom PIL import IcoImagePlugin, Image, ImageDraw\n\nfrom .helper import assert_image_equal, assert_image_equal_tofile, hopper\n\nTEST_ICO_FILE = \"Tests/images/hopper.ico\"\n\n\ndef test_sanity():\n    with Image.open(TEST_ICO_FILE) as im:\n        im.load()\n    assert im.mode == \"RGBA\"\n    assert im.size == (16, 16)\n    assert im.format == \"ICO\"\n    assert im.get_format_mimetype() == \"image/x-icon\"\n\n\ndef test_black_and_white():\n    with Image.open(\"Tests/images/black_and_white.ico\") as im:\n        assert im.mode == \"RGBA\"\n        assert im.size == (16, 16)\n\n\ndef test_invalid_file():\n    with open(\"Tests/images/flower.jpg\", \"rb\") as fp:\n        with pytest.raises(SyntaxError):\n            IcoImagePlugin.IcoImageFile(fp)\n\n\ndef test_save_to_bytes():\n    output = io.BytesIO()\n    im = hopper()\n    im.save(output, \"ico\", sizes=[(32, 32), (64, 64)])\n\n    # The default image\n    output.seek(0)\n    with Image.open(output) as reloaded:\n        assert reloaded.info[\"sizes\"] == {(32, 32), (64, 64)}\n\n        assert im.mode == reloaded.mode\n        assert (64, 64) == reloaded.size\n        assert reloaded.format == \"ICO\"\n        assert_image_equal(reloaded, hopper().resize((64, 64), Image.LANCZOS))\n\n    # The other one\n    output.seek(0)\n    with Image.open(output) as reloaded:\n        reloaded.size = (32, 32)\n\n        assert im.mode == reloaded.mode\n        assert (32, 32) == reloaded.size\n        assert reloaded.format == \"ICO\"\n        assert_image_equal(reloaded, hopper().resize((32, 32), Image.LANCZOS))\n\n\n@pytest.mark.parametrize(\"mode\", (\"1\", \"L\", \"P\", \"RGB\", \"RGBA\"))\ndef test_save_to_bytes_bmp(mode):\n    output = io.BytesIO()\n    im = hopper(mode)\n    im.save(output, \"ico\", bitmap_format=\"bmp\", sizes=[(32, 32), (64, 64)])\n\n    # The default image\n    output.seek(0)\n    with Image.open(output) as reloaded:\n        assert reloaded.info[\"sizes\"] == {(32, 32), (64, 64)}\n\n        assert \"RGBA\" == reloaded.mode\n        assert (64, 64) == reloaded.size\n        assert reloaded.format == \"ICO\"\n        im = hopper(mode).resize((64, 64), Image.LANCZOS).convert(\"RGBA\")\n        assert_image_equal(reloaded, im)\n\n    # The other one\n    output.seek(0)\n    with Image.open(output) as reloaded:\n        reloaded.size = (32, 32)\n\n        assert \"RGBA\" == reloaded.mode\n        assert (32, 32) == reloaded.size\n        assert reloaded.format == \"ICO\"\n        im = hopper(mode).resize((32, 32), Image.LANCZOS).convert(\"RGBA\")\n        assert_image_equal(reloaded, im)\n\n\ndef test_incorrect_size():\n    with Image.open(TEST_ICO_FILE) as im:\n        with pytest.raises(ValueError):\n            im.size = (1, 1)\n\n\ndef test_save_256x256(tmp_path):\n    \"\"\"Issue #2264 https://github.com/python-pillow/Pillow/issues/2264\"\"\"\n    # Arrange\n    with Image.open(\"Tests/images/hopper_256x256.ico\") as im:\n        outfile = str(tmp_path / \"temp_saved_hopper_256x256.ico\")\n\n        # Act\n        im.save(outfile)\n    with Image.open(outfile) as im_saved:\n\n        # Assert\n        assert im_saved.size == (256, 256)\n\n\ndef test_only_save_relevant_sizes(tmp_path):\n    \"\"\"Issue #2266 https://github.com/python-pillow/Pillow/issues/2266\n    Should save in 16x16, 24x24, 32x32, 48x48 sizes\n    and not in 16x16, 24x24, 32x32, 48x48, 48x48, 48x48, 48x48 sizes\n    \"\"\"\n    # Arrange\n    with Image.open(\"Tests/images/python.ico\") as im:  # 16x16, 32x32, 48x48\n        outfile = str(tmp_path / \"temp_saved_python.ico\")\n        # Act\n        im.save(outfile)\n\n    with Image.open(outfile) as im_saved:\n        # Assert\n        assert im_saved.info[\"sizes\"] == {(16, 16), (24, 24), (32, 32), (48, 48)}\n\n\ndef test_save_append_images(tmp_path):\n    # append_images should be used for scaled down versions of the image\n    im = hopper(\"RGBA\")\n    provided_im = Image.new(\"RGBA\", (32, 32), (255, 0, 0))\n    outfile = str(tmp_path / \"temp_saved_multi_icon.ico\")\n    im.save(outfile, sizes=[(32, 32), (128, 128)], append_images=[provided_im])\n\n    with Image.open(outfile) as reread:\n        assert_image_equal(reread, hopper(\"RGBA\"))\n\n        reread.size = (32, 32)\n        assert_image_equal(reread, provided_im)\n\n\ndef test_unexpected_size():\n    # This image has been manually hexedited to state that it is 16x32\n    # while the image within is still 16x16\n    def open():\n        with Image.open(\"Tests/images/hopper_unexpected.ico\") as im:\n            assert im.size == (16, 16)\n\n    pytest.warns(UserWarning, open)\n\n\ndef test_draw_reloaded(tmp_path):\n    with Image.open(TEST_ICO_FILE) as im:\n        outfile = str(tmp_path / \"temp_saved_hopper_draw.ico\")\n\n        draw = ImageDraw.Draw(im)\n        draw.line((0, 0) + im.size, \"#f00\")\n        im.save(outfile)\n\n    with Image.open(outfile) as im:\n        assert_image_equal_tofile(im, \"Tests/images/hopper_draw.ico\")\n"
    ],
    "test_file_names": [
        "test_1.py"
    ],
    "setup_res_code": 0,
    "setup_res_stdout": "Starting Pillow installation attempts...\nVerifying Pillow installation...\n✅ Pillow installation successful!\nSuccessfully installed Pillow\n",
    "setup_res_stderr": "Using CPython 3.9.21\nCreating virtual environment at: .venv\nActivate with: source .venv/bin/activate\nResolved 12 packages in 19ms\nInstalled 12 packages in 88ms\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 702ms\nPrepared 1 package in 32.28s\nInstalled 1 package in 1ms\n + pillow==8.3.0.dev0 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/pillow_2a7eb5415ef20be08d60057623bde858310707fe)\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_2a7eb5415ef20be08d60057623bde858310707fe\nconfigfile: setup.cfg\nplugins: cov-6.0.0\ncollected 15 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[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[32m.\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_black_and_white\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_invalid_file\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_save_to_bytes\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_save_to_bytes_bmp[1]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_save_to_bytes_bmp[L]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_save_to_bytes_bmp[P]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_save_to_bytes_bmp[RGB]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_save_to_bytes_bmp[RGBA]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_incorrect_size\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_save_256x256\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_only_save_relevant_sizes\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_unexpected_size\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_draw_reloaded\u001b[0m\n\u001b[32m============================== \u001b[32m\u001b[1m15 passed\u001b[0m\u001b[32m in 0.20s\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_2a7eb5415ef20be08d60057623bde858310707fe\nconfigfile: setup.cfg\nplugins: cov-6.0.0\ncollected 15 items\n\nr2e_tests/test_1.py \u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[31mF\u001b[0m\u001b[31mF\u001b[0m\u001b[31mF\u001b[0m\u001b[31mF\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[32m.\u001b[0m\u001b[31m                                      [100%]\u001b[0m\n\n=================================== FAILURES ===================================\n\u001b[31m\u001b[1m__________________________ test_save_to_bytes_bmp[1] ___________________________\u001b[0m\n\nmode = '1'\n\n    @pytest.mark.parametrize(\"mode\", (\"1\", \"L\", \"P\", \"RGB\", \"RGBA\"))\n    def test_save_to_bytes_bmp(mode):\n        output = io.BytesIO()\n        im = hopper(mode)\n        im.save(output, \"ico\", bitmap_format=\"bmp\", sizes=[(32, 32), (64, 64)])\n    \n        # The default image\n        output.seek(0)\n        with Image.open(output) as reloaded:\n            assert reloaded.info[\"sizes\"] == {(32, 32), (64, 64)}\n    \n>           assert \"RGBA\" == reloaded.mode\n\u001b[1m\u001b[31mE           AssertionError: assert 'RGBA' == '1'\u001b[0m\n\u001b[1m\u001b[31mE             \u001b[0m\n\u001b[1m\u001b[31mE             - 1\u001b[0m\n\u001b[1m\u001b[31mE             + RGBA\u001b[0m\n\n\u001b[1m\u001b[31mr2e_tests/test_1.py\u001b[0m:70: AssertionError\n\u001b[31m\u001b[1m__________________________ test_save_to_bytes_bmp[L] ___________________________\u001b[0m\n\nmode = 'L'\n\n    @pytest.mark.parametrize(\"mode\", (\"1\", \"L\", \"P\", \"RGB\", \"RGBA\"))\n    def test_save_to_bytes_bmp(mode):\n        output = io.BytesIO()\n        im = hopper(mode)\n        im.save(output, \"ico\", bitmap_format=\"bmp\", sizes=[(32, 32), (64, 64)])\n    \n        # The default image\n        output.seek(0)\n        with Image.open(output) as reloaded:\n            assert reloaded.info[\"sizes\"] == {(32, 32), (64, 64)}\n    \n>           assert \"RGBA\" == reloaded.mode\n\u001b[1m\u001b[31mE           AssertionError: assert 'RGBA' == 'L'\u001b[0m\n\u001b[1m\u001b[31mE             \u001b[0m\n\u001b[1m\u001b[31mE             - L\u001b[0m\n\u001b[1m\u001b[31mE             + RGBA\u001b[0m\n\n\u001b[1m\u001b[31mr2e_tests/test_1.py\u001b[0m:70: AssertionError\n\u001b[31m\u001b[1m__________________________ test_save_to_bytes_bmp[P] ___________________________\u001b[0m\n\nmode = 'P'\n\n    @pytest.mark.parametrize(\"mode\", (\"1\", \"L\", \"P\", \"RGB\", \"RGBA\"))\n    def test_save_to_bytes_bmp(mode):\n        output = io.BytesIO()\n        im = hopper(mode)\n        im.save(output, \"ico\", bitmap_format=\"bmp\", sizes=[(32, 32), (64, 64)])\n    \n        # The default image\n        output.seek(0)\n        with Image.open(output) as reloaded:\n            assert reloaded.info[\"sizes\"] == {(32, 32), (64, 64)}\n    \n>           assert \"RGBA\" == reloaded.mode\n\u001b[1m\u001b[31mE           AssertionError: assert 'RGBA' == 'P'\u001b[0m\n\u001b[1m\u001b[31mE             \u001b[0m\n\u001b[1m\u001b[31mE             - P\u001b[0m\n\u001b[1m\u001b[31mE             + RGBA\u001b[0m\n\n\u001b[1m\u001b[31mr2e_tests/test_1.py\u001b[0m:70: AssertionError\n\u001b[31m\u001b[1m_________________________ test_save_to_bytes_bmp[RGB] __________________________\u001b[0m\n\nmode = 'RGB'\n\n    @pytest.mark.parametrize(\"mode\", (\"1\", \"L\", \"P\", \"RGB\", \"RGBA\"))\n    def test_save_to_bytes_bmp(mode):\n        output = io.BytesIO()\n        im = hopper(mode)\n        im.save(output, \"ico\", bitmap_format=\"bmp\", sizes=[(32, 32), (64, 64)])\n    \n        # The default image\n        output.seek(0)\n        with Image.open(output) as reloaded:\n            assert reloaded.info[\"sizes\"] == {(32, 32), (64, 64)}\n    \n>           assert \"RGBA\" == reloaded.mode\n\u001b[1m\u001b[31mE           AssertionError: assert 'RGBA' == 'RGB'\u001b[0m\n\u001b[1m\u001b[31mE             \u001b[0m\n\u001b[1m\u001b[31mE             - RGB\u001b[0m\n\u001b[1m\u001b[31mE             + RGBA\u001b[0m\n\u001b[1m\u001b[31mE             ?    +\u001b[0m\n\n\u001b[1m\u001b[31mr2e_tests/test_1.py\u001b[0m:70: AssertionError\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_black_and_white\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_invalid_file\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_save_to_bytes\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_save_to_bytes_bmp[RGBA]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_incorrect_size\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_save_256x256\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_only_save_relevant_sizes\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_unexpected_size\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_draw_reloaded\u001b[0m\n\u001b[31mFAILED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_save_to_bytes_bmp[1]\u001b[0m - AssertionError: assert 'RGBA' == '1'\n\u001b[31mFAILED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_save_to_bytes_bmp[L]\u001b[0m - AssertionError: assert 'RGBA' == 'L'\n\u001b[31mFAILED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_save_to_bytes_bmp[P]\u001b[0m - AssertionError: assert 'RGBA' == 'P'\n\u001b[31mFAILED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_save_to_bytes_bmp[RGB]\u001b[0m - AssertionError: assert 'RGBA' == 'RGB'\n\u001b[31m========================= \u001b[31m\u001b[1m4 failed\u001b[0m, \u001b[32m11 passed\u001b[0m\u001b[31m in 0.17s\u001b[0m\u001b[31m =========================\u001b[0m\n",
    "old_commit_res_stderr": ""
}
Tests/test_file_ico.py docs/handbook/image-file-formats.rst docs/releasenotes/8.3.0.rst src/PIL/IcoImagePlugin.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]

**Title:** Incorrect Image Mode When Saving ICO Files in BMP Format

**Description:**
When attempting to save ICO images in BMP format, images with modes `'1'`, `'L'`, `'P'`, and `'RGB'` are incorrectly saved with the `'RGBA'` mode. This results in a mismatch between the original image mode and the saved file, leading to unexpected behavior when the ICO file is used.

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

output = io.BytesIO()
im = Image.new('L', (32, 32))  # Creating a grayscale image
im.save(output, "ico", bitmap_format="bmp", sizes=[(32, 32)])
output.seek(0)
with Image.open(output) as reloaded:
    print(reloaded.mode)  # Outputs: 'RGBA' instead of 'L'
```

**Expected Behavior:**
The saved ICO image should retain the original image mode. For instance, a grayscale (`'L'`) image should remain in `'L'` mode after being saved in BMP format within an ICO file.

**Actual Behavior:**
The saved ICO image is incorrectly set to `'RGBA'` mode regardless of the original image mode, causing inconsistencies and potential issues in image rendering.

[/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/IcoImagePlugin.py
#
# The Python Imaging Library.
# $Id$
#
# Windows Icon support for PIL
#
# History:
#       96-05-27 fl     Created
#
# Copyright (c) Secret Labs AB 1997.
# Copyright (c) Fredrik Lundh 1996.
#
# See the README file for information on usage and redistribution.
#

# This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis
# <casadebender@gmail.com>.
# https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki
#
# Icon format references:
#   * https://en.wikipedia.org/wiki/ICO_(file_format)
#   * https://msdn.microsoft.com/en-us/library/ms997538.aspx


import struct
import warnings
from io import BytesIO
from math import ceil, log

from . import BmpImagePlugin, Image, ImageFile, PngImagePlugin
from ._binary import i16le as i16
from ._binary import i32le as i32

#
# --------------------------------------------------------------------

_MAGIC = b"\0\0\1\0"


def _save(im, fp, filename):
    fp.write(_MAGIC)  # (2+2)
    sizes = im.encoderinfo.get(
        "sizes",
        [(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)],
    )
    width, height = im.size
    sizes = filter(
        lambda x: False
        if (x[0] > width or x[1] > height or x[0] > 256 or x[1] > 256)
        else True,
        sizes,
    )
    sizes = list(sizes)
    fp.write(struct.pack("<H", len(sizes)))  # idCount(2)
    offset = fp.tell() + len(sizes) * 16
    provided_images = {im.size: im for im in im.encoderinfo.get("append_images", [])}
    for size in sizes:
        width, height = size
        # 0 means 256
        fp.write(struct.pack("B", width if width < 256 else 0))  # bWidth(1)
        fp.write(struct.pack("B", height if height < 256 else 0))  # bHeight(1)
        fp.write(b"\0")  # bColorCount(1)
        fp.write(b"\0")  # bReserved(1)
        fp.write(b"\0\0")  # wPlanes(2)
        fp.write(struct.pack("<H", 32))  # wBitCount(2)

        image_io = BytesIO()
        tmp = provided_images.get(size)
        if not tmp:
            # TODO: invent a more convenient method for proportional scalings
            tmp = im.copy()
            tmp.thumbnail(size, Image.LANCZOS, reducing_gap=None)
        tmp.save(image_io, "png")
        image_io.seek(0)
        image_bytes = image_io.read()
        bytes_len = len(image_bytes)
        fp.write(struct.pack("<I", bytes_len))  # dwBytesInRes(4)
        fp.write(struct.pack("<I", offset))  # dwImageOffset(4)
        current = fp.tell()
        fp.seek(offset)
        fp.write(image_bytes)
        offset = offset + bytes_len
        fp.seek(current)


def _accept(prefix):
    return prefix[:4] == _MAGIC


class IcoFile:
    def __init__(self, buf):
        """
        Parse image from file-like object containing ico file data
        """

        # check magic
        s = buf.read(6)
        if not _accept(s):
            raise SyntaxError("not an ICO file")

        self.buf = buf
        self.entry = []

        # Number of items in file
        self.nb_items = i16(s, 4)

        # Get headers for each item
        for i in range(self.nb_items):
            s = buf.read(16)

            icon_header = {
                "width": s[0],
                "height": s[1],
                "nb_color": s[2],  # No. of colors in image (0 if >=8bpp)
                "reserved": s[3],
                "planes": i16(s, 4),
                "bpp": i16(s, 6),
                "size": i32(s, 8),
                "offset": i32(s, 12),
            }

            # See Wikipedia
            for j in ("width", "height"):
                if not icon_header[j]:
                    icon_header[j] = 256

            # See Wikipedia notes about color depth.
            # We need this just to differ images with equal sizes
            icon_header["color_depth"] = (
                icon_header["bpp"]
                or (
                    icon_header["nb_color"] != 0
                    and ceil(log(icon_header["nb_color"], 2))
                )
                or 256
            )

            icon_header["dim"] = (icon_header["width"], icon_header["height"])
            icon_header["square"] = icon_header["width"] * icon_header["height"]

            self.entry.append(icon_header)

        self.entry = sorted(self.entry, key=lambda x: x["color_depth"])
        # ICO images are usually squares
        # self.entry = sorted(self.entry, key=lambda x: x['width'])
        self.entry = sorted(self.entry, key=lambda x: x["square"])
        self.entry.reverse()

    def sizes(self):
        """
        Get a list of all available icon sizes and color depths.
        """
        return {(h["width"], h["height"]) for h in self.entry}

    def getentryindex(self, size, bpp=False):
        for (i, h) in enumerate(self.entry):
            if size == h["dim"] and (bpp is False or bpp == h["color_depth"]):
                return i
        return 0

    def getimage(self, size, bpp=False):
        """
        Get an image from the icon
        """
        return self.frame(self.getentryindex(size, bpp))

    def frame(self, idx):
        """
        Get an image from frame idx
        """

        header = self.entry[idx]

        self.buf.seek(header["offset"])
        data = self.buf.read(8)
        self.buf.seek(header["offset"])

        if data[:8] == PngImagePlugin._MAGIC:
            # png frame
            im = PngImagePlugin.PngImageFile(self.buf)
            Image._decompression_bomb_check(im.size)
        else:
            # XOR + AND mask bmp frame
            im = BmpImagePlugin.DibImageFile(self.buf)
            Image._decompression_bomb_check(im.size)

            # change tile dimension to only encompass XOR image
            im._size = (im.size[0], int(im.size[1] / 2))
            d, e, o, a = im.tile[0]
            im.tile[0] = d, (0, 0) + im.size, o, a

            # figure out where AND mask image starts
            bpp = header["bpp"]
            if 32 == bpp:
                # 32-bit color depth icon image allows semitransparent areas
                # PIL's DIB format ignores transparency bits, recover them.
                # The DIB is packed in BGRX byte order where X is the alpha
                # channel.

                # Back up to start of bmp data
                self.buf.seek(o)
                # extract every 4th byte (eg. 3,7,11,15,...)
                alpha_bytes = self.buf.read(im.size[0] * im.size[1] * 4)[3::4]

                # convert to an 8bpp grayscale image
                mask = Image.frombuffer(
                    "L",  # 8bpp
                    im.size,  # (w, h)
                    alpha_bytes,  # source chars
                    "raw",  # raw decoder
                    ("L", 0, -1),  # 8bpp inverted, unpadded, reversed
                )
            else:
                # get AND image from end of bitmap
                w = im.size[0]
                if (w % 32) > 0:
                    # bitmap row data is aligned to word boundaries
                    w += 32 - (im.size[0] % 32)

                # the total mask data is
                # padded row size * height / bits per char

                and_mask_offset = o + int(im.size[0] * im.size[1] * (bpp / 8.0))
                total_bytes = int((w * im.size[1]) / 8)

                self.buf.seek(and_mask_offset)
                mask_data = self.buf.read(total_bytes)

                # convert raw data to image
                mask = Image.frombuffer(
                    "1",  # 1 bpp
                    im.size,  # (w, h)
                    mask_data,  # source chars
                    "raw",  # raw decoder
                    ("1;I", int(w / 8), -1),  # 1bpp inverted, padded, reversed
                )

                # now we have two images, im is XOR image and mask is AND image

            # apply mask image as alpha channel
            im = im.convert("RGBA")
            im.putalpha(mask)

        return im


##
# Image plugin for Windows Icon files.


class IcoImageFile(ImageFile.ImageFile):
    """
    PIL read-only image support for Microsoft Windows .ico files.

    By default the largest resolution image in the file will be loaded. This
    can be changed by altering the 'size' attribute before calling 'load'.

    The info dictionary has a key 'sizes' that is a list of the sizes available
    in the icon file.

    Handles classic, XP and Vista icon formats.

    When saving, PNG compression is used. Support for this was only added in
    Windows Vista. If you are unable to view the icon in Windows, convert the
    image to "RGBA" mode before saving.

    This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis
    <casadebender@gmail.com>.
    https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki
    """

    format = "ICO"
    format_description = "Windows Icon"

    def _open(self):
        self.ico = IcoFile(self.fp)
        self.info["sizes"] = self.ico.sizes()
        self.size = self.ico.entry[0]["dim"]
        self.load()

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

    @size.setter
    def size(self, value):
        if value not in self.info["sizes"]:
            raise ValueError("This is not one of the allowed sizes of this image")
        self._size = value

    def load(self):
        if self.im and self.im.size == self.size:
            # Already loaded
            return
        im = self.ico.getimage(self.size)
        # if tile is PNG, it won't really be loaded yet
        im.load()
        self.im = im.im
        self.mode = im.mode
        if im.size != self.size:
            warnings.warn("Image was not the expected size")

            index = self.ico.getentryindex(self.size)
            sizes = list(self.info["sizes"])
            sizes[index] = im.size
            self.info["sizes"] = set(sizes)

            self.size = im.size

    def load_seek(self):
        # Flag the ImageFile.Parser so that it
        # just does all the decode at the end.
        pass


#
# --------------------------------------------------------------------


Image.register_open(IcoImageFile.format, IcoImageFile, _accept)
Image.register_save(IcoImageFile.format, _save)
Image.register_extension(IcoImageFile.format, ".ico")

Image.register_mime(IcoImageFile.format, "image/x-icon")

```
--- 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:** Incorrect Image Mode When Saving ICO Files in BMP Format

**Description:**
When attempting to save ICO images in BMP format, images with modes `'1'`, `'L'`, `'P'`, and `'RGB'` are incorrectly saved with the `'RGBA'` mode. This results in a mismatch between the original image mode and the saved file, leading to unexpected behavior when the ICO file is used.

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

output = io.BytesIO()
im = Image.new('L', (32, 32))  # Creating a grayscale image
im.save(output, "ico", bitmap_format="bmp", sizes=[(32, 32)])
output.seek(0)
with Image.open(output) as reloaded:
    print(reloaded.mode)  # Outputs: 'RGBA' instead of 'L'
```

**Expected Behavior:**
The saved ICO image should retain the original image mode. For instance, a grayscale (`'L'`) image should remain in `'L'` mode after being saved in BMP format within an ICO file.

**Actual Behavior:**
The saved ICO image is incorrectly set to `'RGBA'` mode regardless of the original image mode, causing inconsistencies and potential issues in image rendering.

[/ISSUE]
{
    "\u001b[1mtest_sanity\u001b[0m": "PASSED",
    "\u001b[1mtest_black_and_white\u001b[0m": "PASSED",
    "\u001b[1mtest_invalid_file\u001b[0m": "PASSED",
    "\u001b[1mtest_save_to_bytes\u001b[0m": "PASSED",
    "\u001b[1mtest_save_to_bytes_bmp[1]\u001b[0m": "PASSED",
    "\u001b[1mtest_save_to_bytes_bmp[L]\u001b[0m": "PASSED",
    "\u001b[1mtest_save_to_bytes_bmp[P]\u001b[0m": "PASSED",
    "\u001b[1mtest_save_to_bytes_bmp[RGB]\u001b[0m": "PASSED",
    "\u001b[1mtest_save_to_bytes_bmp[RGBA]\u001b[0m": "PASSED",
    "\u001b[1mtest_incorrect_size\u001b[0m": "PASSED",
    "\u001b[1mtest_save_256x256\u001b[0m": "PASSED",
    "\u001b[1mtest_only_save_relevant_sizes\u001b[0m": "PASSED",
    "\u001b[1mtest_save_append_images\u001b[0m": "PASSED",
    "\u001b[1mtest_unexpected_size\u001b[0m": "PASSED",
    "\u001b[1mtest_draw_reloaded\u001b[0m": "PASSED"
}
diff --git a/src/PIL/IcoImagePlugin.py b/src/PIL/IcoImagePlugin.py
index dbc108d7b..ffb1e873d 100644
--- a/src/PIL/IcoImagePlugin.py
+++ b/src/PIL/IcoImagePlugin.py
@@ -30,6 +30,7 @@ from math import ceil, log
 from . import BmpImagePlugin, Image, ImageFile, PngImagePlugin
 from ._binary import i16le as i16
 from ._binary import i32le as i32
+from ._binary import o32le as o32
 
 #
 # --------------------------------------------------------------------
@@ -53,6 +54,7 @@ def _save(im, fp, filename):
     sizes = list(sizes)
     fp.write(struct.pack("<H", len(sizes)))  # idCount(2)
     offset = fp.tell() + len(sizes) * 16
+    bmp = im.encoderinfo.get("bitmap_format") == "bmp"
     provided_images = {im.size: im for im in im.encoderinfo.get("append_images", [])}
     for size in sizes:
         width, height = size
@@ -62,17 +64,30 @@ def _save(im, fp, filename):
         fp.write(b"\0")  # bColorCount(1)
         fp.write(b"\0")  # bReserved(1)
         fp.write(b"\0\0")  # wPlanes(2)
-        fp.write(struct.pack("<H", 32))  # wBitCount(2)
 
-        image_io = BytesIO()
         tmp = provided_images.get(size)
         if not tmp:
             # TODO: invent a more convenient method for proportional scalings
             tmp = im.copy()
             tmp.thumbnail(size, Image.LANCZOS, reducing_gap=None)
-        tmp.save(image_io, "png")
+        bits = BmpImagePlugin.SAVE[tmp.mode][1] if bmp else 32
+        fp.write(struct.pack("<H", bits))  # wBitCount(2)
+
+        image_io = BytesIO()
+        if bmp:
+            tmp.save(image_io, "dib")
+
+            if bits != 32:
+                and_mask = Image.new("1", tmp.size)
+                ImageFile._save(
+                    and_mask, image_io, [("raw", (0, 0) + tmp.size, 0, ("1", 0, -1))]
+                )
+        else:
+            tmp.save(image_io, "png")
         image_io.seek(0)
         image_bytes = image_io.read()
+        if bmp:
+            image_bytes = image_bytes[:8] + o32(height * 2) + image_bytes[12:]
         bytes_len = len(image_bytes)
         fp.write(struct.pack("<I", bytes_len))  # dwBytesInRes(4)
         fp.write(struct.pack("<I", offset))  # dwImageOffset(4)
 

{"src/PIL/IcoImagePlugin.py": "#\n# The Python Imaging Library.\n# $Id$\n#\n# Windows Icon support for PIL\n#\n# History:\n#       96-05-27 fl     Created\n#\n# Copyright (c) Secret Labs AB 1997.\n# Copyright (c) Fredrik Lundh 1996.\n#\n# See the README file for information on usage and redistribution.\n#\n\n# This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis\n# <casadebender@gmail.com>.\n# https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki\n#\n# Icon format references:\n#   * https://en.wikipedia.org/wiki/ICO_(file_format)\n#   * https://msdn.microsoft.com/en-us/library/ms997538.aspx\n\n\nimport struct\nimport warnings\nfrom io import BytesIO\nfrom math import ceil, log\n\nfrom . import BmpImagePlugin, Image, ImageFile, PngImagePlugin\nfrom ._binary import i16le as i16\nfrom ._binary import i32le as i32\n\n#\n# --------------------------------------------------------------------\n\n_MAGIC = b\"\\0\\0\\1\\0\"\n\n\ndef _save(im, fp, filename):\n    fp.write(_MAGIC)  # (2+2)\n    sizes = im.encoderinfo.get(\n        \"sizes\",\n        [(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)],\n    )\n    width, height = im.size\n    sizes = filter(\n        lambda x: False\n        if (x[0] > width or x[1] > height or x[0] > 256 or x[1] > 256)\n        else True,\n        sizes,\n    )\n    sizes = list(sizes)\n    fp.write(struct.pack(\"<H\", len(sizes)))  # idCount(2)\n    offset = fp.tell() + len(sizes) * 16\n    provided_images = {im.size: im for im in im.encoderinfo.get(\"append_images\", [])}\n    for size in sizes:\n        width, height = size\n        # 0 means 256\n        fp.write(struct.pack(\"B\", width if width < 256 else 0))  # bWidth(1)\n        fp.write(struct.pack(\"B\", height if height < 256 else 0))  # bHeight(1)\n        fp.write(b\"\\0\")  # bColorCount(1)\n        fp.write(b\"\\0\")  # bReserved(1)\n        fp.write(b\"\\0\\0\")  # wPlanes(2)\n        fp.write(struct.pack(\"<H\", 32))  # wBitCount(2)\n\n        image_io = BytesIO()\n        tmp = provided_images.get(size)\n        if not tmp:\n            # TODO: invent a more convenient method for proportional scalings\n            tmp = im.copy()\n            tmp.thumbnail(size, Image.LANCZOS, reducing_gap=None)\n        tmp.save(image_io, \"png\")\n        image_io.seek(0)\n        image_bytes = image_io.read()\n        bytes_len = len(image_bytes)\n        fp.write(struct.pack(\"<I\", bytes_len))  # dwBytesInRes(4)\n        fp.write(struct.pack(\"<I\", offset))  # dwImageOffset(4)\n        current = fp.tell()\n        fp.seek(offset)\n        fp.write(image_bytes)\n        offset = offset + bytes_len\n        fp.seek(current)\n\n\ndef _accept(prefix):\n    return prefix[:4] == _MAGIC\n\n\nclass IcoFile:\n    def __init__(self, buf):\n        \"\"\"\n        Parse image from file-like object containing ico file data\n        \"\"\"\n\n        # check magic\n        s = buf.read(6)\n        if not _accept(s):\n            raise SyntaxError(\"not an ICO file\")\n\n        self.buf = buf\n        self.entry = []\n\n        # Number of items in file\n        self.nb_items = i16(s, 4)\n\n        # Get headers for each item\n        for i in range(self.nb_items):\n            s = buf.read(16)\n\n            icon_header = {\n                \"width\": s[0],\n                \"height\": s[1],\n                \"nb_color\": s[2],  # No. of colors in image (0 if >=8bpp)\n                \"reserved\": s[3],\n                \"planes\": i16(s, 4),\n                \"bpp\": i16(s, 6),\n                \"size\": i32(s, 8),\n                \"offset\": i32(s, 12),\n            }\n\n            # See Wikipedia\n            for j in (\"width\", \"height\"):\n                if not icon_header[j]:\n                    icon_header[j] = 256\n\n            # See Wikipedia notes about color depth.\n            # We need this just to differ images with equal sizes\n            icon_header[\"color_depth\"] = (\n                icon_header[\"bpp\"]\n                or (\n                    icon_header[\"nb_color\"] != 0\n                    and ceil(log(icon_header[\"nb_color\"], 2))\n                )\n                or 256\n            )\n\n            icon_header[\"dim\"] = (icon_header[\"width\"], icon_header[\"height\"])\n            icon_header[\"square\"] = icon_header[\"width\"] * icon_header[\"height\"]\n\n            self.entry.append(icon_header)\n\n        self.entry = sorted(self.entry, key=lambda x: x[\"color_depth\"])\n        # ICO images are usually squares\n        # self.entry = sorted(self.entry, key=lambda x: x['width'])\n        self.entry = sorted(self.entry, key=lambda x: x[\"square\"])\n        self.entry.reverse()\n\n    def sizes(self):\n        \"\"\"\n        Get a list of all available icon sizes and color depths.\n        \"\"\"\n        return {(h[\"width\"], h[\"height\"]) for h in self.entry}\n\n    def getentryindex(self, size, bpp=False):\n        for (i, h) in enumerate(self.entry):\n            if size == h[\"dim\"] and (bpp is False or bpp == h[\"color_depth\"]):\n                return i\n        return 0\n\n    def getimage(self, size, bpp=False):\n        \"\"\"\n        Get an image from the icon\n        \"\"\"\n        return self.frame(self.getentryindex(size, bpp))\n\n    def frame(self, idx):\n        \"\"\"\n        Get an image from frame idx\n        \"\"\"\n\n        header = self.entry[idx]\n\n        self.buf.seek(header[\"offset\"])\n        data = self.buf.read(8)\n        self.buf.seek(header[\"offset\"])\n\n        if data[:8] == PngImagePlugin._MAGIC:\n            # png frame\n            im = PngImagePlugin.PngImageFile(self.buf)\n            Image._decompression_bomb_check(im.size)\n        else:\n            # XOR + AND mask bmp frame\n            im = BmpImagePlugin.DibImageFile(self.buf)\n            Image._decompression_bomb_check(im.size)\n\n            # change tile dimension to only encompass XOR image\n            im._size = (im.size[0], int(im.size[1] / 2))\n            d, e, o, a = im.tile[0]\n            im.tile[0] = d, (0, 0) + im.size, o, a\n\n            # figure out where AND mask image starts\n            bpp = header[\"bpp\"]\n            if 32 == bpp:\n                # 32-bit color depth icon image allows semitransparent areas\n                # PIL's DIB format ignores transparency bits, recover them.\n                # The DIB is packed in BGRX byte order where X is the alpha\n                # channel.\n\n                # Back up to start of bmp data\n                self.buf.seek(o)\n                # extract every 4th byte (eg. 3,7,11,15,...)\n                alpha_bytes = self.buf.read(im.size[0] * im.size[1] * 4)[3::4]\n\n                # convert to an 8bpp grayscale image\n                mask = Image.frombuffer(\n                    \"L\",  # 8bpp\n                    im.size,  # (w, h)\n                    alpha_bytes,  # source chars\n                    \"raw\",  # raw decoder\n                    (\"L\", 0, -1),  # 8bpp inverted, unpadded, reversed\n                )\n            else:\n                # get AND image from end of bitmap\n                w = im.size[0]\n                if (w % 32) > 0:\n                    # bitmap row data is aligned to word boundaries\n                    w += 32 - (im.size[0] % 32)\n\n                # the total mask data is\n                # padded row size * height / bits per char\n\n                and_mask_offset = o + int(im.size[0] * im.size[1] * (bpp / 8.0))\n                total_bytes = int((w * im.size[1]) / 8)\n\n                self.buf.seek(and_mask_offset)\n                mask_data = self.buf.read(total_bytes)\n\n                # convert raw data to image\n                mask = Image.frombuffer(\n                    \"1\",  # 1 bpp\n                    im.size,  # (w, h)\n                    mask_data,  # source chars\n                    \"raw\",  # raw decoder\n                    (\"1;I\", int(w / 8), -1),  # 1bpp inverted, padded, reversed\n                )\n\n                # now we have two images, im is XOR image and mask is AND image\n\n            # apply mask image as alpha channel\n            im = im.convert(\"RGBA\")\n            im.putalpha(mask)\n\n        return im\n\n\n##\n# Image plugin for Windows Icon files.\n\n\nclass IcoImageFile(ImageFile.ImageFile):\n    \"\"\"\n    PIL read-only image support for Microsoft Windows .ico files.\n\n    By default the largest resolution image in the file will be loaded. This\n    can be changed by altering the 'size' attribute before calling 'load'.\n\n    The info dictionary has a key 'sizes' that is a list of the sizes available\n    in the icon file.\n\n    Handles classic, XP and Vista icon formats.\n\n    When saving, PNG compression is used. Support for this was only added in\n    Windows Vista. If you are unable to view the icon in Windows, convert the\n    image to \"RGBA\" mode before saving.\n\n    This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis\n    <casadebender@gmail.com>.\n    https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki\n    \"\"\"\n\n    format = \"ICO\"\n    format_description = \"Windows Icon\"\n\n    def _open(self):\n        self.ico = IcoFile(self.fp)\n        self.info[\"sizes\"] = self.ico.sizes()\n        self.size = self.ico.entry[0][\"dim\"]\n        self.load()\n\n    @property\n    def size(self):\n        return self._size\n\n    @size.setter\n    def size(self, value):\n        if value not in self.info[\"sizes\"]:\n            raise ValueError(\"This is not one of the allowed sizes of this image\")\n        self._size = value\n\n    def load(self):\n        if self.im and self.im.size == self.size:\n            # Already loaded\n            return\n        im = self.ico.getimage(self.size)\n        # if tile is PNG, it won't really be loaded yet\n        im.load()\n        self.im = im.im\n        self.mode = im.mode\n        if im.size != self.size:\n            warnings.warn(\"Image was not the expected size\")\n\n            index = self.ico.getentryindex(self.size)\n            sizes = list(self.info[\"sizes\"])\n            sizes[index] = im.size\n            self.info[\"sizes\"] = set(sizes)\n\n            self.size = im.size\n\n    def load_seek(self):\n        # Flag the ImageFile.Parser so that it\n        # just does all the decode at the end.\n        pass\n\n\n#\n# --------------------------------------------------------------------\n\n\nImage.register_open(IcoImageFile.format, IcoImageFile, _accept)\nImage.register_save(IcoImageFile.format, _save)\nImage.register_extension(IcoImageFile.format, \".ico\")\n\nImage.register_mime(IcoImageFile.format, \"image/x-icon\")\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:** Incorrect Image Mode When Saving ICO Files in BMP Format

**Description:**
When attempting to save ICO images in BMP format, images with modes `'1'`, `'L'`, `'P'`, and `'RGB'` are incorrectly saved with the `'RGBA'` mode. This results in a mismatch between the original image mode and the saved file, leading to unexpected behavior when the ICO file is used.

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

output = io.BytesIO()
im = Image.new('L', (32, 32))  # Creating a grayscale image
im.save(output, "ico", bitmap_format="bmp", sizes=[(32, 32)])
output.seek(0)
with Image.open(output) as reloaded:
    print(reloaded.mode)  # Outputs: 'RGBA' instead of 'L'
```

**Expected Behavior:**
The saved ICO image should retain the original image mode. For instance, a grayscale (`'L'`) image should remain in `'L'` mode after being saved in BMP format within an ICO file.

**Actual Behavior:**
The saved ICO image is incorrectly set to `'RGBA'` mode regardless of the original image mode, causing inconsistencies and potential issues in image rendering.

[/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/IcoImagePlugin.py
#
# The Python Imaging Library.
# $Id$
#
# Windows Icon support for PIL
#
# History:
#       96-05-27 fl     Created
#
# Copyright (c) Secret Labs AB 1997.
# Copyright (c) Fredrik Lundh 1996.
#
# See the README file for information on usage and redistribution.
#

# This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis
# <casadebender@gmail.com>.
# https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki
#
# Icon format references:
#   * https://en.wikipedia.org/wiki/ICO_(file_format)
#   * https://msdn.microsoft.com/en-us/library/ms997538.aspx


import struct
import warnings
from io import BytesIO
from math import ceil, log

from . import BmpImagePlugin, Image, ImageFile, PngImagePlugin
from ._binary import i16le as i16
from ._binary import i32le as i32

#
# --------------------------------------------------------------------

_MAGIC = b"\0\0\1\0"


def _save(im, fp, filename):
    fp.write(_MAGIC)  # (2+2)
    sizes = im.encoderinfo.get(
        "sizes",
        [(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)],
    )
    width, height = im.size
    sizes = filter(
        lambda x: False
        if (x[0] > width or x[1] > height or x[0] > 256 or x[1] > 256)
        else True,
        sizes,
    )
    sizes = list(sizes)
    fp.write(struct.pack("<H", len(sizes)))  # idCount(2)
    offset = fp.tell() + len(sizes) * 16
    provided_images = {im.size: im for im in im.encoderinfo.get("append_images", [])}
    for size in sizes:
        width, height = size
        # 0 means 256
        fp.write(struct.pack("B", width if width < 256 else 0))  # bWidth(1)
        fp.write(struct.pack("B", height if height < 256 else 0))  # bHeight(1)
        fp.write(b"\0")  # bColorCount(1)
        fp.write(b"\0")  # bReserved(1)
        fp.write(b"\0\0")  # wPlanes(2)
        fp.write(struct.pack("<H", 32))  # wBitCount(2)

        image_io = BytesIO()
        tmp = provided_images.get(size)
        if not tmp:
            # TODO: invent a more convenient method for proportional scalings
            tmp = im.copy()
            tmp.thumbnail(size, Image.LANCZOS, reducing_gap=None)
        tmp.save(image_io, "png")
        image_io.seek(0)
        image_bytes = image_io.read()
        bytes_len = len(image_bytes)
        fp.write(struct.pack("<I", bytes_len))  # dwBytesInRes(4)
        fp.write(struct.pack("<I", offset))  # dwImageOffset(4)
        current = fp.tell()
        fp.seek(offset)
        fp.write(image_bytes)
        offset = offset + bytes_len
        fp.seek(current)


def _accept(prefix):
    return prefix[:4] == _MAGIC


class IcoFile:
    def __init__(self, buf):
        """
        Parse image from file-like object containing ico file data
        """

        # check magic
        s = buf.read(6)
        if not _accept(s):
            raise SyntaxError("not an ICO file")

        self.buf = buf
        self.entry = []

        # Number of items in file
        self.nb_items = i16(s, 4)

        # Get headers for each item
        for i in range(self.nb_items):
            s = buf.read(16)

            icon_header = {
                "width": s[0],
                "height": s[1],
                "nb_color": s[2],  # No. of colors in image (0 if >=8bpp)
                "reserved": s[3],
                "planes": i16(s, 4),
                "bpp": i16(s, 6),
                "size": i32(s, 8),
                "offset": i32(s, 12),
            }

            # See Wikipedia
            for j in ("width", "height"):
                if not icon_header[j]:
                    icon_header[j] = 256

            # See Wikipedia notes about color depth.
            # We need this just to differ images with equal sizes
            icon_header["color_depth"] = (
                icon_header["bpp"]
                or (
                    icon_header["nb_color"] != 0
                    and ceil(log(icon_header["nb_color"], 2))
                )
                or 256
            )

            icon_header["dim"] = (icon_header["width"], icon_header["height"])
            icon_header["square"] = icon_header["width"] * icon_header["height"]

            self.entry.append(icon_header)

        self.entry = sorted(self.entry, key=lambda x: x["color_depth"])
        # ICO images are usually squares
        # self.entry = sorted(self.entry, key=lambda x: x['width'])
        self.entry = sorted(self.entry, key=lambda x: x["square"])
        self.entry.reverse()

    def sizes(self):
        """
        Get a list of all available icon sizes and color depths.
        """
        return {(h["width"], h["height"]) for h in self.entry}

    def getentryindex(self, size, bpp=False):
        for (i, h) in enumerate(self.entry):
            if size == h["dim"] and (bpp is False or bpp == h["color_depth"]):
                return i
        return 0

    def getimage(self, size, bpp=False):
        """
        Get an image from the icon
        """
        return self.frame(self.getentryindex(size, bpp))

    def frame(self, idx):
        """
        Get an image from frame idx
        """

        header = self.entry[idx]

        self.buf.seek(header["offset"])
        data = self.buf.read(8)
        self.buf.seek(header["offset"])

        if data[:8] == PngImagePlugin._MAGIC:
            # png frame
            im = PngImagePlugin.PngImageFile(self.buf)
            Image._decompression_bomb_check(im.size)
        else:
            # XOR + AND mask bmp frame
            im = BmpImagePlugin.DibImageFile(self.buf)
            Image._decompression_bomb_check(im.size)

            # change tile dimension to only encompass XOR image
            im._size = (im.size[0], int(im.size[1] / 2))
            d, e, o, a = im.tile[0]
            im.tile[0] = d, (0, 0) + im.size, o, a

            # figure out where AND mask image starts
            bpp = header["bpp"]
            if 32 == bpp:
                # 32-bit color depth icon image allows semitransparent areas
                # PIL's DIB format ignores transparency bits, recover them.
                # The DIB is packed in BGRX byte order where X is the alpha
                # channel.

                # Back up to start of bmp data
                self.buf.seek(o)
                # extract every 4th byte (eg. 3,7,11,15,...)
                alpha_bytes = self.buf.read(im.size[0] * im.size[1] * 4)[3::4]

                # convert to an 8bpp grayscale image
                mask = Image.frombuffer(
                    "L",  # 8bpp
                    im.size,  # (w, h)
                    alpha_bytes,  # source chars
                    "raw",  # raw decoder
                    ("L", 0, -1),  # 8bpp inverted, unpadded, reversed
                )
            else:
                # get AND image from end of bitmap
                w = im.size[0]
                if (w % 32) > 0:
                    # bitmap row data is aligned to word boundaries
                    w += 32 - (im.size[0] % 32)

                # the total mask data is
                # padded row size * height / bits per char

                and_mask_offset = o + int(im.size[0] * im.size[1] * (bpp / 8.0))
                total_bytes = int((w * im.size[1]) / 8)

                self.buf.seek(and_mask_offset)
                mask_data = self.buf.read(total_bytes)

                # convert raw data to image
                mask = Image.frombuffer(
                    "1",  # 1 bpp
                    im.size,  # (w, h)
                    mask_data,  # source chars
                    "raw",  # raw decoder
                    ("1;I", int(w / 8), -1),  # 1bpp inverted, padded, reversed
                )

                # now we have two images, im is XOR image and mask is AND image

            # apply mask image as alpha channel
            im = im.convert("RGBA")
            im.putalpha(mask)

        return im


##
# Image plugin for Windows Icon files.


class IcoImageFile(ImageFile.ImageFile):
    """
    PIL read-only image support for Microsoft Windows .ico files.

    By default the largest resolution image in the file will be loaded. This
    can be changed by altering the 'size' attribute before calling 'load'.

    The info dictionary has a key 'sizes' that is a list of the sizes available
    in the icon file.

    Handles classic, XP and Vista icon formats.

    When saving, PNG compression is used. Support for this was only added in
    Windows Vista. If you are unable to view the icon in Windows, convert the
    image to "RGBA" mode before saving.

    This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis
    <casadebender@gmail.com>.
    https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki
    """

    format = "ICO"
    format_description = "Windows Icon"

    def _open(self):
        self.ico = IcoFile(self.fp)
        self.info["sizes"] = self.ico.sizes()
        self.size = self.ico.entry[0]["dim"]
        self.load()

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

    @size.setter
    def size(self, value):
        if value not in self.info["sizes"]:
            raise ValueError("This is not one of the allowed sizes of this image")
        self._size = value

    def load(self):
        if self.im and self.im.size == self.size:
            # Already loaded
            return
        im = self.ico.getimage(self.size)
        # if tile is PNG, it won't really be loaded yet
        im.load()
        self.im = im.im
        self.mode = im.mode
        if im.size != self.size:
            warnings.warn("Image was not the expected size")

            index = self.ico.getentryindex(self.size)
            sizes = list(self.info["sizes"])
            sizes[index] = im.size
            self.info["sizes"] = set(sizes)

            self.size = im.size

    def load_seek(self):
        # Flag the ImageFile.Parser so that it
        # just does all the decode at the end.
        pass


#
# --------------------------------------------------------------------


Image.register_open(IcoImageFile.format, IcoImageFile, _accept)
Image.register_save(IcoImageFile.format, _save)
Image.register_extension(IcoImageFile.format, ".ico")

Image.register_mime(IcoImageFile.format, "image/x-icon")

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