{
    "file_diffs": [
        {
            "old_file_content": "from __future__ import annotations\n\nimport io\nimport logging\nimport os\nimport shutil\nimport sys\nimport tempfile\nimport warnings\nfrom pathlib import Path\nfrom types import ModuleType\nfrom typing import IO, Any\n\nimport pytest\n\nfrom PIL import (\n    ExifTags,\n    Image,\n    ImageDraw,\n    ImageFile,\n    ImagePalette,\n    UnidentifiedImageError,\n    features,\n)\n\nfrom .helper import (\n    assert_image_equal,\n    assert_image_equal_tofile,\n    assert_image_similar,\n    assert_image_similar_tofile,\n    assert_not_all_same,\n    hopper,\n    is_big_endian,\n    is_win32,\n    mark_if_feature_version,\n    skip_unless_feature,\n)\n\nElementTree: ModuleType | None\ntry:\n    from defusedxml import ElementTree\nexcept ImportError:\n    ElementTree = None\n\n\n# Deprecation helper\ndef helper_image_new(mode: str, size: tuple[int, int]) -> Image.Image:\n    if mode.startswith(\"BGR;\"):\n        with pytest.warns(DeprecationWarning):\n            return Image.new(mode, size)\n    else:\n        return Image.new(mode, size)\n\n\nclass TestImage:\n    @pytest.mark.parametrize(\"mode\", Image.MODES + [\"BGR;15\", \"BGR;16\", \"BGR;24\"])\n    def test_image_modes_success(self, mode: str) -> None:\n        helper_image_new(mode, (1, 1))\n\n    @pytest.mark.parametrize(\"mode\", (\"\", \"bad\", \"very very long\"))\n    def test_image_modes_fail(self, mode: str) -> None:\n        with pytest.raises(ValueError) as e:\n            Image.new(mode, (1, 1))\n        assert str(e.value) == \"unrecognized image mode\"\n\n    def test_exception_inheritance(self) -> None:\n        assert issubclass(UnidentifiedImageError, OSError)\n\n    def test_sanity(self) -> None:\n        im = Image.new(\"L\", (100, 100))\n        assert repr(im)[:45] == \"<PIL.Image.Image image mode=L size=100x100 at\"\n        assert im.mode == \"L\"\n        assert im.size == (100, 100)\n\n        im = Image.new(\"RGB\", (100, 100))\n        assert repr(im)[:45] == \"<PIL.Image.Image image mode=RGB size=100x100 \"\n        assert im.mode == \"RGB\"\n        assert im.size == (100, 100)\n\n        Image.new(\"L\", (100, 100), None)\n        im2 = Image.new(\"L\", (100, 100), 0)\n        im3 = Image.new(\"L\", (100, 100), \"black\")\n\n        assert im2.getcolors() == [(10000, 0)]\n        assert im3.getcolors() == [(10000, 0)]\n\n        with pytest.raises(ValueError):\n            Image.new(\"X\", (100, 100))\n        with pytest.raises(ValueError):\n            Image.new(\"\", (100, 100))\n        # with pytest.raises(MemoryError):\n        #   Image.new(\"L\", (1000000, 1000000))\n\n    def test_repr_pretty(self) -> None:\n        class Pretty:\n            def text(self, text: str) -> None:\n                self.pretty_output = text\n\n        im = Image.new(\"L\", (100, 100))\n\n        p = Pretty()\n        im._repr_pretty_(p, None)\n        assert p.pretty_output == \"<PIL.Image.Image image mode=L size=100x100>\"\n\n    def test_open_formats(self) -> None:\n        PNGFILE = \"Tests/images/hopper.png\"\n        JPGFILE = \"Tests/images/hopper.jpg\"\n\n        with pytest.raises(TypeError):\n            with Image.open(PNGFILE, formats=123):  # type: ignore[arg-type]\n                pass\n\n        format_list: list[list[str] | tuple[str, ...]] = [\n            [\"JPEG\"],\n            (\"JPEG\",),\n            [\"jpeg\"],\n            [\"Jpeg\"],\n            [\"jPeG\"],\n            [\"JpEg\"],\n        ]\n        for formats in format_list:\n            with pytest.raises(UnidentifiedImageError):\n                with Image.open(PNGFILE, formats=formats):\n                    pass\n\n            with Image.open(JPGFILE, formats=formats) as im:\n                assert im.mode == \"RGB\"\n                assert im.size == (128, 128)\n\n        for file in [PNGFILE, JPGFILE]:\n            with Image.open(file, formats=None) as im:\n                assert im.mode == \"RGB\"\n                assert im.size == (128, 128)\n\n    def test_width_height(self) -> None:\n        im = Image.new(\"RGB\", (1, 2))\n        assert im.width == 1\n        assert im.height == 2\n\n        with pytest.raises(AttributeError):\n            im.size = (3, 4)  # type: ignore[misc]\n\n    def test_set_mode(self) -> None:\n        im = Image.new(\"RGB\", (1, 1))\n\n        with pytest.raises(AttributeError):\n            im.mode = \"P\"  # type: ignore[misc]\n\n    def test_invalid_image(self) -> None:\n        im = io.BytesIO(b\"\")\n        with pytest.raises(UnidentifiedImageError):\n            with Image.open(im):\n                pass\n\n    def test_bad_mode(self) -> None:\n        with pytest.raises(ValueError):\n            with Image.open(\"filename\", \"bad mode\"):  # type: ignore[arg-type]\n                pass\n\n    def test_stringio(self) -> None:\n        with pytest.raises(ValueError):\n            with Image.open(io.StringIO()):  # type: ignore[arg-type]\n                pass\n\n    def test_pathlib(self, tmp_path: Path) -> None:\n        with Image.open(Path(\"Tests/images/multipage-mmap.tiff\")) as im:\n            assert im.mode == \"P\"\n            assert im.size == (10, 10)\n\n        with Image.open(Path(\"Tests/images/hopper.jpg\")) as im:\n            assert im.mode == \"RGB\"\n            assert im.size == (128, 128)\n\n            for ext in (\".jpg\", \".jp2\"):\n                if ext == \".jp2\" and not features.check_codec(\"jpg_2000\"):\n                    pytest.skip(\"jpg_2000 not available\")\n                temp_file = str(tmp_path / (\"temp.\" + ext))\n                if os.path.exists(temp_file):\n                    os.remove(temp_file)\n                im.save(Path(temp_file))\n\n    def test_fp_name(self, tmp_path: Path) -> None:\n        temp_file = str(tmp_path / \"temp.jpg\")\n\n        class FP(io.BytesIO):\n            name: str\n\n            if sys.version_info >= (3, 12):\n                from collections.abc import Buffer\n\n                def write(self, data: Buffer) -> int:\n                    return len(data)\n\n            else:\n\n                def write(self, data: Any) -> int:\n                    return len(data)\n\n        fp = FP()\n        fp.name = temp_file\n\n        im = hopper()\n        im.save(fp)\n\n    def test_tempfile(self) -> None:\n        # see #1460, pathlib support breaks tempfile.TemporaryFile on py27\n        # Will error out on save on 3.0.0\n        im = hopper()\n        with tempfile.TemporaryFile() as fp:\n            im.save(fp, \"JPEG\")\n            fp.seek(0)\n            with Image.open(fp) as reloaded:\n                assert_image_similar(im, reloaded, 20)\n\n    def test_unknown_extension(self, tmp_path: Path) -> None:\n        im = hopper()\n        temp_file = str(tmp_path / \"temp.unknown\")\n        with pytest.raises(ValueError):\n            im.save(temp_file)\n\n    def test_internals(self) -> None:\n        im = Image.new(\"L\", (100, 100))\n        im.readonly = 1\n        im._copy()\n        assert not im.readonly\n\n        im.readonly = 1\n        im.paste(0, (0, 0, 100, 100))\n        assert not im.readonly\n\n    @pytest.mark.skipif(is_win32(), reason=\"Test requires opening tempfile twice\")\n    @pytest.mark.skipif(\n        sys.platform == \"cygwin\",\n        reason=\"Test requires opening an mmaped file for writing\",\n    )\n    def test_readonly_save(self, tmp_path: Path) -> None:\n        temp_file = str(tmp_path / \"temp.bmp\")\n        shutil.copy(\"Tests/images/rgb32bf-rgba.bmp\", temp_file)\n\n        with Image.open(temp_file) as im:\n            assert im.readonly\n            im.save(temp_file)\n\n    def test_dump(self, tmp_path: Path) -> None:\n        im = Image.new(\"L\", (10, 10))\n        im._dump(str(tmp_path / \"temp_L.ppm\"))\n\n        im = Image.new(\"RGB\", (10, 10))\n        im._dump(str(tmp_path / \"temp_RGB.ppm\"))\n\n        im = Image.new(\"HSV\", (10, 10))\n        with pytest.raises(ValueError):\n            im._dump(str(tmp_path / \"temp_HSV.ppm\"))\n\n    def test_comparison_with_other_type(self) -> None:\n        # Arrange\n        item = Image.new(\"RGB\", (25, 25), \"#000\")\n        num = 12\n\n        # Act/Assert\n        # Shouldn't cause AttributeError (#774)\n        assert item is not None\n        assert item != num\n\n    def test_expand_x(self) -> None:\n        # Arrange\n        im = hopper()\n        orig_size = im.size\n        xmargin = 5\n\n        # Act\n        im = im._expand(xmargin)\n\n        # Assert\n        assert im.size[0] == orig_size[0] + 2 * xmargin\n        assert im.size[1] == orig_size[1] + 2 * xmargin\n\n    def test_expand_xy(self) -> None:\n        # Arrange\n        im = hopper()\n        orig_size = im.size\n        xmargin = 5\n        ymargin = 3\n\n        # Act\n        im = im._expand(xmargin, ymargin)\n\n        # Assert\n        assert im.size[0] == orig_size[0] + 2 * xmargin\n        assert im.size[1] == orig_size[1] + 2 * ymargin\n\n    def test_getbands(self) -> None:\n        # Assert\n        assert hopper(\"RGB\").getbands() == (\"R\", \"G\", \"B\")\n        assert hopper(\"YCbCr\").getbands() == (\"Y\", \"Cb\", \"Cr\")\n\n    def test_getchannel_wrong_params(self) -> None:\n        im = hopper()\n\n        with pytest.raises(ValueError):\n            im.getchannel(-1)\n        with pytest.raises(ValueError):\n            im.getchannel(3)\n        with pytest.raises(ValueError):\n            im.getchannel(\"Z\")\n        with pytest.raises(ValueError):\n            im.getchannel(\"1\")\n\n    def test_getchannel(self) -> None:\n        im = hopper(\"YCbCr\")\n        Y, Cb, Cr = im.split()\n\n        assert_image_equal(Y, im.getchannel(0))\n        assert_image_equal(Y, im.getchannel(\"Y\"))\n        assert_image_equal(Cb, im.getchannel(1))\n        assert_image_equal(Cb, im.getchannel(\"Cb\"))\n        assert_image_equal(Cr, im.getchannel(2))\n        assert_image_equal(Cr, im.getchannel(\"Cr\"))\n\n    def test_getbbox(self) -> None:\n        # Arrange\n        im = hopper()\n\n        # Act\n        bbox = im.getbbox()\n\n        # Assert\n        assert bbox == (0, 0, 128, 128)\n\n    def test_ne(self) -> None:\n        # Arrange\n        im1 = Image.new(\"RGB\", (25, 25), \"black\")\n        im2 = Image.new(\"RGB\", (25, 25), \"white\")\n\n        # Act / Assert\n        assert im1 != im2\n\n    def test_alpha_composite(self) -> None:\n        # https://stackoverflow.com/questions/3374878\n        # Arrange\n        expected_colors = sorted(\n            [\n                (1122, (128, 127, 0, 255)),\n                (1089, (0, 255, 0, 255)),\n                (3300, (255, 0, 0, 255)),\n                (1156, (170, 85, 0, 192)),\n                (1122, (0, 255, 0, 128)),\n                (1122, (255, 0, 0, 128)),\n                (1089, (0, 255, 0, 0)),\n            ]\n        )\n\n        dst = Image.new(\"RGBA\", size=(100, 100), color=(0, 255, 0, 255))\n        draw = ImageDraw.Draw(dst)\n        draw.rectangle((0, 33, 100, 66), fill=(0, 255, 0, 128))\n        draw.rectangle((0, 67, 100, 100), fill=(0, 255, 0, 0))\n        src = Image.new(\"RGBA\", size=(100, 100), color=(255, 0, 0, 255))\n        draw = ImageDraw.Draw(src)\n        draw.rectangle((33, 0, 66, 100), fill=(255, 0, 0, 128))\n        draw.rectangle((67, 0, 100, 100), fill=(255, 0, 0, 0))\n\n        # Act\n        img = Image.alpha_composite(dst, src)\n\n        # Assert\n        img_colors = sorted(img.getcolors())\n        assert img_colors == expected_colors\n\n    def test_alpha_inplace(self) -> None:\n        src = Image.new(\"RGBA\", (128, 128), \"blue\")\n\n        over = Image.new(\"RGBA\", (128, 128), \"red\")\n        mask = hopper(\"L\")\n        over.putalpha(mask)\n\n        target = Image.alpha_composite(src, over)\n\n        # basic\n        full = src.copy()\n        full.alpha_composite(over)\n        assert_image_equal(full, target)\n\n        # with offset down to right\n        offset = src.copy()\n        offset.alpha_composite(over, (64, 64))\n        assert_image_equal(offset.crop((64, 64, 127, 127)), target.crop((0, 0, 63, 63)))\n        assert offset.size == (128, 128)\n\n        # with negative offset\n        offset = src.copy()\n        offset.alpha_composite(over, (-64, -64))\n        assert_image_equal(offset.crop((0, 0, 63, 63)), target.crop((64, 64, 127, 127)))\n        assert offset.size == (128, 128)\n\n        # offset and crop\n        box = src.copy()\n        box.alpha_composite(over, (64, 64), (0, 0, 32, 32))\n        assert_image_equal(box.crop((64, 64, 96, 96)), target.crop((0, 0, 32, 32)))\n        assert_image_equal(box.crop((96, 96, 128, 128)), src.crop((0, 0, 32, 32)))\n        assert box.size == (128, 128)\n\n        # source point\n        source = src.copy()\n        source.alpha_composite(over, (32, 32), (32, 32, 96, 96))\n\n        assert_image_equal(source.crop((32, 32, 96, 96)), target.crop((32, 32, 96, 96)))\n        assert source.size == (128, 128)\n\n        # errors\n        with pytest.raises(ValueError):\n            source.alpha_composite(over, \"invalid destination\")  # type: ignore[arg-type]\n        with pytest.raises(ValueError):\n            source.alpha_composite(over, (0, 0), \"invalid source\")  # type: ignore[arg-type]\n        with pytest.raises(ValueError):\n            source.alpha_composite(over, 0)  # type: ignore[arg-type]\n        with pytest.raises(ValueError):\n            source.alpha_composite(over, (0, 0), 0)  # type: ignore[arg-type]\n        with pytest.raises(ValueError):\n            source.alpha_composite(over, (0, 0), (0, -1))\n\n    def test_register_open_duplicates(self) -> None:\n        # Arrange\n        factory, accept = Image.OPEN[\"JPEG\"]\n        id_length = len(Image.ID)\n\n        # Act\n        Image.register_open(\"JPEG\", factory, accept)\n\n        # Assert\n        assert len(Image.ID) == id_length\n\n    def test_registered_extensions_uninitialized(self) -> None:\n        # Arrange\n        Image._initialized = 0\n\n        # Act\n        Image.registered_extensions()\n\n        # Assert\n        assert Image._initialized == 2\n\n    def test_registered_extensions(self) -> None:\n        # Arrange\n        # Open an image to trigger plugin registration\n        with Image.open(\"Tests/images/rgb.jpg\"):\n            pass\n\n        # Act\n        extensions = Image.registered_extensions()\n\n        # Assert\n        assert extensions\n        for ext in [\".cur\", \".icns\", \".tif\", \".tiff\"]:\n            assert ext in extensions\n\n    def test_effect_mandelbrot(self) -> None:\n        # Arrange\n        size = (512, 512)\n        extent = (-3, -2.5, 2, 2.5)\n        quality = 100\n\n        # Act\n        im = Image.effect_mandelbrot(size, extent, quality)\n\n        # Assert\n        assert im.size == (512, 512)\n        assert_image_equal_tofile(im, \"Tests/images/effect_mandelbrot.png\")\n\n    def test_effect_mandelbrot_bad_arguments(self) -> None:\n        # Arrange\n        size = (512, 512)\n        # Get coordinates the wrong way round:\n        extent = (+3, +2.5, -2, -2.5)\n        # Quality < 2:\n        quality = 1\n\n        # Act/Assert\n        with pytest.raises(ValueError):\n            Image.effect_mandelbrot(size, extent, quality)\n\n    def test_effect_noise(self) -> None:\n        # Arrange\n        size = (100, 100)\n        sigma = 128\n\n        # Act\n        im = Image.effect_noise(size, sigma)\n\n        # Assert\n        assert im.size == (100, 100)\n        assert im.mode == \"L\"\n        p0 = im.getpixel((0, 0))\n        p1 = im.getpixel((0, 1))\n        p2 = im.getpixel((0, 2))\n        p3 = im.getpixel((0, 3))\n        p4 = im.getpixel((0, 4))\n        assert_not_all_same([p0, p1, p2, p3, p4])\n\n    def test_effect_spread(self) -> None:\n        # Arrange\n        im = hopper()\n        distance = 10\n\n        # Act\n        im2 = im.effect_spread(distance)\n\n        # Assert\n        assert im.size == (128, 128)\n        assert_image_similar_tofile(im2, \"Tests/images/effect_spread.png\", 110)\n\n    def test_effect_spread_zero(self) -> None:\n        # Arrange\n        im = hopper()\n        distance = 0\n\n        # Act\n        im2 = im.effect_spread(distance)\n\n        # Assert\n        assert_image_equal(im, im2)\n\n    def test_check_size(self) -> None:\n        # Checking that the _check_size function throws value errors when we want it to\n        with pytest.raises(ValueError):\n            # not a tuple\n            Image.new(\"RGB\", 0)  # type: ignore[arg-type]\n        with pytest.raises(ValueError):\n            # tuple too short\n            Image.new(\"RGB\", (0,))  # type: ignore[arg-type]\n        with pytest.raises(ValueError):\n            Image.new(\"RGB\", (-1, -1))  # w,h < 0\n\n        # this should pass with 0 sized images, #2259\n        im = Image.new(\"L\", (0, 0))\n        assert im.size == (0, 0)\n\n        im = Image.new(\"L\", (0, 100))\n        assert im.size == (0, 100)\n\n        im = Image.new(\"L\", (100, 0))\n        assert im.size == (100, 0)\n\n        assert Image.new(\"RGB\", (1, 1))\n        # Should pass lists too\n        i = Image.new(\"RGB\", [1, 1])\n        assert isinstance(i.size, tuple)\n\n    @pytest.mark.timeout(0.75)\n    @pytest.mark.skipif(\n        \"PILLOW_VALGRIND_TEST\" in os.environ, reason=\"Valgrind is slower\"\n    )\n    @pytest.mark.parametrize(\"size\", ((0, 100000000), (100000000, 0)))\n    def test_empty_image(self, size: tuple[int, int]) -> None:\n        Image.new(\"RGB\", size)\n\n    def test_storage_neg(self) -> None:\n        # Storage.c accepted negative values for xsize, ysize.  Was\n        # test_neg_ppm, but the core function for that has been\n        # removed Calling directly into core to test the error in\n        # Storage.c, rather than the size check above\n\n        with pytest.raises(ValueError):\n            Image.core.fill(\"RGB\", (2, -2), (0, 0, 0))\n\n    def test_one_item_tuple(self) -> None:\n        for mode in (\"I\", \"F\", \"L\"):\n            im = Image.new(mode, (100, 100), (5,))\n            px = im.load()\n            assert px[0, 0] == 5\n\n    def test_linear_gradient_wrong_mode(self) -> None:\n        # Arrange\n        wrong_mode = \"RGB\"\n\n        # Act / Assert\n        with pytest.raises(ValueError):\n            Image.linear_gradient(wrong_mode)\n\n    @pytest.mark.parametrize(\"mode\", (\"L\", \"P\", \"I\", \"F\"))\n    def test_linear_gradient(self, mode: str) -> None:\n        # Arrange\n        target_file = \"Tests/images/linear_gradient.png\"\n\n        # Act\n        im = Image.linear_gradient(mode)\n\n        # Assert\n        assert im.size == (256, 256)\n        assert im.mode == mode\n        assert im.getpixel((0, 0)) == 0\n        assert im.getpixel((255, 255)) == 255\n        with Image.open(target_file) as target:\n            target = target.convert(mode)\n        assert_image_equal(im, target)\n\n    def test_radial_gradient_wrong_mode(self) -> None:\n        # Arrange\n        wrong_mode = \"RGB\"\n\n        # Act / Assert\n        with pytest.raises(ValueError):\n            Image.radial_gradient(wrong_mode)\n\n    @pytest.mark.parametrize(\"mode\", (\"L\", \"P\", \"I\", \"F\"))\n    def test_radial_gradient(self, mode: str) -> None:\n        # Arrange\n        target_file = \"Tests/images/radial_gradient.png\"\n\n        # Act\n        im = Image.radial_gradient(mode)\n\n        # Assert\n        assert im.size == (256, 256)\n        assert im.mode == mode\n        assert im.getpixel((0, 0)) == 255\n        assert im.getpixel((128, 128)) == 0\n        with Image.open(target_file) as target:\n            target = target.convert(mode)\n        assert_image_equal(im, target)\n\n    def test_register_extensions(self) -> None:\n        test_format = \"a\"\n        exts = [\"b\", \"c\"]\n        for ext in exts:\n            Image.register_extension(test_format, ext)\n        ext_individual = Image.EXTENSION.copy()\n        for ext in exts:\n            del Image.EXTENSION[ext]\n\n        Image.register_extensions(test_format, exts)\n        ext_multiple = Image.EXTENSION.copy()\n        for ext in exts:\n            del Image.EXTENSION[ext]\n\n        assert ext_individual == ext_multiple\n\n    def test_remap_palette(self) -> None:\n        # Test identity transform\n        with Image.open(\"Tests/images/hopper.gif\") as im:\n            assert_image_equal(im, im.remap_palette(list(range(256))))\n\n        # Test identity transform with an RGBA palette\n        im = Image.new(\"P\", (256, 1))\n        for x in range(256):\n            im.putpixel((x, 0), x)\n        im.putpalette(list(range(256)) * 4, \"RGBA\")\n        im_remapped = im.remap_palette(list(range(256)))\n        assert_image_equal(im, im_remapped)\n        assert im.palette.palette == im_remapped.palette.palette\n\n        # Test illegal image mode\n        with hopper() as im:\n            with pytest.raises(ValueError):\n                im.remap_palette(None)\n\n    def test_remap_palette_transparency(self) -> None:\n        im = Image.new(\"P\", (1, 2), (0, 0, 0))\n        im.putpixel((0, 1), (255, 0, 0))\n        im.info[\"transparency\"] = 0\n\n        im_remapped = im.remap_palette([1, 0])\n        assert im_remapped.info[\"transparency\"] == 1\n        assert len(im_remapped.getpalette()) == 6\n\n        # Test unused transparency\n        im.info[\"transparency\"] = 2\n\n        im_remapped = im.remap_palette([1, 0])\n        assert \"transparency\" not in im_remapped.info\n\n    def test__new(self) -> None:\n        im = hopper(\"RGB\")\n        im_p = hopper(\"P\")\n\n        blank_p = Image.new(\"P\", (10, 10))\n        blank_pa = Image.new(\"PA\", (10, 10))\n        blank_p.palette = None\n        blank_pa.palette = None\n\n        def _make_new(\n            base_image: Image.Image,\n            image: Image.Image,\n            palette_result: ImagePalette.ImagePalette | None = None,\n        ) -> None:\n            new_image = base_image._new(image.im)\n            assert new_image.mode == image.mode\n            assert new_image.size == image.size\n            assert new_image.info == base_image.info\n            if palette_result is not None:\n                assert new_image.palette.tobytes() == palette_result.tobytes()\n            else:\n                assert new_image.palette is None\n\n        _make_new(im, im_p, ImagePalette.ImagePalette(list(range(256)) * 3))\n        _make_new(im_p, im, None)\n        _make_new(im, blank_p, ImagePalette.ImagePalette())\n        _make_new(im, blank_pa, ImagePalette.ImagePalette())\n\n    @pytest.mark.parametrize(\n        \"mode, color\",\n        (\n            (\"RGB\", \"#DDEEFF\"),\n            (\"RGB\", (221, 238, 255)),\n            (\"RGBA\", (221, 238, 255, 255)),\n        ),\n    )\n    def test_p_from_rgb_rgba(self, mode: str, color: str | tuple[int, ...]) -> None:\n        im = Image.new(\"P\", (100, 100), color)\n        expected = Image.new(mode, (100, 100), color)\n        assert_image_equal(im.convert(mode), expected)\n\n    def test_no_resource_warning_on_save(self, tmp_path: Path) -> None:\n        # https://github.com/python-pillow/Pillow/issues/835\n        # Arrange\n        test_file = \"Tests/images/hopper.png\"\n        temp_file = str(tmp_path / \"temp.jpg\")\n\n        # Act/Assert\n        with Image.open(test_file) as im:\n            with warnings.catch_warnings():\n                im.save(temp_file)\n\n    def test_no_new_file_on_error(self, tmp_path: Path) -> None:\n        temp_file = str(tmp_path / \"temp.jpg\")\n\n        im = Image.new(\"RGB\", (0, 0))\n        with pytest.raises(ValueError):\n            im.save(temp_file)\n\n        assert not os.path.exists(temp_file)\n\n    def test_load_on_nonexclusive_multiframe(self) -> None:\n        with open(\"Tests/images/frozenpond.mpo\", \"rb\") as fp:\n\n            def act(fp: IO[bytes]) -> None:\n                im = Image.open(fp)\n                im.load()\n\n            act(fp)\n\n            with Image.open(fp) as im:\n                im.load()\n\n            assert not fp.closed\n\n    def test_empty_exif(self) -> None:\n        with Image.open(\"Tests/images/exif.png\") as im:\n            exif = im.getexif()\n        assert dict(exif)\n\n        # Test that exif data is cleared after another load\n        exif.load(None)\n        assert not dict(exif)\n\n        # Test loading just the EXIF header\n        exif.load(b\"Exif\\x00\\x00\")\n        assert not dict(exif)\n\n    @mark_if_feature_version(\n        pytest.mark.valgrind_known_error, \"libjpeg_turbo\", \"2.0\", reason=\"Known Failing\"\n    )\n    def test_exif_jpeg(self, tmp_path: Path) -> None:\n        with Image.open(\"Tests/images/exif-72dpi-int.jpg\") as im:  # Little endian\n            exif = im.getexif()\n            assert 258 not in exif\n            assert 274 in exif\n            assert 282 in exif\n            assert exif[296] == 2\n            assert exif[11] == \"gThumb 3.0.1\"\n\n            out = str(tmp_path / \"temp.jpg\")\n            exif[258] = 8\n            del exif[274]\n            del exif[282]\n            exif[296] = 455\n            exif[11] = \"Pillow test\"\n            im.save(out, exif=exif)\n        with Image.open(out) as reloaded:\n            reloaded_exif = reloaded.getexif()\n            assert reloaded_exif[258] == 8\n            assert 274 not in reloaded_exif\n            assert 282 not in reloaded_exif\n            assert reloaded_exif[296] == 455\n            assert reloaded_exif[11] == \"Pillow test\"\n\n        with Image.open(\"Tests/images/no-dpi-in-exif.jpg\") as im:  # Big endian\n            exif = im.getexif()\n            assert 258 not in exif\n            assert 306 in exif\n            assert exif[274] == 1\n            assert exif[305] == \"Adobe Photoshop CC 2017 (Macintosh)\"\n\n            out = str(tmp_path / \"temp.jpg\")\n            exif[258] = 8\n            del exif[306]\n            exif[274] = 455\n            exif[305] = \"Pillow test\"\n            im.save(out, exif=exif)\n        with Image.open(out) as reloaded:\n            reloaded_exif = reloaded.getexif()\n            assert reloaded_exif[258] == 8\n            assert 306 not in reloaded_exif\n            assert reloaded_exif[274] == 455\n            assert reloaded_exif[305] == \"Pillow test\"\n\n    @skip_unless_feature(\"webp\")\n    @skip_unless_feature(\"webp_anim\")\n    def test_exif_webp(self, tmp_path: Path) -> None:\n        with Image.open(\"Tests/images/hopper.webp\") as im:\n            exif = im.getexif()\n            assert exif == {}\n\n            out = str(tmp_path / \"temp.webp\")\n            exif[258] = 8\n            exif[40963] = 455\n            exif[305] = \"Pillow test\"\n\n            def check_exif() -> None:\n                with Image.open(out) as reloaded:\n                    reloaded_exif = reloaded.getexif()\n                    assert reloaded_exif[258] == 8\n                    assert reloaded_exif[40963] == 455\n                    assert reloaded_exif[305] == \"Pillow test\"\n\n            im.save(out, exif=exif)\n            check_exif()\n            im.save(out, exif=exif, save_all=True)\n            check_exif()\n\n    def test_exif_png(self, tmp_path: Path) -> None:\n        with Image.open(\"Tests/images/exif.png\") as im:\n            exif = im.getexif()\n            assert exif == {274: 1}\n\n            out = str(tmp_path / \"temp.png\")\n            exif[258] = 8\n            del exif[274]\n            exif[40963] = 455\n            exif[305] = \"Pillow test\"\n            im.save(out, exif=exif)\n\n        with Image.open(out) as reloaded:\n            reloaded_exif = reloaded.getexif()\n            assert reloaded_exif == {258: 8, 40963: 455, 305: \"Pillow test\"}\n\n    def test_exif_interop(self) -> None:\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            exif = im.getexif()\n            assert exif.get_ifd(0xA005) == {\n                1: \"R98\",\n                2: b\"0100\",\n                4097: 2272,\n                4098: 1704,\n            }\n\n            reloaded_exif = Image.Exif()\n            reloaded_exif.load(exif.tobytes())\n            assert reloaded_exif.get_ifd(0xA005) == exif.get_ifd(0xA005)\n\n    def test_exif_ifd1(self) -> None:\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            exif = im.getexif()\n            assert exif.get_ifd(ExifTags.IFD.IFD1) == {\n                513: 2036,\n                514: 5448,\n                259: 6,\n                296: 2,\n                282: 180.0,\n                283: 180.0,\n            }\n\n    def test_exif_ifd(self) -> None:\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            exif = im.getexif()\n        del exif.get_ifd(0x8769)[0xA005]\n\n        reloaded_exif = Image.Exif()\n        reloaded_exif.load(exif.tobytes())\n        assert reloaded_exif.get_ifd(0x8769) == exif.get_ifd(0x8769)\n\n    def test_exif_load_from_fp(self) -> None:\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            data = im.info[\"exif\"]\n            if data.startswith(b\"Exif\\x00\\x00\"):\n                data = data[6:]\n            fp = io.BytesIO(data)\n\n            exif = Image.Exif()\n            exif.load_from_fp(fp)\n            assert exif == {\n                271: \"Canon\",\n                272: \"Canon PowerShot S40\",\n                274: 1,\n                282: 180.0,\n                283: 180.0,\n                296: 2,\n                306: \"2003:12:14 12:01:44\",\n                531: 1,\n                34665: 196,\n            }\n\n    def test_exif_hide_offsets(self) -> None:\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            exif = im.getexif()\n\n        # Check offsets are present initially\n        assert 0x8769 in exif\n        for tag in (0xA005, 0x927C):\n            assert tag in exif.get_ifd(0x8769)\n        assert exif.get_ifd(0xA005)\n        loaded_exif = exif\n\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            new_exif = im.getexif()\n\n            for exif in (loaded_exif, new_exif):\n                exif.hide_offsets()\n\n                # Assert they are hidden afterwards,\n                # but that the IFDs are still available\n                assert 0x8769 not in exif\n                assert exif.get_ifd(0x8769)\n                for tag in (0xA005, 0x927C):\n                    assert tag not in exif.get_ifd(0x8769)\n                assert exif.get_ifd(0xA005)\n\n    def test_empty_xmp(self) -> None:\n        with Image.open(\"Tests/images/hopper.gif\") as im:\n            assert im.getxmp() == {}\n\n    def test_getxmp_padded(self) -> None:\n        im = Image.new(\"RGB\", (1, 1))\n        im.info[\"xmp\"] = (\n            b'<?xpacket begin=\"\\xef\\xbb\\xbf\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\\n'\n            b'<x:xmpmeta xmlns:x=\"adobe:ns:meta/\" />\\n<?xpacket end=\"w\"?>\\x00\\x00'\n        )\n        if ElementTree is None:\n            with pytest.warns(\n                UserWarning,\n                match=\"XMP data cannot be read without defusedxml dependency\",\n            ):\n                assert im.getxmp() == {}\n        else:\n            assert im.getxmp() == {\"xmpmeta\": None}\n\n    @pytest.mark.parametrize(\"size\", ((1, 0), (0, 1), (0, 0)))\n    def test_zero_tobytes(self, size: tuple[int, int]) -> None:\n        im = Image.new(\"RGB\", size)\n        assert im.tobytes() == b\"\"\n\n    @pytest.mark.parametrize(\"size\", ((1, 0), (0, 1), (0, 0)))\n    def test_zero_frombytes(self, size: tuple[int, int]) -> None:\n        Image.frombytes(\"RGB\", size, b\"\")\n\n        im = Image.new(\"RGB\", size)\n        im.frombytes(b\"\")\n\n    def test_has_transparency_data(self) -> None:\n        for mode in (\"1\", \"L\", \"P\", \"RGB\"):\n            im = Image.new(mode, (1, 1))\n            assert not im.has_transparency_data\n\n        for mode in (\"LA\", \"La\", \"PA\", \"RGBA\", \"RGBa\"):\n            im = Image.new(mode, (1, 1))\n            assert im.has_transparency_data\n\n        # P mode with \"transparency\" info\n        with Image.open(\"Tests/images/first_frame_transparency.gif\") as im:\n            assert \"transparency\" in im.info\n            assert im.has_transparency_data\n\n        # RGB mode with \"transparency\" info\n        with Image.open(\"Tests/images/rgb_trns.png\") as im:\n            assert \"transparency\" in im.info\n            assert im.has_transparency_data\n\n        # P mode with RGBA palette\n        im = Image.new(\"RGBA\", (1, 1)).convert(\"P\")\n        assert im.mode == \"P\"\n        assert im.palette.mode == \"RGBA\"\n        assert im.has_transparency_data\n\n    def test_apply_transparency(self) -> None:\n        im = Image.new(\"P\", (1, 1))\n        im.putpalette((0, 0, 0, 1, 1, 1))\n        assert im.palette.colors == {(0, 0, 0): 0, (1, 1, 1): 1}\n\n        # Test that no transformation is applied without transparency\n        im.apply_transparency()\n        assert im.palette.colors == {(0, 0, 0): 0, (1, 1, 1): 1}\n\n        # Test that a transparency index is applied\n        im.info[\"transparency\"] = 0\n        im.apply_transparency()\n        assert \"transparency\" not in im.info\n        assert im.palette.colors == {(0, 0, 0, 0): 0, (1, 1, 1, 255): 1}\n\n        # Test that existing transparency is kept\n        im = Image.new(\"P\", (1, 1))\n        im.putpalette((0, 0, 0, 255, 1, 1, 1, 128), \"RGBA\")\n        im.info[\"transparency\"] = 0\n        im.apply_transparency()\n        assert im.palette.colors == {(0, 0, 0, 0): 0, (1, 1, 1, 128): 1}\n\n        # Test that transparency bytes are applied\n        with Image.open(\"Tests/images/pil123p.png\") as im:\n            assert isinstance(im.info[\"transparency\"], bytes)\n            assert im.palette.colors[(27, 35, 6)] == 24\n            im.apply_transparency()\n            assert im.palette.colors[(27, 35, 6, 214)] == 24\n\n    def test_constants(self) -> None:\n        for enum in (\n            Image.Transpose,\n            Image.Transform,\n            Image.Resampling,\n            Image.Dither,\n            Image.Palette,\n            Image.Quantize,\n        ):\n            for name in enum.__members__:\n                assert getattr(Image, name) == enum[name]\n\n    @pytest.mark.parametrize(\n        \"path\",\n        [\n            \"fli_overrun.bin\",\n            \"sgi_overrun.bin\",\n            \"sgi_overrun_expandrow.bin\",\n            \"sgi_overrun_expandrow2.bin\",\n            \"pcx_overrun.bin\",\n            \"pcx_overrun2.bin\",\n            \"ossfuzz-4836216264589312.pcx\",\n            \"01r_00.pcx\",\n        ],\n    )\n    def test_overrun(self, path: str) -> None:\n        \"\"\"For overrun completeness, test as:\n        valgrind pytest -qq Tests/test_image.py::TestImage::test_overrun | grep decode.c\n        \"\"\"\n        with Image.open(os.path.join(\"Tests/images\", path)) as im:\n            try:\n                im.load()\n                pytest.fail()\n            except OSError as e:\n                buffer_overrun = str(e) == \"buffer overrun when reading image file\"\n                truncated = \"image file is truncated\" in str(e)\n\n                assert buffer_overrun or truncated\n\n    def test_fli_overrun2(self) -> None:\n        with Image.open(\"Tests/images/fli_overrun2.bin\") as im:\n            try:\n                im.seek(1)\n                pytest.fail()\n            except OSError as e:\n                assert str(e) == \"buffer overrun when reading image file\"\n\n    def test_exit_fp(self) -> None:\n        with Image.new(\"L\", (1, 1)) as im:\n            pass\n        assert not hasattr(im, \"fp\")\n\n    def test_close_graceful(self, caplog: pytest.LogCaptureFixture) -> None:\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            copy = im.copy()\n            with caplog.at_level(logging.DEBUG):\n                im.close()\n                copy.close()\n            assert len(caplog.records) == 0\n            assert im.fp is None\n\n\nclass TestImageBytes:\n    @pytest.mark.parametrize(\"mode\", Image.MODES + [\"BGR;15\", \"BGR;16\", \"BGR;24\"])\n    def test_roundtrip_bytes_constructor(self, mode: str) -> None:\n        im = hopper(mode)\n        source_bytes = im.tobytes()\n\n        if mode.startswith(\"BGR;\"):\n            with pytest.warns(DeprecationWarning):\n                reloaded = Image.frombytes(mode, im.size, source_bytes)\n        else:\n            reloaded = Image.frombytes(mode, im.size, source_bytes)\n        assert reloaded.tobytes() == source_bytes\n\n    @pytest.mark.parametrize(\"mode\", Image.MODES + [\"BGR;15\", \"BGR;16\", \"BGR;24\"])\n    def test_roundtrip_bytes_method(self, mode: str) -> None:\n        im = hopper(mode)\n        source_bytes = im.tobytes()\n\n        reloaded = helper_image_new(mode, im.size)\n        reloaded.frombytes(source_bytes)\n        assert reloaded.tobytes() == source_bytes\n\n    @pytest.mark.parametrize(\"mode\", Image.MODES + [\"BGR;15\", \"BGR;16\", \"BGR;24\"])\n    def test_getdata_putdata(self, mode: str) -> None:\n        if is_big_endian() and mode == \"BGR;15\":\n            pytest.xfail(\"Known failure of BGR;15 on big-endian\")\n        im = hopper(mode)\n        reloaded = helper_image_new(mode, im.size)\n        reloaded.putdata(im.getdata())\n        assert_image_equal(im, reloaded)\n\n\nclass MockEncoder(ImageFile.PyEncoder):\n    pass\n\n\nclass TestRegistry:\n    def test_encode_registry(self) -> None:\n        Image.register_encoder(\"MOCK\", MockEncoder)\n        assert \"MOCK\" in Image.ENCODERS\n\n        enc = Image._getencoder(\"RGB\", \"MOCK\", (\"args\",), extra=(\"extra\",))\n\n        assert isinstance(enc, MockEncoder)\n        assert enc.mode == \"RGB\"\n        assert enc.args == (\"args\", \"extra\")\n\n    def test_encode_registry_fail(self) -> None:\n        with pytest.raises(OSError):\n            Image._getencoder(\"RGB\", \"DoesNotExist\", (\"args\",), extra=(\"extra\",))\n",
            "new_file_content": "from __future__ import annotations\n\nimport io\nimport logging\nimport os\nimport shutil\nimport sys\nimport tempfile\nimport warnings\nfrom pathlib import Path\nfrom types import ModuleType\nfrom typing import IO, Any\n\nimport pytest\n\nfrom PIL import (\n    ExifTags,\n    Image,\n    ImageDraw,\n    ImageFile,\n    ImagePalette,\n    UnidentifiedImageError,\n    features,\n)\n\nfrom .helper import (\n    assert_image_equal,\n    assert_image_equal_tofile,\n    assert_image_similar,\n    assert_image_similar_tofile,\n    assert_not_all_same,\n    hopper,\n    is_big_endian,\n    is_win32,\n    mark_if_feature_version,\n    skip_unless_feature,\n)\n\nElementTree: ModuleType | None\ntry:\n    from defusedxml import ElementTree\nexcept ImportError:\n    ElementTree = None\n\n\n# Deprecation helper\ndef helper_image_new(mode: str, size: tuple[int, int]) -> Image.Image:\n    if mode.startswith(\"BGR;\"):\n        with pytest.warns(DeprecationWarning):\n            return Image.new(mode, size)\n    else:\n        return Image.new(mode, size)\n\n\nclass TestImage:\n    @pytest.mark.parametrize(\"mode\", Image.MODES + [\"BGR;15\", \"BGR;16\", \"BGR;24\"])\n    def test_image_modes_success(self, mode: str) -> None:\n        helper_image_new(mode, (1, 1))\n\n    @pytest.mark.parametrize(\"mode\", (\"\", \"bad\", \"very very long\"))\n    def test_image_modes_fail(self, mode: str) -> None:\n        with pytest.raises(ValueError) as e:\n            Image.new(mode, (1, 1))\n        assert str(e.value) == \"unrecognized image mode\"\n\n    def test_exception_inheritance(self) -> None:\n        assert issubclass(UnidentifiedImageError, OSError)\n\n    def test_sanity(self) -> None:\n        im = Image.new(\"L\", (100, 100))\n        assert repr(im)[:45] == \"<PIL.Image.Image image mode=L size=100x100 at\"\n        assert im.mode == \"L\"\n        assert im.size == (100, 100)\n\n        im = Image.new(\"RGB\", (100, 100))\n        assert repr(im)[:45] == \"<PIL.Image.Image image mode=RGB size=100x100 \"\n        assert im.mode == \"RGB\"\n        assert im.size == (100, 100)\n\n        Image.new(\"L\", (100, 100), None)\n        im2 = Image.new(\"L\", (100, 100), 0)\n        im3 = Image.new(\"L\", (100, 100), \"black\")\n\n        assert im2.getcolors() == [(10000, 0)]\n        assert im3.getcolors() == [(10000, 0)]\n\n        with pytest.raises(ValueError):\n            Image.new(\"X\", (100, 100))\n        with pytest.raises(ValueError):\n            Image.new(\"\", (100, 100))\n        # with pytest.raises(MemoryError):\n        #   Image.new(\"L\", (1000000, 1000000))\n\n    def test_repr_pretty(self) -> None:\n        class Pretty:\n            def text(self, text: str) -> None:\n                self.pretty_output = text\n\n        im = Image.new(\"L\", (100, 100))\n\n        p = Pretty()\n        im._repr_pretty_(p, None)\n        assert p.pretty_output == \"<PIL.Image.Image image mode=L size=100x100>\"\n\n    def test_open_formats(self) -> None:\n        PNGFILE = \"Tests/images/hopper.png\"\n        JPGFILE = \"Tests/images/hopper.jpg\"\n\n        with pytest.raises(TypeError):\n            with Image.open(PNGFILE, formats=123):  # type: ignore[arg-type]\n                pass\n\n        format_list: list[list[str] | tuple[str, ...]] = [\n            [\"JPEG\"],\n            (\"JPEG\",),\n            [\"jpeg\"],\n            [\"Jpeg\"],\n            [\"jPeG\"],\n            [\"JpEg\"],\n        ]\n        for formats in format_list:\n            with pytest.raises(UnidentifiedImageError):\n                with Image.open(PNGFILE, formats=formats):\n                    pass\n\n            with Image.open(JPGFILE, formats=formats) as im:\n                assert im.mode == \"RGB\"\n                assert im.size == (128, 128)\n\n        for file in [PNGFILE, JPGFILE]:\n            with Image.open(file, formats=None) as im:\n                assert im.mode == \"RGB\"\n                assert im.size == (128, 128)\n\n    def test_open_verbose_failure(self, monkeypatch: pytest.MonkeyPatch) -> None:\n        monkeypatch.setattr(Image, \"WARN_POSSIBLE_FORMATS\", True)\n\n        im = io.BytesIO(b\"\")\n        with pytest.warns(UserWarning):\n            with pytest.raises(UnidentifiedImageError):\n                with Image.open(im):\n                    pass\n\n    def test_width_height(self) -> None:\n        im = Image.new(\"RGB\", (1, 2))\n        assert im.width == 1\n        assert im.height == 2\n\n        with pytest.raises(AttributeError):\n            im.size = (3, 4)  # type: ignore[misc]\n\n    def test_set_mode(self) -> None:\n        im = Image.new(\"RGB\", (1, 1))\n\n        with pytest.raises(AttributeError):\n            im.mode = \"P\"  # type: ignore[misc]\n\n    def test_invalid_image(self) -> None:\n        im = io.BytesIO(b\"\")\n        with pytest.raises(UnidentifiedImageError):\n            with Image.open(im):\n                pass\n\n    def test_bad_mode(self) -> None:\n        with pytest.raises(ValueError):\n            with Image.open(\"filename\", \"bad mode\"):  # type: ignore[arg-type]\n                pass\n\n    def test_stringio(self) -> None:\n        with pytest.raises(ValueError):\n            with Image.open(io.StringIO()):  # type: ignore[arg-type]\n                pass\n\n    def test_pathlib(self, tmp_path: Path) -> None:\n        with Image.open(Path(\"Tests/images/multipage-mmap.tiff\")) as im:\n            assert im.mode == \"P\"\n            assert im.size == (10, 10)\n\n        with Image.open(Path(\"Tests/images/hopper.jpg\")) as im:\n            assert im.mode == \"RGB\"\n            assert im.size == (128, 128)\n\n            for ext in (\".jpg\", \".jp2\"):\n                if ext == \".jp2\" and not features.check_codec(\"jpg_2000\"):\n                    pytest.skip(\"jpg_2000 not available\")\n                temp_file = str(tmp_path / (\"temp.\" + ext))\n                if os.path.exists(temp_file):\n                    os.remove(temp_file)\n                im.save(Path(temp_file))\n\n    def test_fp_name(self, tmp_path: Path) -> None:\n        temp_file = str(tmp_path / \"temp.jpg\")\n\n        class FP(io.BytesIO):\n            name: str\n\n            if sys.version_info >= (3, 12):\n                from collections.abc import Buffer\n\n                def write(self, data: Buffer) -> int:\n                    return len(data)\n\n            else:\n\n                def write(self, data: Any) -> int:\n                    return len(data)\n\n        fp = FP()\n        fp.name = temp_file\n\n        im = hopper()\n        im.save(fp)\n\n    def test_tempfile(self) -> None:\n        # see #1460, pathlib support breaks tempfile.TemporaryFile on py27\n        # Will error out on save on 3.0.0\n        im = hopper()\n        with tempfile.TemporaryFile() as fp:\n            im.save(fp, \"JPEG\")\n            fp.seek(0)\n            with Image.open(fp) as reloaded:\n                assert_image_similar(im, reloaded, 20)\n\n    def test_unknown_extension(self, tmp_path: Path) -> None:\n        im = hopper()\n        temp_file = str(tmp_path / \"temp.unknown\")\n        with pytest.raises(ValueError):\n            im.save(temp_file)\n\n    def test_internals(self) -> None:\n        im = Image.new(\"L\", (100, 100))\n        im.readonly = 1\n        im._copy()\n        assert not im.readonly\n\n        im.readonly = 1\n        im.paste(0, (0, 0, 100, 100))\n        assert not im.readonly\n\n    @pytest.mark.skipif(is_win32(), reason=\"Test requires opening tempfile twice\")\n    @pytest.mark.skipif(\n        sys.platform == \"cygwin\",\n        reason=\"Test requires opening an mmaped file for writing\",\n    )\n    def test_readonly_save(self, tmp_path: Path) -> None:\n        temp_file = str(tmp_path / \"temp.bmp\")\n        shutil.copy(\"Tests/images/rgb32bf-rgba.bmp\", temp_file)\n\n        with Image.open(temp_file) as im:\n            assert im.readonly\n            im.save(temp_file)\n\n    def test_dump(self, tmp_path: Path) -> None:\n        im = Image.new(\"L\", (10, 10))\n        im._dump(str(tmp_path / \"temp_L.ppm\"))\n\n        im = Image.new(\"RGB\", (10, 10))\n        im._dump(str(tmp_path / \"temp_RGB.ppm\"))\n\n        im = Image.new(\"HSV\", (10, 10))\n        with pytest.raises(ValueError):\n            im._dump(str(tmp_path / \"temp_HSV.ppm\"))\n\n    def test_comparison_with_other_type(self) -> None:\n        # Arrange\n        item = Image.new(\"RGB\", (25, 25), \"#000\")\n        num = 12\n\n        # Act/Assert\n        # Shouldn't cause AttributeError (#774)\n        assert item is not None\n        assert item != num\n\n    def test_expand_x(self) -> None:\n        # Arrange\n        im = hopper()\n        orig_size = im.size\n        xmargin = 5\n\n        # Act\n        im = im._expand(xmargin)\n\n        # Assert\n        assert im.size[0] == orig_size[0] + 2 * xmargin\n        assert im.size[1] == orig_size[1] + 2 * xmargin\n\n    def test_expand_xy(self) -> None:\n        # Arrange\n        im = hopper()\n        orig_size = im.size\n        xmargin = 5\n        ymargin = 3\n\n        # Act\n        im = im._expand(xmargin, ymargin)\n\n        # Assert\n        assert im.size[0] == orig_size[0] + 2 * xmargin\n        assert im.size[1] == orig_size[1] + 2 * ymargin\n\n    def test_getbands(self) -> None:\n        # Assert\n        assert hopper(\"RGB\").getbands() == (\"R\", \"G\", \"B\")\n        assert hopper(\"YCbCr\").getbands() == (\"Y\", \"Cb\", \"Cr\")\n\n    def test_getchannel_wrong_params(self) -> None:\n        im = hopper()\n\n        with pytest.raises(ValueError):\n            im.getchannel(-1)\n        with pytest.raises(ValueError):\n            im.getchannel(3)\n        with pytest.raises(ValueError):\n            im.getchannel(\"Z\")\n        with pytest.raises(ValueError):\n            im.getchannel(\"1\")\n\n    def test_getchannel(self) -> None:\n        im = hopper(\"YCbCr\")\n        Y, Cb, Cr = im.split()\n\n        assert_image_equal(Y, im.getchannel(0))\n        assert_image_equal(Y, im.getchannel(\"Y\"))\n        assert_image_equal(Cb, im.getchannel(1))\n        assert_image_equal(Cb, im.getchannel(\"Cb\"))\n        assert_image_equal(Cr, im.getchannel(2))\n        assert_image_equal(Cr, im.getchannel(\"Cr\"))\n\n    def test_getbbox(self) -> None:\n        # Arrange\n        im = hopper()\n\n        # Act\n        bbox = im.getbbox()\n\n        # Assert\n        assert bbox == (0, 0, 128, 128)\n\n    def test_ne(self) -> None:\n        # Arrange\n        im1 = Image.new(\"RGB\", (25, 25), \"black\")\n        im2 = Image.new(\"RGB\", (25, 25), \"white\")\n\n        # Act / Assert\n        assert im1 != im2\n\n    def test_alpha_composite(self) -> None:\n        # https://stackoverflow.com/questions/3374878\n        # Arrange\n        expected_colors = sorted(\n            [\n                (1122, (128, 127, 0, 255)),\n                (1089, (0, 255, 0, 255)),\n                (3300, (255, 0, 0, 255)),\n                (1156, (170, 85, 0, 192)),\n                (1122, (0, 255, 0, 128)),\n                (1122, (255, 0, 0, 128)),\n                (1089, (0, 255, 0, 0)),\n            ]\n        )\n\n        dst = Image.new(\"RGBA\", size=(100, 100), color=(0, 255, 0, 255))\n        draw = ImageDraw.Draw(dst)\n        draw.rectangle((0, 33, 100, 66), fill=(0, 255, 0, 128))\n        draw.rectangle((0, 67, 100, 100), fill=(0, 255, 0, 0))\n        src = Image.new(\"RGBA\", size=(100, 100), color=(255, 0, 0, 255))\n        draw = ImageDraw.Draw(src)\n        draw.rectangle((33, 0, 66, 100), fill=(255, 0, 0, 128))\n        draw.rectangle((67, 0, 100, 100), fill=(255, 0, 0, 0))\n\n        # Act\n        img = Image.alpha_composite(dst, src)\n\n        # Assert\n        img_colors = sorted(img.getcolors())\n        assert img_colors == expected_colors\n\n    def test_alpha_inplace(self) -> None:\n        src = Image.new(\"RGBA\", (128, 128), \"blue\")\n\n        over = Image.new(\"RGBA\", (128, 128), \"red\")\n        mask = hopper(\"L\")\n        over.putalpha(mask)\n\n        target = Image.alpha_composite(src, over)\n\n        # basic\n        full = src.copy()\n        full.alpha_composite(over)\n        assert_image_equal(full, target)\n\n        # with offset down to right\n        offset = src.copy()\n        offset.alpha_composite(over, (64, 64))\n        assert_image_equal(offset.crop((64, 64, 127, 127)), target.crop((0, 0, 63, 63)))\n        assert offset.size == (128, 128)\n\n        # with negative offset\n        offset = src.copy()\n        offset.alpha_composite(over, (-64, -64))\n        assert_image_equal(offset.crop((0, 0, 63, 63)), target.crop((64, 64, 127, 127)))\n        assert offset.size == (128, 128)\n\n        # offset and crop\n        box = src.copy()\n        box.alpha_composite(over, (64, 64), (0, 0, 32, 32))\n        assert_image_equal(box.crop((64, 64, 96, 96)), target.crop((0, 0, 32, 32)))\n        assert_image_equal(box.crop((96, 96, 128, 128)), src.crop((0, 0, 32, 32)))\n        assert box.size == (128, 128)\n\n        # source point\n        source = src.copy()\n        source.alpha_composite(over, (32, 32), (32, 32, 96, 96))\n\n        assert_image_equal(source.crop((32, 32, 96, 96)), target.crop((32, 32, 96, 96)))\n        assert source.size == (128, 128)\n\n        # errors\n        with pytest.raises(ValueError):\n            source.alpha_composite(over, \"invalid destination\")  # type: ignore[arg-type]\n        with pytest.raises(ValueError):\n            source.alpha_composite(over, (0, 0), \"invalid source\")  # type: ignore[arg-type]\n        with pytest.raises(ValueError):\n            source.alpha_composite(over, 0)  # type: ignore[arg-type]\n        with pytest.raises(ValueError):\n            source.alpha_composite(over, (0, 0), 0)  # type: ignore[arg-type]\n        with pytest.raises(ValueError):\n            source.alpha_composite(over, (0, 0), (0, -1))\n\n    def test_register_open_duplicates(self) -> None:\n        # Arrange\n        factory, accept = Image.OPEN[\"JPEG\"]\n        id_length = len(Image.ID)\n\n        # Act\n        Image.register_open(\"JPEG\", factory, accept)\n\n        # Assert\n        assert len(Image.ID) == id_length\n\n    def test_registered_extensions_uninitialized(self) -> None:\n        # Arrange\n        Image._initialized = 0\n\n        # Act\n        Image.registered_extensions()\n\n        # Assert\n        assert Image._initialized == 2\n\n    def test_registered_extensions(self) -> None:\n        # Arrange\n        # Open an image to trigger plugin registration\n        with Image.open(\"Tests/images/rgb.jpg\"):\n            pass\n\n        # Act\n        extensions = Image.registered_extensions()\n\n        # Assert\n        assert extensions\n        for ext in [\".cur\", \".icns\", \".tif\", \".tiff\"]:\n            assert ext in extensions\n\n    def test_effect_mandelbrot(self) -> None:\n        # Arrange\n        size = (512, 512)\n        extent = (-3, -2.5, 2, 2.5)\n        quality = 100\n\n        # Act\n        im = Image.effect_mandelbrot(size, extent, quality)\n\n        # Assert\n        assert im.size == (512, 512)\n        assert_image_equal_tofile(im, \"Tests/images/effect_mandelbrot.png\")\n\n    def test_effect_mandelbrot_bad_arguments(self) -> None:\n        # Arrange\n        size = (512, 512)\n        # Get coordinates the wrong way round:\n        extent = (+3, +2.5, -2, -2.5)\n        # Quality < 2:\n        quality = 1\n\n        # Act/Assert\n        with pytest.raises(ValueError):\n            Image.effect_mandelbrot(size, extent, quality)\n\n    def test_effect_noise(self) -> None:\n        # Arrange\n        size = (100, 100)\n        sigma = 128\n\n        # Act\n        im = Image.effect_noise(size, sigma)\n\n        # Assert\n        assert im.size == (100, 100)\n        assert im.mode == \"L\"\n        p0 = im.getpixel((0, 0))\n        p1 = im.getpixel((0, 1))\n        p2 = im.getpixel((0, 2))\n        p3 = im.getpixel((0, 3))\n        p4 = im.getpixel((0, 4))\n        assert_not_all_same([p0, p1, p2, p3, p4])\n\n    def test_effect_spread(self) -> None:\n        # Arrange\n        im = hopper()\n        distance = 10\n\n        # Act\n        im2 = im.effect_spread(distance)\n\n        # Assert\n        assert im.size == (128, 128)\n        assert_image_similar_tofile(im2, \"Tests/images/effect_spread.png\", 110)\n\n    def test_effect_spread_zero(self) -> None:\n        # Arrange\n        im = hopper()\n        distance = 0\n\n        # Act\n        im2 = im.effect_spread(distance)\n\n        # Assert\n        assert_image_equal(im, im2)\n\n    def test_check_size(self) -> None:\n        # Checking that the _check_size function throws value errors when we want it to\n        with pytest.raises(ValueError):\n            # not a tuple\n            Image.new(\"RGB\", 0)  # type: ignore[arg-type]\n        with pytest.raises(ValueError):\n            # tuple too short\n            Image.new(\"RGB\", (0,))  # type: ignore[arg-type]\n        with pytest.raises(ValueError):\n            Image.new(\"RGB\", (-1, -1))  # w,h < 0\n\n        # this should pass with 0 sized images, #2259\n        im = Image.new(\"L\", (0, 0))\n        assert im.size == (0, 0)\n\n        im = Image.new(\"L\", (0, 100))\n        assert im.size == (0, 100)\n\n        im = Image.new(\"L\", (100, 0))\n        assert im.size == (100, 0)\n\n        assert Image.new(\"RGB\", (1, 1))\n        # Should pass lists too\n        i = Image.new(\"RGB\", [1, 1])\n        assert isinstance(i.size, tuple)\n\n    @pytest.mark.timeout(0.75)\n    @pytest.mark.skipif(\n        \"PILLOW_VALGRIND_TEST\" in os.environ, reason=\"Valgrind is slower\"\n    )\n    @pytest.mark.parametrize(\"size\", ((0, 100000000), (100000000, 0)))\n    def test_empty_image(self, size: tuple[int, int]) -> None:\n        Image.new(\"RGB\", size)\n\n    def test_storage_neg(self) -> None:\n        # Storage.c accepted negative values for xsize, ysize.  Was\n        # test_neg_ppm, but the core function for that has been\n        # removed Calling directly into core to test the error in\n        # Storage.c, rather than the size check above\n\n        with pytest.raises(ValueError):\n            Image.core.fill(\"RGB\", (2, -2), (0, 0, 0))\n\n    def test_one_item_tuple(self) -> None:\n        for mode in (\"I\", \"F\", \"L\"):\n            im = Image.new(mode, (100, 100), (5,))\n            px = im.load()\n            assert px[0, 0] == 5\n\n    def test_linear_gradient_wrong_mode(self) -> None:\n        # Arrange\n        wrong_mode = \"RGB\"\n\n        # Act / Assert\n        with pytest.raises(ValueError):\n            Image.linear_gradient(wrong_mode)\n\n    @pytest.mark.parametrize(\"mode\", (\"L\", \"P\", \"I\", \"F\"))\n    def test_linear_gradient(self, mode: str) -> None:\n        # Arrange\n        target_file = \"Tests/images/linear_gradient.png\"\n\n        # Act\n        im = Image.linear_gradient(mode)\n\n        # Assert\n        assert im.size == (256, 256)\n        assert im.mode == mode\n        assert im.getpixel((0, 0)) == 0\n        assert im.getpixel((255, 255)) == 255\n        with Image.open(target_file) as target:\n            target = target.convert(mode)\n        assert_image_equal(im, target)\n\n    def test_radial_gradient_wrong_mode(self) -> None:\n        # Arrange\n        wrong_mode = \"RGB\"\n\n        # Act / Assert\n        with pytest.raises(ValueError):\n            Image.radial_gradient(wrong_mode)\n\n    @pytest.mark.parametrize(\"mode\", (\"L\", \"P\", \"I\", \"F\"))\n    def test_radial_gradient(self, mode: str) -> None:\n        # Arrange\n        target_file = \"Tests/images/radial_gradient.png\"\n\n        # Act\n        im = Image.radial_gradient(mode)\n\n        # Assert\n        assert im.size == (256, 256)\n        assert im.mode == mode\n        assert im.getpixel((0, 0)) == 255\n        assert im.getpixel((128, 128)) == 0\n        with Image.open(target_file) as target:\n            target = target.convert(mode)\n        assert_image_equal(im, target)\n\n    def test_register_extensions(self) -> None:\n        test_format = \"a\"\n        exts = [\"b\", \"c\"]\n        for ext in exts:\n            Image.register_extension(test_format, ext)\n        ext_individual = Image.EXTENSION.copy()\n        for ext in exts:\n            del Image.EXTENSION[ext]\n\n        Image.register_extensions(test_format, exts)\n        ext_multiple = Image.EXTENSION.copy()\n        for ext in exts:\n            del Image.EXTENSION[ext]\n\n        assert ext_individual == ext_multiple\n\n    def test_remap_palette(self) -> None:\n        # Test identity transform\n        with Image.open(\"Tests/images/hopper.gif\") as im:\n            assert_image_equal(im, im.remap_palette(list(range(256))))\n\n        # Test identity transform with an RGBA palette\n        im = Image.new(\"P\", (256, 1))\n        for x in range(256):\n            im.putpixel((x, 0), x)\n        im.putpalette(list(range(256)) * 4, \"RGBA\")\n        im_remapped = im.remap_palette(list(range(256)))\n        assert_image_equal(im, im_remapped)\n        assert im.palette.palette == im_remapped.palette.palette\n\n        # Test illegal image mode\n        with hopper() as im:\n            with pytest.raises(ValueError):\n                im.remap_palette(None)\n\n    def test_remap_palette_transparency(self) -> None:\n        im = Image.new(\"P\", (1, 2), (0, 0, 0))\n        im.putpixel((0, 1), (255, 0, 0))\n        im.info[\"transparency\"] = 0\n\n        im_remapped = im.remap_palette([1, 0])\n        assert im_remapped.info[\"transparency\"] == 1\n        assert len(im_remapped.getpalette()) == 6\n\n        # Test unused transparency\n        im.info[\"transparency\"] = 2\n\n        im_remapped = im.remap_palette([1, 0])\n        assert \"transparency\" not in im_remapped.info\n\n    def test__new(self) -> None:\n        im = hopper(\"RGB\")\n        im_p = hopper(\"P\")\n\n        blank_p = Image.new(\"P\", (10, 10))\n        blank_pa = Image.new(\"PA\", (10, 10))\n        blank_p.palette = None\n        blank_pa.palette = None\n\n        def _make_new(\n            base_image: Image.Image,\n            image: Image.Image,\n            palette_result: ImagePalette.ImagePalette | None = None,\n        ) -> None:\n            new_image = base_image._new(image.im)\n            assert new_image.mode == image.mode\n            assert new_image.size == image.size\n            assert new_image.info == base_image.info\n            if palette_result is not None:\n                assert new_image.palette.tobytes() == palette_result.tobytes()\n            else:\n                assert new_image.palette is None\n\n        _make_new(im, im_p, ImagePalette.ImagePalette(list(range(256)) * 3))\n        _make_new(im_p, im, None)\n        _make_new(im, blank_p, ImagePalette.ImagePalette())\n        _make_new(im, blank_pa, ImagePalette.ImagePalette())\n\n    @pytest.mark.parametrize(\n        \"mode, color\",\n        (\n            (\"RGB\", \"#DDEEFF\"),\n            (\"RGB\", (221, 238, 255)),\n            (\"RGBA\", (221, 238, 255, 255)),\n        ),\n    )\n    def test_p_from_rgb_rgba(self, mode: str, color: str | tuple[int, ...]) -> None:\n        im = Image.new(\"P\", (100, 100), color)\n        expected = Image.new(mode, (100, 100), color)\n        assert_image_equal(im.convert(mode), expected)\n\n    def test_no_resource_warning_on_save(self, tmp_path: Path) -> None:\n        # https://github.com/python-pillow/Pillow/issues/835\n        # Arrange\n        test_file = \"Tests/images/hopper.png\"\n        temp_file = str(tmp_path / \"temp.jpg\")\n\n        # Act/Assert\n        with Image.open(test_file) as im:\n            with warnings.catch_warnings():\n                im.save(temp_file)\n\n    def test_no_new_file_on_error(self, tmp_path: Path) -> None:\n        temp_file = str(tmp_path / \"temp.jpg\")\n\n        im = Image.new(\"RGB\", (0, 0))\n        with pytest.raises(ValueError):\n            im.save(temp_file)\n\n        assert not os.path.exists(temp_file)\n\n    def test_load_on_nonexclusive_multiframe(self) -> None:\n        with open(\"Tests/images/frozenpond.mpo\", \"rb\") as fp:\n\n            def act(fp: IO[bytes]) -> None:\n                im = Image.open(fp)\n                im.load()\n\n            act(fp)\n\n            with Image.open(fp) as im:\n                im.load()\n\n            assert not fp.closed\n\n    def test_empty_exif(self) -> None:\n        with Image.open(\"Tests/images/exif.png\") as im:\n            exif = im.getexif()\n        assert dict(exif)\n\n        # Test that exif data is cleared after another load\n        exif.load(None)\n        assert not dict(exif)\n\n        # Test loading just the EXIF header\n        exif.load(b\"Exif\\x00\\x00\")\n        assert not dict(exif)\n\n    @mark_if_feature_version(\n        pytest.mark.valgrind_known_error, \"libjpeg_turbo\", \"2.0\", reason=\"Known Failing\"\n    )\n    def test_exif_jpeg(self, tmp_path: Path) -> None:\n        with Image.open(\"Tests/images/exif-72dpi-int.jpg\") as im:  # Little endian\n            exif = im.getexif()\n            assert 258 not in exif\n            assert 274 in exif\n            assert 282 in exif\n            assert exif[296] == 2\n            assert exif[11] == \"gThumb 3.0.1\"\n\n            out = str(tmp_path / \"temp.jpg\")\n            exif[258] = 8\n            del exif[274]\n            del exif[282]\n            exif[296] = 455\n            exif[11] = \"Pillow test\"\n            im.save(out, exif=exif)\n        with Image.open(out) as reloaded:\n            reloaded_exif = reloaded.getexif()\n            assert reloaded_exif[258] == 8\n            assert 274 not in reloaded_exif\n            assert 282 not in reloaded_exif\n            assert reloaded_exif[296] == 455\n            assert reloaded_exif[11] == \"Pillow test\"\n\n        with Image.open(\"Tests/images/no-dpi-in-exif.jpg\") as im:  # Big endian\n            exif = im.getexif()\n            assert 258 not in exif\n            assert 306 in exif\n            assert exif[274] == 1\n            assert exif[305] == \"Adobe Photoshop CC 2017 (Macintosh)\"\n\n            out = str(tmp_path / \"temp.jpg\")\n            exif[258] = 8\n            del exif[306]\n            exif[274] = 455\n            exif[305] = \"Pillow test\"\n            im.save(out, exif=exif)\n        with Image.open(out) as reloaded:\n            reloaded_exif = reloaded.getexif()\n            assert reloaded_exif[258] == 8\n            assert 306 not in reloaded_exif\n            assert reloaded_exif[274] == 455\n            assert reloaded_exif[305] == \"Pillow test\"\n\n    @skip_unless_feature(\"webp\")\n    @skip_unless_feature(\"webp_anim\")\n    def test_exif_webp(self, tmp_path: Path) -> None:\n        with Image.open(\"Tests/images/hopper.webp\") as im:\n            exif = im.getexif()\n            assert exif == {}\n\n            out = str(tmp_path / \"temp.webp\")\n            exif[258] = 8\n            exif[40963] = 455\n            exif[305] = \"Pillow test\"\n\n            def check_exif() -> None:\n                with Image.open(out) as reloaded:\n                    reloaded_exif = reloaded.getexif()\n                    assert reloaded_exif[258] == 8\n                    assert reloaded_exif[40963] == 455\n                    assert reloaded_exif[305] == \"Pillow test\"\n\n            im.save(out, exif=exif)\n            check_exif()\n            im.save(out, exif=exif, save_all=True)\n            check_exif()\n\n    def test_exif_png(self, tmp_path: Path) -> None:\n        with Image.open(\"Tests/images/exif.png\") as im:\n            exif = im.getexif()\n            assert exif == {274: 1}\n\n            out = str(tmp_path / \"temp.png\")\n            exif[258] = 8\n            del exif[274]\n            exif[40963] = 455\n            exif[305] = \"Pillow test\"\n            im.save(out, exif=exif)\n\n        with Image.open(out) as reloaded:\n            reloaded_exif = reloaded.getexif()\n            assert reloaded_exif == {258: 8, 40963: 455, 305: \"Pillow test\"}\n\n    def test_exif_interop(self) -> None:\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            exif = im.getexif()\n            assert exif.get_ifd(0xA005) == {\n                1: \"R98\",\n                2: b\"0100\",\n                4097: 2272,\n                4098: 1704,\n            }\n\n            reloaded_exif = Image.Exif()\n            reloaded_exif.load(exif.tobytes())\n            assert reloaded_exif.get_ifd(0xA005) == exif.get_ifd(0xA005)\n\n    def test_exif_ifd1(self) -> None:\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            exif = im.getexif()\n            assert exif.get_ifd(ExifTags.IFD.IFD1) == {\n                513: 2036,\n                514: 5448,\n                259: 6,\n                296: 2,\n                282: 180.0,\n                283: 180.0,\n            }\n\n    def test_exif_ifd(self) -> None:\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            exif = im.getexif()\n        del exif.get_ifd(0x8769)[0xA005]\n\n        reloaded_exif = Image.Exif()\n        reloaded_exif.load(exif.tobytes())\n        assert reloaded_exif.get_ifd(0x8769) == exif.get_ifd(0x8769)\n\n    def test_exif_load_from_fp(self) -> None:\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            data = im.info[\"exif\"]\n            if data.startswith(b\"Exif\\x00\\x00\"):\n                data = data[6:]\n            fp = io.BytesIO(data)\n\n            exif = Image.Exif()\n            exif.load_from_fp(fp)\n            assert exif == {\n                271: \"Canon\",\n                272: \"Canon PowerShot S40\",\n                274: 1,\n                282: 180.0,\n                283: 180.0,\n                296: 2,\n                306: \"2003:12:14 12:01:44\",\n                531: 1,\n                34665: 196,\n            }\n\n    def test_exif_hide_offsets(self) -> None:\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            exif = im.getexif()\n\n        # Check offsets are present initially\n        assert 0x8769 in exif\n        for tag in (0xA005, 0x927C):\n            assert tag in exif.get_ifd(0x8769)\n        assert exif.get_ifd(0xA005)\n        loaded_exif = exif\n\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            new_exif = im.getexif()\n\n            for exif in (loaded_exif, new_exif):\n                exif.hide_offsets()\n\n                # Assert they are hidden afterwards,\n                # but that the IFDs are still available\n                assert 0x8769 not in exif\n                assert exif.get_ifd(0x8769)\n                for tag in (0xA005, 0x927C):\n                    assert tag not in exif.get_ifd(0x8769)\n                assert exif.get_ifd(0xA005)\n\n    def test_empty_xmp(self) -> None:\n        with Image.open(\"Tests/images/hopper.gif\") as im:\n            assert im.getxmp() == {}\n\n    def test_getxmp_padded(self) -> None:\n        im = Image.new(\"RGB\", (1, 1))\n        im.info[\"xmp\"] = (\n            b'<?xpacket begin=\"\\xef\\xbb\\xbf\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\\n'\n            b'<x:xmpmeta xmlns:x=\"adobe:ns:meta/\" />\\n<?xpacket end=\"w\"?>\\x00\\x00'\n        )\n        if ElementTree is None:\n            with pytest.warns(\n                UserWarning,\n                match=\"XMP data cannot be read without defusedxml dependency\",\n            ):\n                assert im.getxmp() == {}\n        else:\n            assert im.getxmp() == {\"xmpmeta\": None}\n\n    @pytest.mark.parametrize(\"size\", ((1, 0), (0, 1), (0, 0)))\n    def test_zero_tobytes(self, size: tuple[int, int]) -> None:\n        im = Image.new(\"RGB\", size)\n        assert im.tobytes() == b\"\"\n\n    @pytest.mark.parametrize(\"size\", ((1, 0), (0, 1), (0, 0)))\n    def test_zero_frombytes(self, size: tuple[int, int]) -> None:\n        Image.frombytes(\"RGB\", size, b\"\")\n\n        im = Image.new(\"RGB\", size)\n        im.frombytes(b\"\")\n\n    def test_has_transparency_data(self) -> None:\n        for mode in (\"1\", \"L\", \"P\", \"RGB\"):\n            im = Image.new(mode, (1, 1))\n            assert not im.has_transparency_data\n\n        for mode in (\"LA\", \"La\", \"PA\", \"RGBA\", \"RGBa\"):\n            im = Image.new(mode, (1, 1))\n            assert im.has_transparency_data\n\n        # P mode with \"transparency\" info\n        with Image.open(\"Tests/images/first_frame_transparency.gif\") as im:\n            assert \"transparency\" in im.info\n            assert im.has_transparency_data\n\n        # RGB mode with \"transparency\" info\n        with Image.open(\"Tests/images/rgb_trns.png\") as im:\n            assert \"transparency\" in im.info\n            assert im.has_transparency_data\n\n        # P mode with RGBA palette\n        im = Image.new(\"RGBA\", (1, 1)).convert(\"P\")\n        assert im.mode == \"P\"\n        assert im.palette.mode == \"RGBA\"\n        assert im.has_transparency_data\n\n    def test_apply_transparency(self) -> None:\n        im = Image.new(\"P\", (1, 1))\n        im.putpalette((0, 0, 0, 1, 1, 1))\n        assert im.palette.colors == {(0, 0, 0): 0, (1, 1, 1): 1}\n\n        # Test that no transformation is applied without transparency\n        im.apply_transparency()\n        assert im.palette.colors == {(0, 0, 0): 0, (1, 1, 1): 1}\n\n        # Test that a transparency index is applied\n        im.info[\"transparency\"] = 0\n        im.apply_transparency()\n        assert \"transparency\" not in im.info\n        assert im.palette.colors == {(0, 0, 0, 0): 0, (1, 1, 1, 255): 1}\n\n        # Test that existing transparency is kept\n        im = Image.new(\"P\", (1, 1))\n        im.putpalette((0, 0, 0, 255, 1, 1, 1, 128), \"RGBA\")\n        im.info[\"transparency\"] = 0\n        im.apply_transparency()\n        assert im.palette.colors == {(0, 0, 0, 0): 0, (1, 1, 1, 128): 1}\n\n        # Test that transparency bytes are applied\n        with Image.open(\"Tests/images/pil123p.png\") as im:\n            assert isinstance(im.info[\"transparency\"], bytes)\n            assert im.palette.colors[(27, 35, 6)] == 24\n            im.apply_transparency()\n            assert im.palette.colors[(27, 35, 6, 214)] == 24\n\n    def test_constants(self) -> None:\n        for enum in (\n            Image.Transpose,\n            Image.Transform,\n            Image.Resampling,\n            Image.Dither,\n            Image.Palette,\n            Image.Quantize,\n        ):\n            for name in enum.__members__:\n                assert getattr(Image, name) == enum[name]\n\n    @pytest.mark.parametrize(\n        \"path\",\n        [\n            \"fli_overrun.bin\",\n            \"sgi_overrun.bin\",\n            \"sgi_overrun_expandrow.bin\",\n            \"sgi_overrun_expandrow2.bin\",\n            \"pcx_overrun.bin\",\n            \"pcx_overrun2.bin\",\n            \"ossfuzz-4836216264589312.pcx\",\n            \"01r_00.pcx\",\n        ],\n    )\n    def test_overrun(self, path: str) -> None:\n        \"\"\"For overrun completeness, test as:\n        valgrind pytest -qq Tests/test_image.py::TestImage::test_overrun | grep decode.c\n        \"\"\"\n        with Image.open(os.path.join(\"Tests/images\", path)) as im:\n            try:\n                im.load()\n                pytest.fail()\n            except OSError as e:\n                buffer_overrun = str(e) == \"buffer overrun when reading image file\"\n                truncated = \"image file is truncated\" in str(e)\n\n                assert buffer_overrun or truncated\n\n    def test_fli_overrun2(self) -> None:\n        with Image.open(\"Tests/images/fli_overrun2.bin\") as im:\n            try:\n                im.seek(1)\n                pytest.fail()\n            except OSError as e:\n                assert str(e) == \"buffer overrun when reading image file\"\n\n    def test_exit_fp(self) -> None:\n        with Image.new(\"L\", (1, 1)) as im:\n            pass\n        assert not hasattr(im, \"fp\")\n\n    def test_close_graceful(self, caplog: pytest.LogCaptureFixture) -> None:\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            copy = im.copy()\n            with caplog.at_level(logging.DEBUG):\n                im.close()\n                copy.close()\n            assert len(caplog.records) == 0\n            assert im.fp is None\n\n\nclass TestImageBytes:\n    @pytest.mark.parametrize(\"mode\", Image.MODES + [\"BGR;15\", \"BGR;16\", \"BGR;24\"])\n    def test_roundtrip_bytes_constructor(self, mode: str) -> None:\n        im = hopper(mode)\n        source_bytes = im.tobytes()\n\n        if mode.startswith(\"BGR;\"):\n            with pytest.warns(DeprecationWarning):\n                reloaded = Image.frombytes(mode, im.size, source_bytes)\n        else:\n            reloaded = Image.frombytes(mode, im.size, source_bytes)\n        assert reloaded.tobytes() == source_bytes\n\n    @pytest.mark.parametrize(\"mode\", Image.MODES + [\"BGR;15\", \"BGR;16\", \"BGR;24\"])\n    def test_roundtrip_bytes_method(self, mode: str) -> None:\n        im = hopper(mode)\n        source_bytes = im.tobytes()\n\n        reloaded = helper_image_new(mode, im.size)\n        reloaded.frombytes(source_bytes)\n        assert reloaded.tobytes() == source_bytes\n\n    @pytest.mark.parametrize(\"mode\", Image.MODES + [\"BGR;15\", \"BGR;16\", \"BGR;24\"])\n    def test_getdata_putdata(self, mode: str) -> None:\n        if is_big_endian() and mode == \"BGR;15\":\n            pytest.xfail(\"Known failure of BGR;15 on big-endian\")\n        im = hopper(mode)\n        reloaded = helper_image_new(mode, im.size)\n        reloaded.putdata(im.getdata())\n        assert_image_equal(im, reloaded)\n\n\nclass MockEncoder(ImageFile.PyEncoder):\n    pass\n\n\nclass TestRegistry:\n    def test_encode_registry(self) -> None:\n        Image.register_encoder(\"MOCK\", MockEncoder)\n        assert \"MOCK\" in Image.ENCODERS\n\n        enc = Image._getencoder(\"RGB\", \"MOCK\", (\"args\",), extra=(\"extra\",))\n\n        assert isinstance(enc, MockEncoder)\n        assert enc.mode == \"RGB\"\n        assert enc.args == (\"args\", \"extra\")\n\n    def test_encode_registry_fail(self) -> None:\n        with pytest.raises(OSError):\n            Image._getencoder(\"RGB\", \"DoesNotExist\", (\"args\",), extra=(\"extra\",))\n",
            "header": {
                "file": {
                    "path": "Tests/test_image.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "c5cf5b383",
                "new_commit_hash": "93f9b9833",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/Tests/test_image.py"
            },
            "plus_file": {
                "path": "b/Tests/test_image.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 132,
                            "length": 6
                        },
                        "new_range": {
                            "start": 132,
                            "length": 15
                        },
                        "section": "class TestImage:"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "                assert im.mode == \"RGB\"",
                                "type": "context"
                            },
                            {
                                "content": "                assert im.size == (128, 128)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def test_open_verbose_failure(self, monkeypatch: pytest.MonkeyPatch) -> None:",
                                "type": "added"
                            },
                            {
                                "content": "        monkeypatch.setattr(Image, \"WARN_POSSIBLE_FORMATS\", True)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        im = io.BytesIO(b\"\")",
                                "type": "added"
                            },
                            {
                                "content": "        with pytest.warns(UserWarning):",
                                "type": "added"
                            },
                            {
                                "content": "            with pytest.raises(UnidentifiedImageError):",
                                "type": "added"
                            },
                            {
                                "content": "                with Image.open(im):",
                                "type": "added"
                            },
                            {
                                "content": "                    pass",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def test_width_height(self) -> None:",
                                "type": "context"
                            },
                            {
                                "content": "        im = Image.new(\"RGB\", (1, 2))",
                                "type": "context"
                            },
                            {
                                "content": "        assert im.width == 1",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Tests/test_image.py",
                            "type": "class",
                            "name": "TestImage",
                            "content": "class TestImage:\n    @pytest.mark.parametrize(\"mode\", Image.MODES + [\"BGR;15\", \"BGR;16\", \"BGR;24\"])\n    def test_image_modes_success(self, mode: str) -> None:\n        helper_image_new(mode, (1, 1))\n\n    @pytest.mark.parametrize(\"mode\", (\"\", \"bad\", \"very very long\"))\n    def test_image_modes_fail(self, mode: str) -> None:\n        with pytest.raises(ValueError) as e:\n            Image.new(mode, (1, 1))\n        assert str(e.value) == \"unrecognized image mode\"\n\n    def test_exception_inheritance(self) -> None:\n        assert issubclass(UnidentifiedImageError, OSError)\n\n    def test_sanity(self) -> None:\n        im = Image.new(\"L\", (100, 100))\n        assert repr(im)[:45] == \"<PIL.Image.Image image mode=L size=100x100 at\"\n        assert im.mode == \"L\"\n        assert im.size == (100, 100)\n\n        im = Image.new(\"RGB\", (100, 100))\n        assert repr(im)[:45] == \"<PIL.Image.Image image mode=RGB size=100x100 \"\n        assert im.mode == \"RGB\"\n        assert im.size == (100, 100)\n\n        Image.new(\"L\", (100, 100), None)\n        im2 = Image.new(\"L\", (100, 100), 0)\n        im3 = Image.new(\"L\", (100, 100), \"black\")\n\n        assert im2.getcolors() == [(10000, 0)]\n        assert im3.getcolors() == [(10000, 0)]\n\n        with pytest.raises(ValueError):\n            Image.new(\"X\", (100, 100))\n        with pytest.raises(ValueError):\n            Image.new(\"\", (100, 100))\n        # with pytest.raises(MemoryError):\n        #   Image.new(\"L\", (1000000, 1000000))\n\n    def test_repr_pretty(self) -> None:\n        class Pretty:\n            def text(self, text: str) -> None:\n                self.pretty_output = text\n\n        im = Image.new(\"L\", (100, 100))\n\n        p = Pretty()\n        im._repr_pretty_(p, None)\n        assert p.pretty_output == \"<PIL.Image.Image image mode=L size=100x100>\"\n\n    def test_open_formats(self) -> None:\n        PNGFILE = \"Tests/images/hopper.png\"\n        JPGFILE = \"Tests/images/hopper.jpg\"\n\n        with pytest.raises(TypeError):\n            with Image.open(PNGFILE, formats=123):  # type: ignore[arg-type]\n                pass\n\n        format_list: list[list[str] | tuple[str, ...]] = [\n            [\"JPEG\"],\n            (\"JPEG\",),\n            [\"jpeg\"],\n            [\"Jpeg\"],\n            [\"jPeG\"],\n            [\"JpEg\"],\n        ]\n        for formats in format_list:\n            with pytest.raises(UnidentifiedImageError):\n                with Image.open(PNGFILE, formats=formats):\n                    pass\n\n            with Image.open(JPGFILE, formats=formats) as im:\n                assert im.mode == \"RGB\"\n                assert im.size == (128, 128)\n\n        for file in [PNGFILE, JPGFILE]:\n            with Image.open(file, formats=None) as im:\n                assert im.mode == \"RGB\"\n                assert im.size == (128, 128)\n\n    def test_open_verbose_failure(self, monkeypatch: pytest.MonkeyPatch) -> None:\n        monkeypatch.setattr(Image, \"WARN_POSSIBLE_FORMATS\", True)\n\n        im = io.BytesIO(b\"\")\n        with pytest.warns(UserWarning):\n            with pytest.raises(UnidentifiedImageError):\n                with Image.open(im):\n                    pass\n\n    def test_width_height(self) -> None:\n        im = Image.new(\"RGB\", (1, 2))\n        assert im.width == 1\n        assert im.height == 2\n\n        with pytest.raises(AttributeError):\n            im.size = (3, 4)  # type: ignore[misc]\n\n    def test_set_mode(self) -> None:\n        im = Image.new(\"RGB\", (1, 1))\n\n        with pytest.raises(AttributeError):\n            im.mode = \"P\"  # type: ignore[misc]\n\n    def test_invalid_image(self) -> None:\n        im = io.BytesIO(b\"\")\n        with pytest.raises(UnidentifiedImageError):\n            with Image.open(im):\n                pass\n\n    def test_bad_mode(self) -> None:\n        with pytest.raises(ValueError):\n            with Image.open(\"filename\", \"bad mode\"):  # type: ignore[arg-type]\n                pass\n\n    def test_stringio(self) -> None:\n        with pytest.raises(ValueError):\n            with Image.open(io.StringIO()):  # type: ignore[arg-type]\n                pass\n\n    def test_pathlib(self, tmp_path: Path) -> None:\n        with Image.open(Path(\"Tests/images/multipage-mmap.tiff\")) as im:\n            assert im.mode == \"P\"\n            assert im.size == (10, 10)\n\n        with Image.open(Path(\"Tests/images/hopper.jpg\")) as im:\n            assert im.mode == \"RGB\"\n            assert im.size == (128, 128)\n\n            for ext in (\".jpg\", \".jp2\"):\n                if ext == \".jp2\" and not features.check_codec(\"jpg_2000\"):\n                    pytest.skip(\"jpg_2000 not available\")\n                temp_file = str(tmp_path / (\"temp.\" + ext))\n                if os.path.exists(temp_file):\n                    os.remove(temp_file)\n                im.save(Path(temp_file))\n\n    def test_fp_name(self, tmp_path: Path) -> None:\n        temp_file = str(tmp_path / \"temp.jpg\")\n\n        class FP(io.BytesIO):\n            name: str\n\n            if sys.version_info >= (3, 12):\n                from collections.abc import Buffer\n\n                def write(self, data: Buffer) -> int:\n                    return len(data)\n\n            else:\n\n                def write(self, data: Any) -> int:\n                    return len(data)\n\n        fp = FP()\n        fp.name = temp_file\n\n        im = hopper()\n        im.save(fp)\n\n    def test_tempfile(self) -> None:\n        # see #1460, pathlib support breaks tempfile.TemporaryFile on py27\n        # Will error out on save on 3.0.0\n        im = hopper()\n        with tempfile.TemporaryFile() as fp:\n            im.save(fp, \"JPEG\")\n            fp.seek(0)\n            with Image.open(fp) as reloaded:\n                assert_image_similar(im, reloaded, 20)\n\n    def test_unknown_extension(self, tmp_path: Path) -> None:\n        im = hopper()\n        temp_file = str(tmp_path / \"temp.unknown\")\n        with pytest.raises(ValueError):\n            im.save(temp_file)\n\n    def test_internals(self) -> None:\n        im = Image.new(\"L\", (100, 100))\n        im.readonly = 1\n        im._copy()\n        assert not im.readonly\n\n        im.readonly = 1\n        im.paste(0, (0, 0, 100, 100))\n        assert not im.readonly\n\n    @pytest.mark.skipif(is_win32(), reason=\"Test requires opening tempfile twice\")\n    @pytest.mark.skipif(\n        sys.platform == \"cygwin\",\n        reason=\"Test requires opening an mmaped file for writing\",\n    )\n    def test_readonly_save(self, tmp_path: Path) -> None:\n        temp_file = str(tmp_path / \"temp.bmp\")\n        shutil.copy(\"Tests/images/rgb32bf-rgba.bmp\", temp_file)\n\n        with Image.open(temp_file) as im:\n            assert im.readonly\n            im.save(temp_file)\n\n    def test_dump(self, tmp_path: Path) -> None:\n        im = Image.new(\"L\", (10, 10))\n        im._dump(str(tmp_path / \"temp_L.ppm\"))\n\n        im = Image.new(\"RGB\", (10, 10))\n        im._dump(str(tmp_path / \"temp_RGB.ppm\"))\n\n        im = Image.new(\"HSV\", (10, 10))\n        with pytest.raises(ValueError):\n            im._dump(str(tmp_path / \"temp_HSV.ppm\"))\n\n    def test_comparison_with_other_type(self) -> None:\n        # Arrange\n        item = Image.new(\"RGB\", (25, 25), \"#000\")\n        num = 12\n\n        # Act/Assert\n        # Shouldn't cause AttributeError (#774)\n        assert item is not None\n        assert item != num\n\n    def test_expand_x(self) -> None:\n        # Arrange\n        im = hopper()\n        orig_size = im.size\n        xmargin = 5\n\n        # Act\n        im = im._expand(xmargin)\n\n        # Assert\n        assert im.size[0] == orig_size[0] + 2 * xmargin\n        assert im.size[1] == orig_size[1] + 2 * xmargin\n\n    def test_expand_xy(self) -> None:\n        # Arrange\n        im = hopper()\n        orig_size = im.size\n        xmargin = 5\n        ymargin = 3\n\n        # Act\n        im = im._expand(xmargin, ymargin)\n\n        # Assert\n        assert im.size[0] == orig_size[0] + 2 * xmargin\n        assert im.size[1] == orig_size[1] + 2 * ymargin\n\n    def test_getbands(self) -> None:\n        # Assert\n        assert hopper(\"RGB\").getbands() == (\"R\", \"G\", \"B\")\n        assert hopper(\"YCbCr\").getbands() == (\"Y\", \"Cb\", \"Cr\")\n\n    def test_getchannel_wrong_params(self) -> None:\n        im = hopper()\n\n        with pytest.raises(ValueError):\n            im.getchannel(-1)\n        with pytest.raises(ValueError):\n            im.getchannel(3)\n        with pytest.raises(ValueError):\n            im.getchannel(\"Z\")\n        with pytest.raises(ValueError):\n            im.getchannel(\"1\")\n\n    def test_getchannel(self) -> None:\n        im = hopper(\"YCbCr\")\n        Y, Cb, Cr = im.split()\n\n        assert_image_equal(Y, im.getchannel(0))\n        assert_image_equal(Y, im.getchannel(\"Y\"))\n        assert_image_equal(Cb, im.getchannel(1))\n        assert_image_equal(Cb, im.getchannel(\"Cb\"))\n        assert_image_equal(Cr, im.getchannel(2))\n        assert_image_equal(Cr, im.getchannel(\"Cr\"))\n\n    def test_getbbox(self) -> None:\n        # Arrange\n        im = hopper()\n\n        # Act\n        bbox = im.getbbox()\n\n        # Assert\n        assert bbox == (0, 0, 128, 128)\n\n    def test_ne(self) -> None:\n        # Arrange\n        im1 = Image.new(\"RGB\", (25, 25), \"black\")\n        im2 = Image.new(\"RGB\", (25, 25), \"white\")\n\n        # Act / Assert\n        assert im1 != im2\n\n    def test_alpha_composite(self) -> None:\n        # https://stackoverflow.com/questions/3374878\n        # Arrange\n        expected_colors = sorted(\n            [\n                (1122, (128, 127, 0, 255)),\n                (1089, (0, 255, 0, 255)),\n                (3300, (255, 0, 0, 255)),\n                (1156, (170, 85, 0, 192)),\n                (1122, (0, 255, 0, 128)),\n                (1122, (255, 0, 0, 128)),\n                (1089, (0, 255, 0, 0)),\n            ]\n        )\n\n        dst = Image.new(\"RGBA\", size=(100, 100), color=(0, 255, 0, 255))\n        draw = ImageDraw.Draw(dst)\n        draw.rectangle((0, 33, 100, 66), fill=(0, 255, 0, 128))\n        draw.rectangle((0, 67, 100, 100), fill=(0, 255, 0, 0))\n        src = Image.new(\"RGBA\", size=(100, 100), color=(255, 0, 0, 255))\n        draw = ImageDraw.Draw(src)\n        draw.rectangle((33, 0, 66, 100), fill=(255, 0, 0, 128))\n        draw.rectangle((67, 0, 100, 100), fill=(255, 0, 0, 0))\n\n        # Act\n        img = Image.alpha_composite(dst, src)\n\n        # Assert\n        img_colors = sorted(img.getcolors())\n        assert img_colors == expected_colors\n\n    def test_alpha_inplace(self) -> None:\n        src = Image.new(\"RGBA\", (128, 128), \"blue\")\n\n        over = Image.new(\"RGBA\", (128, 128), \"red\")\n        mask = hopper(\"L\")\n        over.putalpha(mask)\n\n        target = Image.alpha_composite(src, over)\n\n        # basic\n        full = src.copy()\n        full.alpha_composite(over)\n        assert_image_equal(full, target)\n\n        # with offset down to right\n        offset = src.copy()\n        offset.alpha_composite(over, (64, 64))\n        assert_image_equal(offset.crop((64, 64, 127, 127)), target.crop((0, 0, 63, 63)))\n        assert offset.size == (128, 128)\n\n        # with negative offset\n        offset = src.copy()\n        offset.alpha_composite(over, (-64, -64))\n        assert_image_equal(offset.crop((0, 0, 63, 63)), target.crop((64, 64, 127, 127)))\n        assert offset.size == (128, 128)\n\n        # offset and crop\n        box = src.copy()\n        box.alpha_composite(over, (64, 64), (0, 0, 32, 32))\n        assert_image_equal(box.crop((64, 64, 96, 96)), target.crop((0, 0, 32, 32)))\n        assert_image_equal(box.crop((96, 96, 128, 128)), src.crop((0, 0, 32, 32)))\n        assert box.size == (128, 128)\n\n        # source point\n        source = src.copy()\n        source.alpha_composite(over, (32, 32), (32, 32, 96, 96))\n\n        assert_image_equal(source.crop((32, 32, 96, 96)), target.crop((32, 32, 96, 96)))\n        assert source.size == (128, 128)\n\n        # errors\n        with pytest.raises(ValueError):\n            source.alpha_composite(over, \"invalid destination\")  # type: ignore[arg-type]\n        with pytest.raises(ValueError):\n            source.alpha_composite(over, (0, 0), \"invalid source\")  # type: ignore[arg-type]\n        with pytest.raises(ValueError):\n            source.alpha_composite(over, 0)  # type: ignore[arg-type]\n        with pytest.raises(ValueError):\n            source.alpha_composite(over, (0, 0), 0)  # type: ignore[arg-type]\n        with pytest.raises(ValueError):\n            source.alpha_composite(over, (0, 0), (0, -1))\n\n    def test_register_open_duplicates(self) -> None:\n        # Arrange\n        factory, accept = Image.OPEN[\"JPEG\"]\n        id_length = len(Image.ID)\n\n        # Act\n        Image.register_open(\"JPEG\", factory, accept)\n\n        # Assert\n        assert len(Image.ID) == id_length\n\n    def test_registered_extensions_uninitialized(self) -> None:\n        # Arrange\n        Image._initialized = 0\n\n        # Act\n        Image.registered_extensions()\n\n        # Assert\n        assert Image._initialized == 2\n\n    def test_registered_extensions(self) -> None:\n        # Arrange\n        # Open an image to trigger plugin registration\n        with Image.open(\"Tests/images/rgb.jpg\"):\n            pass\n\n        # Act\n        extensions = Image.registered_extensions()\n\n        # Assert\n        assert extensions\n        for ext in [\".cur\", \".icns\", \".tif\", \".tiff\"]:\n            assert ext in extensions\n\n    def test_effect_mandelbrot(self) -> None:\n        # Arrange\n        size = (512, 512)\n        extent = (-3, -2.5, 2, 2.5)\n        quality = 100\n\n        # Act\n        im = Image.effect_mandelbrot(size, extent, quality)\n\n        # Assert\n        assert im.size == (512, 512)\n        assert_image_equal_tofile(im, \"Tests/images/effect_mandelbrot.png\")\n\n    def test_effect_mandelbrot_bad_arguments(self) -> None:\n        # Arrange\n        size = (512, 512)\n        # Get coordinates the wrong way round:\n        extent = (+3, +2.5, -2, -2.5)\n        # Quality < 2:\n        quality = 1\n\n        # Act/Assert\n        with pytest.raises(ValueError):\n            Image.effect_mandelbrot(size, extent, quality)\n\n    def test_effect_noise(self) -> None:\n        # Arrange\n        size = (100, 100)\n        sigma = 128\n\n        # Act\n        im = Image.effect_noise(size, sigma)\n\n        # Assert\n        assert im.size == (100, 100)\n        assert im.mode == \"L\"\n        p0 = im.getpixel((0, 0))\n        p1 = im.getpixel((0, 1))\n        p2 = im.getpixel((0, 2))\n        p3 = im.getpixel((0, 3))\n        p4 = im.getpixel((0, 4))\n        assert_not_all_same([p0, p1, p2, p3, p4])\n\n    def test_effect_spread(self) -> None:\n        # Arrange\n        im = hopper()\n        distance = 10\n\n        # Act\n        im2 = im.effect_spread(distance)\n\n        # Assert\n        assert im.size == (128, 128)\n        assert_image_similar_tofile(im2, \"Tests/images/effect_spread.png\", 110)\n\n    def test_effect_spread_zero(self) -> None:\n        # Arrange\n        im = hopper()\n        distance = 0\n\n        # Act\n        im2 = im.effect_spread(distance)\n\n        # Assert\n        assert_image_equal(im, im2)\n\n    def test_check_size(self) -> None:\n        # Checking that the _check_size function throws value errors when we want it to\n        with pytest.raises(ValueError):\n            # not a tuple\n            Image.new(\"RGB\", 0)  # type: ignore[arg-type]\n        with pytest.raises(ValueError):\n            # tuple too short\n            Image.new(\"RGB\", (0,))  # type: ignore[arg-type]\n        with pytest.raises(ValueError):\n            Image.new(\"RGB\", (-1, -1))  # w,h < 0\n\n        # this should pass with 0 sized images, #2259\n        im = Image.new(\"L\", (0, 0))\n        assert im.size == (0, 0)\n\n        im = Image.new(\"L\", (0, 100))\n        assert im.size == (0, 100)\n\n        im = Image.new(\"L\", (100, 0))\n        assert im.size == (100, 0)\n\n        assert Image.new(\"RGB\", (1, 1))\n        # Should pass lists too\n        i = Image.new(\"RGB\", [1, 1])\n        assert isinstance(i.size, tuple)\n\n    @pytest.mark.timeout(0.75)\n    @pytest.mark.skipif(\n        \"PILLOW_VALGRIND_TEST\" in os.environ, reason=\"Valgrind is slower\"\n    )\n    @pytest.mark.parametrize(\"size\", ((0, 100000000), (100000000, 0)))\n    def test_empty_image(self, size: tuple[int, int]) -> None:\n        Image.new(\"RGB\", size)\n\n    def test_storage_neg(self) -> None:\n        # Storage.c accepted negative values for xsize, ysize.  Was\n        # test_neg_ppm, but the core function for that has been\n        # removed Calling directly into core to test the error in\n        # Storage.c, rather than the size check above\n\n        with pytest.raises(ValueError):\n            Image.core.fill(\"RGB\", (2, -2), (0, 0, 0))\n\n    def test_one_item_tuple(self) -> None:\n        for mode in (\"I\", \"F\", \"L\"):\n            im = Image.new(mode, (100, 100), (5,))\n            px = im.load()\n            assert px[0, 0] == 5\n\n    def test_linear_gradient_wrong_mode(self) -> None:\n        # Arrange\n        wrong_mode = \"RGB\"\n\n        # Act / Assert\n        with pytest.raises(ValueError):\n            Image.linear_gradient(wrong_mode)\n\n    @pytest.mark.parametrize(\"mode\", (\"L\", \"P\", \"I\", \"F\"))\n    def test_linear_gradient(self, mode: str) -> None:\n        # Arrange\n        target_file = \"Tests/images/linear_gradient.png\"\n\n        # Act\n        im = Image.linear_gradient(mode)\n\n        # Assert\n        assert im.size == (256, 256)\n        assert im.mode == mode\n        assert im.getpixel((0, 0)) == 0\n        assert im.getpixel((255, 255)) == 255\n        with Image.open(target_file) as target:\n            target = target.convert(mode)\n        assert_image_equal(im, target)\n\n    def test_radial_gradient_wrong_mode(self) -> None:\n        # Arrange\n        wrong_mode = \"RGB\"\n\n        # Act / Assert\n        with pytest.raises(ValueError):\n            Image.radial_gradient(wrong_mode)\n\n    @pytest.mark.parametrize(\"mode\", (\"L\", \"P\", \"I\", \"F\"))\n    def test_radial_gradient(self, mode: str) -> None:\n        # Arrange\n        target_file = \"Tests/images/radial_gradient.png\"\n\n        # Act\n        im = Image.radial_gradient(mode)\n\n        # Assert\n        assert im.size == (256, 256)\n        assert im.mode == mode\n        assert im.getpixel((0, 0)) == 255\n        assert im.getpixel((128, 128)) == 0\n        with Image.open(target_file) as target:\n            target = target.convert(mode)\n        assert_image_equal(im, target)\n\n    def test_register_extensions(self) -> None:\n        test_format = \"a\"\n        exts = [\"b\", \"c\"]\n        for ext in exts:\n            Image.register_extension(test_format, ext)\n        ext_individual = Image.EXTENSION.copy()\n        for ext in exts:\n            del Image.EXTENSION[ext]\n\n        Image.register_extensions(test_format, exts)\n        ext_multiple = Image.EXTENSION.copy()\n        for ext in exts:\n            del Image.EXTENSION[ext]\n\n        assert ext_individual == ext_multiple\n\n    def test_remap_palette(self) -> None:\n        # Test identity transform\n        with Image.open(\"Tests/images/hopper.gif\") as im:\n            assert_image_equal(im, im.remap_palette(list(range(256))))\n\n        # Test identity transform with an RGBA palette\n        im = Image.new(\"P\", (256, 1))\n        for x in range(256):\n            im.putpixel((x, 0), x)\n        im.putpalette(list(range(256)) * 4, \"RGBA\")\n        im_remapped = im.remap_palette(list(range(256)))\n        assert_image_equal(im, im_remapped)\n        assert im.palette.palette == im_remapped.palette.palette\n\n        # Test illegal image mode\n        with hopper() as im:\n            with pytest.raises(ValueError):\n                im.remap_palette(None)\n\n    def test_remap_palette_transparency(self) -> None:\n        im = Image.new(\"P\", (1, 2), (0, 0, 0))\n        im.putpixel((0, 1), (255, 0, 0))\n        im.info[\"transparency\"] = 0\n\n        im_remapped = im.remap_palette([1, 0])\n        assert im_remapped.info[\"transparency\"] == 1\n        assert len(im_remapped.getpalette()) == 6\n\n        # Test unused transparency\n        im.info[\"transparency\"] = 2\n\n        im_remapped = im.remap_palette([1, 0])\n        assert \"transparency\" not in im_remapped.info\n\n    def test__new(self) -> None:\n        im = hopper(\"RGB\")\n        im_p = hopper(\"P\")\n\n        blank_p = Image.new(\"P\", (10, 10))\n        blank_pa = Image.new(\"PA\", (10, 10))\n        blank_p.palette = None\n        blank_pa.palette = None\n\n        def _make_new(\n            base_image: Image.Image,\n            image: Image.Image,\n            palette_result: ImagePalette.ImagePalette | None = None,\n        ) -> None:\n            new_image = base_image._new(image.im)\n            assert new_image.mode == image.mode\n            assert new_image.size == image.size\n            assert new_image.info == base_image.info\n            if palette_result is not None:\n                assert new_image.palette.tobytes() == palette_result.tobytes()\n            else:\n                assert new_image.palette is None\n\n        _make_new(im, im_p, ImagePalette.ImagePalette(list(range(256)) * 3))\n        _make_new(im_p, im, None)\n        _make_new(im, blank_p, ImagePalette.ImagePalette())\n        _make_new(im, blank_pa, ImagePalette.ImagePalette())\n\n    @pytest.mark.parametrize(\n        \"mode, color\",\n        (\n            (\"RGB\", \"#DDEEFF\"),\n            (\"RGB\", (221, 238, 255)),\n            (\"RGBA\", (221, 238, 255, 255)),\n        ),\n    )\n    def test_p_from_rgb_rgba(self, mode: str, color: str | tuple[int, ...]) -> None:\n        im = Image.new(\"P\", (100, 100), color)\n        expected = Image.new(mode, (100, 100), color)\n        assert_image_equal(im.convert(mode), expected)\n\n    def test_no_resource_warning_on_save(self, tmp_path: Path) -> None:\n        # https://github.com/python-pillow/Pillow/issues/835\n        # Arrange\n        test_file = \"Tests/images/hopper.png\"\n        temp_file = str(tmp_path / \"temp.jpg\")\n\n        # Act/Assert\n        with Image.open(test_file) as im:\n            with warnings.catch_warnings():\n                im.save(temp_file)\n\n    def test_no_new_file_on_error(self, tmp_path: Path) -> None:\n        temp_file = str(tmp_path / \"temp.jpg\")\n\n        im = Image.new(\"RGB\", (0, 0))\n        with pytest.raises(ValueError):\n            im.save(temp_file)\n\n        assert not os.path.exists(temp_file)\n\n    def test_load_on_nonexclusive_multiframe(self) -> None:\n        with open(\"Tests/images/frozenpond.mpo\", \"rb\") as fp:\n\n            def act(fp: IO[bytes]) -> None:\n                im = Image.open(fp)\n                im.load()\n\n            act(fp)\n\n            with Image.open(fp) as im:\n                im.load()\n\n            assert not fp.closed\n\n    def test_empty_exif(self) -> None:\n        with Image.open(\"Tests/images/exif.png\") as im:\n            exif = im.getexif()\n        assert dict(exif)\n\n        # Test that exif data is cleared after another load\n        exif.load(None)\n        assert not dict(exif)\n\n        # Test loading just the EXIF header\n        exif.load(b\"Exif\\x00\\x00\")\n        assert not dict(exif)\n\n    @mark_if_feature_version(\n        pytest.mark.valgrind_known_error, \"libjpeg_turbo\", \"2.0\", reason=\"Known Failing\"\n    )\n    def test_exif_jpeg(self, tmp_path: Path) -> None:\n        with Image.open(\"Tests/images/exif-72dpi-int.jpg\") as im:  # Little endian\n            exif = im.getexif()\n            assert 258 not in exif\n            assert 274 in exif\n            assert 282 in exif\n            assert exif[296] == 2\n            assert exif[11] == \"gThumb 3.0.1\"\n\n            out = str(tmp_path / \"temp.jpg\")\n            exif[258] = 8\n            del exif[274]\n            del exif[282]\n            exif[296] = 455\n            exif[11] = \"Pillow test\"\n            im.save(out, exif=exif)\n        with Image.open(out) as reloaded:\n            reloaded_exif = reloaded.getexif()\n            assert reloaded_exif[258] == 8\n            assert 274 not in reloaded_exif\n            assert 282 not in reloaded_exif\n            assert reloaded_exif[296] == 455\n            assert reloaded_exif[11] == \"Pillow test\"\n\n        with Image.open(\"Tests/images/no-dpi-in-exif.jpg\") as im:  # Big endian\n            exif = im.getexif()\n            assert 258 not in exif\n            assert 306 in exif\n            assert exif[274] == 1\n            assert exif[305] == \"Adobe Photoshop CC 2017 (Macintosh)\"\n\n            out = str(tmp_path / \"temp.jpg\")\n            exif[258] = 8\n            del exif[306]\n            exif[274] = 455\n            exif[305] = \"Pillow test\"\n            im.save(out, exif=exif)\n        with Image.open(out) as reloaded:\n            reloaded_exif = reloaded.getexif()\n            assert reloaded_exif[258] == 8\n            assert 306 not in reloaded_exif\n            assert reloaded_exif[274] == 455\n            assert reloaded_exif[305] == \"Pillow test\"\n\n    @skip_unless_feature(\"webp\")\n    @skip_unless_feature(\"webp_anim\")\n    def test_exif_webp(self, tmp_path: Path) -> None:\n        with Image.open(\"Tests/images/hopper.webp\") as im:\n            exif = im.getexif()\n            assert exif == {}\n\n            out = str(tmp_path / \"temp.webp\")\n            exif[258] = 8\n            exif[40963] = 455\n            exif[305] = \"Pillow test\"\n\n            def check_exif() -> None:\n                with Image.open(out) as reloaded:\n                    reloaded_exif = reloaded.getexif()\n                    assert reloaded_exif[258] == 8\n                    assert reloaded_exif[40963] == 455\n                    assert reloaded_exif[305] == \"Pillow test\"\n\n            im.save(out, exif=exif)\n            check_exif()\n            im.save(out, exif=exif, save_all=True)\n            check_exif()\n\n    def test_exif_png(self, tmp_path: Path) -> None:\n        with Image.open(\"Tests/images/exif.png\") as im:\n            exif = im.getexif()\n            assert exif == {274: 1}\n\n            out = str(tmp_path / \"temp.png\")\n            exif[258] = 8\n            del exif[274]\n            exif[40963] = 455\n            exif[305] = \"Pillow test\"\n            im.save(out, exif=exif)\n\n        with Image.open(out) as reloaded:\n            reloaded_exif = reloaded.getexif()\n            assert reloaded_exif == {258: 8, 40963: 455, 305: \"Pillow test\"}\n\n    def test_exif_interop(self) -> None:\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            exif = im.getexif()\n            assert exif.get_ifd(0xA005) == {\n                1: \"R98\",\n                2: b\"0100\",\n                4097: 2272,\n                4098: 1704,\n            }\n\n            reloaded_exif = Image.Exif()\n            reloaded_exif.load(exif.tobytes())\n            assert reloaded_exif.get_ifd(0xA005) == exif.get_ifd(0xA005)\n\n    def test_exif_ifd1(self) -> None:\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            exif = im.getexif()\n            assert exif.get_ifd(ExifTags.IFD.IFD1) == {\n                513: 2036,\n                514: 5448,\n                259: 6,\n                296: 2,\n                282: 180.0,\n                283: 180.0,\n            }\n\n    def test_exif_ifd(self) -> None:\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            exif = im.getexif()\n        del exif.get_ifd(0x8769)[0xA005]\n\n        reloaded_exif = Image.Exif()\n        reloaded_exif.load(exif.tobytes())\n        assert reloaded_exif.get_ifd(0x8769) == exif.get_ifd(0x8769)\n\n    def test_exif_load_from_fp(self) -> None:\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            data = im.info[\"exif\"]\n            if data.startswith(b\"Exif\\x00\\x00\"):\n                data = data[6:]\n            fp = io.BytesIO(data)\n\n            exif = Image.Exif()\n            exif.load_from_fp(fp)\n            assert exif == {\n                271: \"Canon\",\n                272: \"Canon PowerShot S40\",\n                274: 1,\n                282: 180.0,\n                283: 180.0,\n                296: 2,\n                306: \"2003:12:14 12:01:44\",\n                531: 1,\n                34665: 196,\n            }\n\n    def test_exif_hide_offsets(self) -> None:\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            exif = im.getexif()\n\n        # Check offsets are present initially\n        assert 0x8769 in exif\n        for tag in (0xA005, 0x927C):\n            assert tag in exif.get_ifd(0x8769)\n        assert exif.get_ifd(0xA005)\n        loaded_exif = exif\n\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            new_exif = im.getexif()\n\n            for exif in (loaded_exif, new_exif):\n                exif.hide_offsets()\n\n                # Assert they are hidden afterwards,\n                # but that the IFDs are still available\n                assert 0x8769 not in exif\n                assert exif.get_ifd(0x8769)\n                for tag in (0xA005, 0x927C):\n                    assert tag not in exif.get_ifd(0x8769)\n                assert exif.get_ifd(0xA005)\n\n    def test_empty_xmp(self) -> None:\n        with Image.open(\"Tests/images/hopper.gif\") as im:\n            assert im.getxmp() == {}\n\n    def test_getxmp_padded(self) -> None:\n        im = Image.new(\"RGB\", (1, 1))\n        im.info[\"xmp\"] = (\n            b'<?xpacket begin=\"\\xef\\xbb\\xbf\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\\n'\n            b'<x:xmpmeta xmlns:x=\"adobe:ns:meta/\" />\\n<?xpacket end=\"w\"?>\\x00\\x00'\n        )\n        if ElementTree is None:\n            with pytest.warns(\n                UserWarning,\n                match=\"XMP data cannot be read without defusedxml dependency\",\n            ):\n                assert im.getxmp() == {}\n        else:\n            assert im.getxmp() == {\"xmpmeta\": None}\n\n    @pytest.mark.parametrize(\"size\", ((1, 0), (0, 1), (0, 0)))\n    def test_zero_tobytes(self, size: tuple[int, int]) -> None:\n        im = Image.new(\"RGB\", size)\n        assert im.tobytes() == b\"\"\n\n    @pytest.mark.parametrize(\"size\", ((1, 0), (0, 1), (0, 0)))\n    def test_zero_frombytes(self, size: tuple[int, int]) -> None:\n        Image.frombytes(\"RGB\", size, b\"\")\n\n        im = Image.new(\"RGB\", size)\n        im.frombytes(b\"\")\n\n    def test_has_transparency_data(self) -> None:\n        for mode in (\"1\", \"L\", \"P\", \"RGB\"):\n            im = Image.new(mode, (1, 1))\n            assert not im.has_transparency_data\n\n        for mode in (\"LA\", \"La\", \"PA\", \"RGBA\", \"RGBa\"):\n            im = Image.new(mode, (1, 1))\n            assert im.has_transparency_data\n\n        # P mode with \"transparency\" info\n        with Image.open(\"Tests/images/first_frame_transparency.gif\") as im:\n            assert \"transparency\" in im.info\n            assert im.has_transparency_data\n\n        # RGB mode with \"transparency\" info\n        with Image.open(\"Tests/images/rgb_trns.png\") as im:\n            assert \"transparency\" in im.info\n            assert im.has_transparency_data\n\n        # P mode with RGBA palette\n        im = Image.new(\"RGBA\", (1, 1)).convert(\"P\")\n        assert im.mode == \"P\"\n        assert im.palette.mode == \"RGBA\"\n        assert im.has_transparency_data\n\n    def test_apply_transparency(self) -> None:\n        im = Image.new(\"P\", (1, 1))\n        im.putpalette((0, 0, 0, 1, 1, 1))\n        assert im.palette.colors == {(0, 0, 0): 0, (1, 1, 1): 1}\n\n        # Test that no transformation is applied without transparency\n        im.apply_transparency()\n        assert im.palette.colors == {(0, 0, 0): 0, (1, 1, 1): 1}\n\n        # Test that a transparency index is applied\n        im.info[\"transparency\"] = 0\n        im.apply_transparency()\n        assert \"transparency\" not in im.info\n        assert im.palette.colors == {(0, 0, 0, 0): 0, (1, 1, 1, 255): 1}\n\n        # Test that existing transparency is kept\n        im = Image.new(\"P\", (1, 1))\n        im.putpalette((0, 0, 0, 255, 1, 1, 1, 128), \"RGBA\")\n        im.info[\"transparency\"] = 0\n        im.apply_transparency()\n        assert im.palette.colors == {(0, 0, 0, 0): 0, (1, 1, 1, 128): 1}\n\n        # Test that transparency bytes are applied\n        with Image.open(\"Tests/images/pil123p.png\") as im:\n            assert isinstance(im.info[\"transparency\"], bytes)\n            assert im.palette.colors[(27, 35, 6)] == 24\n            im.apply_transparency()\n            assert im.palette.colors[(27, 35, 6, 214)] == 24\n\n    def test_constants(self) -> None:\n        for enum in (\n            Image.Transpose,\n            Image.Transform,\n            Image.Resampling,\n            Image.Dither,\n            Image.Palette,\n            Image.Quantize,\n        ):\n            for name in enum.__members__:\n                assert getattr(Image, name) == enum[name]\n\n    @pytest.mark.parametrize(\n        \"path\",\n        [\n            \"fli_overrun.bin\",\n            \"sgi_overrun.bin\",\n            \"sgi_overrun_expandrow.bin\",\n            \"sgi_overrun_expandrow2.bin\",\n            \"pcx_overrun.bin\",\n            \"pcx_overrun2.bin\",\n            \"ossfuzz-4836216264589312.pcx\",\n            \"01r_00.pcx\",\n        ],\n    )\n    def test_overrun(self, path: str) -> None:\n        \"\"\"For overrun completeness, test as:\n        valgrind pytest -qq Tests/test_image.py::TestImage::test_overrun | grep decode.c\n        \"\"\"\n        with Image.open(os.path.join(\"Tests/images\", path)) as im:\n            try:\n                im.load()\n                pytest.fail()\n            except OSError as e:\n                buffer_overrun = str(e) == \"buffer overrun when reading image file\"\n                truncated = \"image file is truncated\" in str(e)\n\n                assert buffer_overrun or truncated\n\n    def test_fli_overrun2(self) -> None:\n        with Image.open(\"Tests/images/fli_overrun2.bin\") as im:\n            try:\n                im.seek(1)\n                pytest.fail()\n            except OSError as e:\n                assert str(e) == \"buffer overrun when reading image file\"\n\n    def test_exit_fp(self) -> None:\n        with Image.new(\"L\", (1, 1)) as im:\n            pass\n        assert not hasattr(im, \"fp\")\n\n    def test_close_graceful(self, caplog: pytest.LogCaptureFixture) -> None:\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            copy = im.copy()\n            with caplog.at_level(logging.DEBUG):\n                im.close()\n                copy.close()\n            assert len(caplog.records) == 0\n            assert im.fp is None",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 55,
                            "end_lineno": 1080,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "Tests/test_image.py",
                            "type": "method",
                            "name": "TestImage.test_open_verbose_failure",
                            "content": "class TestImage:\n    @pytest.mark.parametrize(\"mode\", Image.MODES + [\"BGR;15\", \"BGR;16\", \"BGR;24\"])\n    def test_image_modes_success(self, mode: str) -> None:\n        helper_image_new(mode, (1, 1))\n\n    @pytest.mark.parametrize(\"mode\", (\"\", \"bad\", \"very very long\"))\n    def test_image_modes_fail(self, mode: str) -> None:\n        with pytest.raises(ValueError) as e:\n            Image.new(mode, (1, 1))\n        assert str(e.value) == \"unrecognized image mode\"\n\n    def test_exception_inheritance(self) -> None:\n        assert issubclass(UnidentifiedImageError, OSError)\n\n    def test_sanity(self) -> None:\n        im = Image.new(\"L\", (100, 100))\n        assert repr(im)[:45] == \"<PIL.Image.Image image mode=L size=100x100 at\"\n        assert im.mode == \"L\"\n        assert im.size == (100, 100)\n\n        im = Image.new(\"RGB\", (100, 100))\n        assert repr(im)[:45] == \"<PIL.Image.Image image mode=RGB size=100x100 \"\n        assert im.mode == \"RGB\"\n        assert im.size == (100, 100)\n\n        Image.new(\"L\", (100, 100), None)\n        im2 = Image.new(\"L\", (100, 100), 0)\n        im3 = Image.new(\"L\", (100, 100), \"black\")\n\n        assert im2.getcolors() == [(10000, 0)]\n        assert im3.getcolors() == [(10000, 0)]\n\n        with pytest.raises(ValueError):\n            Image.new(\"X\", (100, 100))\n        with pytest.raises(ValueError):\n            Image.new(\"\", (100, 100))\n        # with pytest.raises(MemoryError):\n        #   Image.new(\"L\", (1000000, 1000000))\n\n    def test_repr_pretty(self) -> None:\n        class Pretty:\n            def text(self, text: str) -> None:\n                self.pretty_output = text\n\n        im = Image.new(\"L\", (100, 100))\n\n        p = Pretty()\n        im._repr_pretty_(p, None)\n        assert p.pretty_output == \"<PIL.Image.Image image mode=L size=100x100>\"\n\n    def test_open_formats(self) -> None:\n        PNGFILE = \"Tests/images/hopper.png\"\n        JPGFILE = \"Tests/images/hopper.jpg\"\n\n        with pytest.raises(TypeError):\n            with Image.open(PNGFILE, formats=123):  # type: ignore[arg-type]\n                pass\n\n        format_list: list[list[str] | tuple[str, ...]] = [\n            [\"JPEG\"],\n            (\"JPEG\",),\n            [\"jpeg\"],\n            [\"Jpeg\"],\n            [\"jPeG\"],\n            [\"JpEg\"],\n        ]\n        for formats in format_list:\n            with pytest.raises(UnidentifiedImageError):\n                with Image.open(PNGFILE, formats=formats):\n                    pass\n\n            with Image.open(JPGFILE, formats=formats) as im:\n                assert im.mode == \"RGB\"\n                assert im.size == (128, 128)\n\n        for file in [PNGFILE, JPGFILE]:\n            with Image.open(file, formats=None) as im:\n                assert im.mode == \"RGB\"\n                assert im.size == (128, 128)\n\n    def test_open_verbose_failure(self, monkeypatch: pytest.MonkeyPatch) -> None:\n        monkeypatch.setattr(Image, \"WARN_POSSIBLE_FORMATS\", True)\n\n        im = io.BytesIO(b\"\")\n        with pytest.warns(UserWarning):\n            with pytest.raises(UnidentifiedImageError):\n                with Image.open(im):\n                    pass\n\n    def test_width_height(self) -> None:\n        im = Image.new(\"RGB\", (1, 2))\n        assert im.width == 1\n        assert im.height == 2\n\n        with pytest.raises(AttributeError):\n            im.size = (3, 4)  # type: ignore[misc]\n\n    def test_set_mode(self) -> None:\n        im = Image.new(\"RGB\", (1, 1))\n\n        with pytest.raises(AttributeError):\n            im.mode = \"P\"  # type: ignore[misc]\n\n    def test_invalid_image(self) -> None:\n        im = io.BytesIO(b\"\")\n        with pytest.raises(UnidentifiedImageError):\n            with Image.open(im):\n                pass\n\n    def test_bad_mode(self) -> None:\n        with pytest.raises(ValueError):\n            with Image.open(\"filename\", \"bad mode\"):  # type: ignore[arg-type]\n                pass\n\n    def test_stringio(self) -> None:\n        with pytest.raises(ValueError):\n            with Image.open(io.StringIO()):  # type: ignore[arg-type]\n                pass\n\n    def test_pathlib(self, tmp_path: Path) -> None:\n        with Image.open(Path(\"Tests/images/multipage-mmap.tiff\")) as im:\n            assert im.mode == \"P\"\n            assert im.size == (10, 10)\n\n        with Image.open(Path(\"Tests/images/hopper.jpg\")) as im:\n            assert im.mode == \"RGB\"\n            assert im.size == (128, 128)\n\n            for ext in (\".jpg\", \".jp2\"):\n                if ext == \".jp2\" and not features.check_codec(\"jpg_2000\"):\n                    pytest.skip(\"jpg_2000 not available\")\n                temp_file = str(tmp_path / (\"temp.\" + ext))\n                if os.path.exists(temp_file):\n                    os.remove(temp_file)\n                im.save(Path(temp_file))\n\n    def test_fp_name(self, tmp_path: Path) -> None:\n        temp_file = str(tmp_path / \"temp.jpg\")\n\n        class FP(io.BytesIO):\n            name: str\n\n            if sys.version_info >= (3, 12):\n                from collections.abc import Buffer\n\n                def write(self, data: Buffer) -> int:\n                    return len(data)\n\n            else:\n\n                def write(self, data: Any) -> int:\n                    return len(data)\n\n        fp = FP()\n        fp.name = temp_file\n\n        im = hopper()\n        im.save(fp)\n\n    def test_tempfile(self) -> None:\n        # see #1460, pathlib support breaks tempfile.TemporaryFile on py27\n        # Will error out on save on 3.0.0\n        im = hopper()\n        with tempfile.TemporaryFile() as fp:\n            im.save(fp, \"JPEG\")\n            fp.seek(0)\n            with Image.open(fp) as reloaded:\n                assert_image_similar(im, reloaded, 20)\n\n    def test_unknown_extension(self, tmp_path: Path) -> None:\n        im = hopper()\n        temp_file = str(tmp_path / \"temp.unknown\")\n        with pytest.raises(ValueError):\n            im.save(temp_file)\n\n    def test_internals(self) -> None:\n        im = Image.new(\"L\", (100, 100))\n        im.readonly = 1\n        im._copy()\n        assert not im.readonly\n\n        im.readonly = 1\n        im.paste(0, (0, 0, 100, 100))\n        assert not im.readonly\n\n    @pytest.mark.skipif(is_win32(), reason=\"Test requires opening tempfile twice\")\n    @pytest.mark.skipif(\n        sys.platform == \"cygwin\",\n        reason=\"Test requires opening an mmaped file for writing\",\n    )\n    def test_readonly_save(self, tmp_path: Path) -> None:\n        temp_file = str(tmp_path / \"temp.bmp\")\n        shutil.copy(\"Tests/images/rgb32bf-rgba.bmp\", temp_file)\n\n        with Image.open(temp_file) as im:\n            assert im.readonly\n            im.save(temp_file)\n\n    def test_dump(self, tmp_path: Path) -> None:\n        im = Image.new(\"L\", (10, 10))\n        im._dump(str(tmp_path / \"temp_L.ppm\"))\n\n        im = Image.new(\"RGB\", (10, 10))\n        im._dump(str(tmp_path / \"temp_RGB.ppm\"))\n\n        im = Image.new(\"HSV\", (10, 10))\n        with pytest.raises(ValueError):\n            im._dump(str(tmp_path / \"temp_HSV.ppm\"))\n\n    def test_comparison_with_other_type(self) -> None:\n        # Arrange\n        item = Image.new(\"RGB\", (25, 25), \"#000\")\n        num = 12\n\n        # Act/Assert\n        # Shouldn't cause AttributeError (#774)\n        assert item is not None\n        assert item != num\n\n    def test_expand_x(self) -> None:\n        # Arrange\n        im = hopper()\n        orig_size = im.size\n        xmargin = 5\n\n        # Act\n        im = im._expand(xmargin)\n\n        # Assert\n        assert im.size[0] == orig_size[0] + 2 * xmargin\n        assert im.size[1] == orig_size[1] + 2 * xmargin\n\n    def test_expand_xy(self) -> None:\n        # Arrange\n        im = hopper()\n        orig_size = im.size\n        xmargin = 5\n        ymargin = 3\n\n        # Act\n        im = im._expand(xmargin, ymargin)\n\n        # Assert\n        assert im.size[0] == orig_size[0] + 2 * xmargin\n        assert im.size[1] == orig_size[1] + 2 * ymargin\n\n    def test_getbands(self) -> None:\n        # Assert\n        assert hopper(\"RGB\").getbands() == (\"R\", \"G\", \"B\")\n        assert hopper(\"YCbCr\").getbands() == (\"Y\", \"Cb\", \"Cr\")\n\n    def test_getchannel_wrong_params(self) -> None:\n        im = hopper()\n\n        with pytest.raises(ValueError):\n            im.getchannel(-1)\n        with pytest.raises(ValueError):\n            im.getchannel(3)\n        with pytest.raises(ValueError):\n            im.getchannel(\"Z\")\n        with pytest.raises(ValueError):\n            im.getchannel(\"1\")\n\n    def test_getchannel(self) -> None:\n        im = hopper(\"YCbCr\")\n        Y, Cb, Cr = im.split()\n\n        assert_image_equal(Y, im.getchannel(0))\n        assert_image_equal(Y, im.getchannel(\"Y\"))\n        assert_image_equal(Cb, im.getchannel(1))\n        assert_image_equal(Cb, im.getchannel(\"Cb\"))\n        assert_image_equal(Cr, im.getchannel(2))\n        assert_image_equal(Cr, im.getchannel(\"Cr\"))\n\n    def test_getbbox(self) -> None:\n        # Arrange\n        im = hopper()\n\n        # Act\n        bbox = im.getbbox()\n\n        # Assert\n        assert bbox == (0, 0, 128, 128)\n\n    def test_ne(self) -> None:\n        # Arrange\n        im1 = Image.new(\"RGB\", (25, 25), \"black\")\n        im2 = Image.new(\"RGB\", (25, 25), \"white\")\n\n        # Act / Assert\n        assert im1 != im2\n\n    def test_alpha_composite(self) -> None:\n        # https://stackoverflow.com/questions/3374878\n        # Arrange\n        expected_colors = sorted(\n            [\n                (1122, (128, 127, 0, 255)),\n                (1089, (0, 255, 0, 255)),\n                (3300, (255, 0, 0, 255)),\n                (1156, (170, 85, 0, 192)),\n                (1122, (0, 255, 0, 128)),\n                (1122, (255, 0, 0, 128)),\n                (1089, (0, 255, 0, 0)),\n            ]\n        )\n\n        dst = Image.new(\"RGBA\", size=(100, 100), color=(0, 255, 0, 255))\n        draw = ImageDraw.Draw(dst)\n        draw.rectangle((0, 33, 100, 66), fill=(0, 255, 0, 128))\n        draw.rectangle((0, 67, 100, 100), fill=(0, 255, 0, 0))\n        src = Image.new(\"RGBA\", size=(100, 100), color=(255, 0, 0, 255))\n        draw = ImageDraw.Draw(src)\n        draw.rectangle((33, 0, 66, 100), fill=(255, 0, 0, 128))\n        draw.rectangle((67, 0, 100, 100), fill=(255, 0, 0, 0))\n\n        # Act\n        img = Image.alpha_composite(dst, src)\n\n        # Assert\n        img_colors = sorted(img.getcolors())\n        assert img_colors == expected_colors\n\n    def test_alpha_inplace(self) -> None:\n        src = Image.new(\"RGBA\", (128, 128), \"blue\")\n\n        over = Image.new(\"RGBA\", (128, 128), \"red\")\n        mask = hopper(\"L\")\n        over.putalpha(mask)\n\n        target = Image.alpha_composite(src, over)\n\n        # basic\n        full = src.copy()\n        full.alpha_composite(over)\n        assert_image_equal(full, target)\n\n        # with offset down to right\n        offset = src.copy()\n        offset.alpha_composite(over, (64, 64))\n        assert_image_equal(offset.crop((64, 64, 127, 127)), target.crop((0, 0, 63, 63)))\n        assert offset.size == (128, 128)\n\n        # with negative offset\n        offset = src.copy()\n        offset.alpha_composite(over, (-64, -64))\n        assert_image_equal(offset.crop((0, 0, 63, 63)), target.crop((64, 64, 127, 127)))\n        assert offset.size == (128, 128)\n\n        # offset and crop\n        box = src.copy()\n        box.alpha_composite(over, (64, 64), (0, 0, 32, 32))\n        assert_image_equal(box.crop((64, 64, 96, 96)), target.crop((0, 0, 32, 32)))\n        assert_image_equal(box.crop((96, 96, 128, 128)), src.crop((0, 0, 32, 32)))\n        assert box.size == (128, 128)\n\n        # source point\n        source = src.copy()\n        source.alpha_composite(over, (32, 32), (32, 32, 96, 96))\n\n        assert_image_equal(source.crop((32, 32, 96, 96)), target.crop((32, 32, 96, 96)))\n        assert source.size == (128, 128)\n\n        # errors\n        with pytest.raises(ValueError):\n            source.alpha_composite(over, \"invalid destination\")  # type: ignore[arg-type]\n        with pytest.raises(ValueError):\n            source.alpha_composite(over, (0, 0), \"invalid source\")  # type: ignore[arg-type]\n        with pytest.raises(ValueError):\n            source.alpha_composite(over, 0)  # type: ignore[arg-type]\n        with pytest.raises(ValueError):\n            source.alpha_composite(over, (0, 0), 0)  # type: ignore[arg-type]\n        with pytest.raises(ValueError):\n            source.alpha_composite(over, (0, 0), (0, -1))\n\n    def test_register_open_duplicates(self) -> None:\n        # Arrange\n        factory, accept = Image.OPEN[\"JPEG\"]\n        id_length = len(Image.ID)\n\n        # Act\n        Image.register_open(\"JPEG\", factory, accept)\n\n        # Assert\n        assert len(Image.ID) == id_length\n\n    def test_registered_extensions_uninitialized(self) -> None:\n        # Arrange\n        Image._initialized = 0\n\n        # Act\n        Image.registered_extensions()\n\n        # Assert\n        assert Image._initialized == 2\n\n    def test_registered_extensions(self) -> None:\n        # Arrange\n        # Open an image to trigger plugin registration\n        with Image.open(\"Tests/images/rgb.jpg\"):\n            pass\n\n        # Act\n        extensions = Image.registered_extensions()\n\n        # Assert\n        assert extensions\n        for ext in [\".cur\", \".icns\", \".tif\", \".tiff\"]:\n            assert ext in extensions\n\n    def test_effect_mandelbrot(self) -> None:\n        # Arrange\n        size = (512, 512)\n        extent = (-3, -2.5, 2, 2.5)\n        quality = 100\n\n        # Act\n        im = Image.effect_mandelbrot(size, extent, quality)\n\n        # Assert\n        assert im.size == (512, 512)\n        assert_image_equal_tofile(im, \"Tests/images/effect_mandelbrot.png\")\n\n    def test_effect_mandelbrot_bad_arguments(self) -> None:\n        # Arrange\n        size = (512, 512)\n        # Get coordinates the wrong way round:\n        extent = (+3, +2.5, -2, -2.5)\n        # Quality < 2:\n        quality = 1\n\n        # Act/Assert\n        with pytest.raises(ValueError):\n            Image.effect_mandelbrot(size, extent, quality)\n\n    def test_effect_noise(self) -> None:\n        # Arrange\n        size = (100, 100)\n        sigma = 128\n\n        # Act\n        im = Image.effect_noise(size, sigma)\n\n        # Assert\n        assert im.size == (100, 100)\n        assert im.mode == \"L\"\n        p0 = im.getpixel((0, 0))\n        p1 = im.getpixel((0, 1))\n        p2 = im.getpixel((0, 2))\n        p3 = im.getpixel((0, 3))\n        p4 = im.getpixel((0, 4))\n        assert_not_all_same([p0, p1, p2, p3, p4])\n\n    def test_effect_spread(self) -> None:\n        # Arrange\n        im = hopper()\n        distance = 10\n\n        # Act\n        im2 = im.effect_spread(distance)\n\n        # Assert\n        assert im.size == (128, 128)\n        assert_image_similar_tofile(im2, \"Tests/images/effect_spread.png\", 110)\n\n    def test_effect_spread_zero(self) -> None:\n        # Arrange\n        im = hopper()\n        distance = 0\n\n        # Act\n        im2 = im.effect_spread(distance)\n\n        # Assert\n        assert_image_equal(im, im2)\n\n    def test_check_size(self) -> None:\n        # Checking that the _check_size function throws value errors when we want it to\n        with pytest.raises(ValueError):\n            # not a tuple\n            Image.new(\"RGB\", 0)  # type: ignore[arg-type]\n        with pytest.raises(ValueError):\n            # tuple too short\n            Image.new(\"RGB\", (0,))  # type: ignore[arg-type]\n        with pytest.raises(ValueError):\n            Image.new(\"RGB\", (-1, -1))  # w,h < 0\n\n        # this should pass with 0 sized images, #2259\n        im = Image.new(\"L\", (0, 0))\n        assert im.size == (0, 0)\n\n        im = Image.new(\"L\", (0, 100))\n        assert im.size == (0, 100)\n\n        im = Image.new(\"L\", (100, 0))\n        assert im.size == (100, 0)\n\n        assert Image.new(\"RGB\", (1, 1))\n        # Should pass lists too\n        i = Image.new(\"RGB\", [1, 1])\n        assert isinstance(i.size, tuple)\n\n    @pytest.mark.timeout(0.75)\n    @pytest.mark.skipif(\n        \"PILLOW_VALGRIND_TEST\" in os.environ, reason=\"Valgrind is slower\"\n    )\n    @pytest.mark.parametrize(\"size\", ((0, 100000000), (100000000, 0)))\n    def test_empty_image(self, size: tuple[int, int]) -> None:\n        Image.new(\"RGB\", size)\n\n    def test_storage_neg(self) -> None:\n        # Storage.c accepted negative values for xsize, ysize.  Was\n        # test_neg_ppm, but the core function for that has been\n        # removed Calling directly into core to test the error in\n        # Storage.c, rather than the size check above\n\n        with pytest.raises(ValueError):\n            Image.core.fill(\"RGB\", (2, -2), (0, 0, 0))\n\n    def test_one_item_tuple(self) -> None:\n        for mode in (\"I\", \"F\", \"L\"):\n            im = Image.new(mode, (100, 100), (5,))\n            px = im.load()\n            assert px[0, 0] == 5\n\n    def test_linear_gradient_wrong_mode(self) -> None:\n        # Arrange\n        wrong_mode = \"RGB\"\n\n        # Act / Assert\n        with pytest.raises(ValueError):\n            Image.linear_gradient(wrong_mode)\n\n    @pytest.mark.parametrize(\"mode\", (\"L\", \"P\", \"I\", \"F\"))\n    def test_linear_gradient(self, mode: str) -> None:\n        # Arrange\n        target_file = \"Tests/images/linear_gradient.png\"\n\n        # Act\n        im = Image.linear_gradient(mode)\n\n        # Assert\n        assert im.size == (256, 256)\n        assert im.mode == mode\n        assert im.getpixel((0, 0)) == 0\n        assert im.getpixel((255, 255)) == 255\n        with Image.open(target_file) as target:\n            target = target.convert(mode)\n        assert_image_equal(im, target)\n\n    def test_radial_gradient_wrong_mode(self) -> None:\n        # Arrange\n        wrong_mode = \"RGB\"\n\n        # Act / Assert\n        with pytest.raises(ValueError):\n            Image.radial_gradient(wrong_mode)\n\n    @pytest.mark.parametrize(\"mode\", (\"L\", \"P\", \"I\", \"F\"))\n    def test_radial_gradient(self, mode: str) -> None:\n        # Arrange\n        target_file = \"Tests/images/radial_gradient.png\"\n\n        # Act\n        im = Image.radial_gradient(mode)\n\n        # Assert\n        assert im.size == (256, 256)\n        assert im.mode == mode\n        assert im.getpixel((0, 0)) == 255\n        assert im.getpixel((128, 128)) == 0\n        with Image.open(target_file) as target:\n            target = target.convert(mode)\n        assert_image_equal(im, target)\n\n    def test_register_extensions(self) -> None:\n        test_format = \"a\"\n        exts = [\"b\", \"c\"]\n        for ext in exts:\n            Image.register_extension(test_format, ext)\n        ext_individual = Image.EXTENSION.copy()\n        for ext in exts:\n            del Image.EXTENSION[ext]\n\n        Image.register_extensions(test_format, exts)\n        ext_multiple = Image.EXTENSION.copy()\n        for ext in exts:\n            del Image.EXTENSION[ext]\n\n        assert ext_individual == ext_multiple\n\n    def test_remap_palette(self) -> None:\n        # Test identity transform\n        with Image.open(\"Tests/images/hopper.gif\") as im:\n            assert_image_equal(im, im.remap_palette(list(range(256))))\n\n        # Test identity transform with an RGBA palette\n        im = Image.new(\"P\", (256, 1))\n        for x in range(256):\n            im.putpixel((x, 0), x)\n        im.putpalette(list(range(256)) * 4, \"RGBA\")\n        im_remapped = im.remap_palette(list(range(256)))\n        assert_image_equal(im, im_remapped)\n        assert im.palette.palette == im_remapped.palette.palette\n\n        # Test illegal image mode\n        with hopper() as im:\n            with pytest.raises(ValueError):\n                im.remap_palette(None)\n\n    def test_remap_palette_transparency(self) -> None:\n        im = Image.new(\"P\", (1, 2), (0, 0, 0))\n        im.putpixel((0, 1), (255, 0, 0))\n        im.info[\"transparency\"] = 0\n\n        im_remapped = im.remap_palette([1, 0])\n        assert im_remapped.info[\"transparency\"] == 1\n        assert len(im_remapped.getpalette()) == 6\n\n        # Test unused transparency\n        im.info[\"transparency\"] = 2\n\n        im_remapped = im.remap_palette([1, 0])\n        assert \"transparency\" not in im_remapped.info\n\n    def test__new(self) -> None:\n        im = hopper(\"RGB\")\n        im_p = hopper(\"P\")\n\n        blank_p = Image.new(\"P\", (10, 10))\n        blank_pa = Image.new(\"PA\", (10, 10))\n        blank_p.palette = None\n        blank_pa.palette = None\n\n        def _make_new(\n            base_image: Image.Image,\n            image: Image.Image,\n            palette_result: ImagePalette.ImagePalette | None = None,\n        ) -> None:\n            new_image = base_image._new(image.im)\n            assert new_image.mode == image.mode\n            assert new_image.size == image.size\n            assert new_image.info == base_image.info\n            if palette_result is not None:\n                assert new_image.palette.tobytes() == palette_result.tobytes()\n            else:\n                assert new_image.palette is None\n\n        _make_new(im, im_p, ImagePalette.ImagePalette(list(range(256)) * 3))\n        _make_new(im_p, im, None)\n        _make_new(im, blank_p, ImagePalette.ImagePalette())\n        _make_new(im, blank_pa, ImagePalette.ImagePalette())\n\n    @pytest.mark.parametrize(\n        \"mode, color\",\n        (\n            (\"RGB\", \"#DDEEFF\"),\n            (\"RGB\", (221, 238, 255)),\n            (\"RGBA\", (221, 238, 255, 255)),\n        ),\n    )\n    def test_p_from_rgb_rgba(self, mode: str, color: str | tuple[int, ...]) -> None:\n        im = Image.new(\"P\", (100, 100), color)\n        expected = Image.new(mode, (100, 100), color)\n        assert_image_equal(im.convert(mode), expected)\n\n    def test_no_resource_warning_on_save(self, tmp_path: Path) -> None:\n        # https://github.com/python-pillow/Pillow/issues/835\n        # Arrange\n        test_file = \"Tests/images/hopper.png\"\n        temp_file = str(tmp_path / \"temp.jpg\")\n\n        # Act/Assert\n        with Image.open(test_file) as im:\n            with warnings.catch_warnings():\n                im.save(temp_file)\n\n    def test_no_new_file_on_error(self, tmp_path: Path) -> None:\n        temp_file = str(tmp_path / \"temp.jpg\")\n\n        im = Image.new(\"RGB\", (0, 0))\n        with pytest.raises(ValueError):\n            im.save(temp_file)\n\n        assert not os.path.exists(temp_file)\n\n    def test_load_on_nonexclusive_multiframe(self) -> None:\n        with open(\"Tests/images/frozenpond.mpo\", \"rb\") as fp:\n\n            def act(fp: IO[bytes]) -> None:\n                im = Image.open(fp)\n                im.load()\n\n            act(fp)\n\n            with Image.open(fp) as im:\n                im.load()\n\n            assert not fp.closed\n\n    def test_empty_exif(self) -> None:\n        with Image.open(\"Tests/images/exif.png\") as im:\n            exif = im.getexif()\n        assert dict(exif)\n\n        # Test that exif data is cleared after another load\n        exif.load(None)\n        assert not dict(exif)\n\n        # Test loading just the EXIF header\n        exif.load(b\"Exif\\x00\\x00\")\n        assert not dict(exif)\n\n    @mark_if_feature_version(\n        pytest.mark.valgrind_known_error, \"libjpeg_turbo\", \"2.0\", reason=\"Known Failing\"\n    )\n    def test_exif_jpeg(self, tmp_path: Path) -> None:\n        with Image.open(\"Tests/images/exif-72dpi-int.jpg\") as im:  # Little endian\n            exif = im.getexif()\n            assert 258 not in exif\n            assert 274 in exif\n            assert 282 in exif\n            assert exif[296] == 2\n            assert exif[11] == \"gThumb 3.0.1\"\n\n            out = str(tmp_path / \"temp.jpg\")\n            exif[258] = 8\n            del exif[274]\n            del exif[282]\n            exif[296] = 455\n            exif[11] = \"Pillow test\"\n            im.save(out, exif=exif)\n        with Image.open(out) as reloaded:\n            reloaded_exif = reloaded.getexif()\n            assert reloaded_exif[258] == 8\n            assert 274 not in reloaded_exif\n            assert 282 not in reloaded_exif\n            assert reloaded_exif[296] == 455\n            assert reloaded_exif[11] == \"Pillow test\"\n\n        with Image.open(\"Tests/images/no-dpi-in-exif.jpg\") as im:  # Big endian\n            exif = im.getexif()\n            assert 258 not in exif\n            assert 306 in exif\n            assert exif[274] == 1\n            assert exif[305] == \"Adobe Photoshop CC 2017 (Macintosh)\"\n\n            out = str(tmp_path / \"temp.jpg\")\n            exif[258] = 8\n            del exif[306]\n            exif[274] = 455\n            exif[305] = \"Pillow test\"\n            im.save(out, exif=exif)\n        with Image.open(out) as reloaded:\n            reloaded_exif = reloaded.getexif()\n            assert reloaded_exif[258] == 8\n            assert 306 not in reloaded_exif\n            assert reloaded_exif[274] == 455\n            assert reloaded_exif[305] == \"Pillow test\"\n\n    @skip_unless_feature(\"webp\")\n    @skip_unless_feature(\"webp_anim\")\n    def test_exif_webp(self, tmp_path: Path) -> None:\n        with Image.open(\"Tests/images/hopper.webp\") as im:\n            exif = im.getexif()\n            assert exif == {}\n\n            out = str(tmp_path / \"temp.webp\")\n            exif[258] = 8\n            exif[40963] = 455\n            exif[305] = \"Pillow test\"\n\n            def check_exif() -> None:\n                with Image.open(out) as reloaded:\n                    reloaded_exif = reloaded.getexif()\n                    assert reloaded_exif[258] == 8\n                    assert reloaded_exif[40963] == 455\n                    assert reloaded_exif[305] == \"Pillow test\"\n\n            im.save(out, exif=exif)\n            check_exif()\n            im.save(out, exif=exif, save_all=True)\n            check_exif()\n\n    def test_exif_png(self, tmp_path: Path) -> None:\n        with Image.open(\"Tests/images/exif.png\") as im:\n            exif = im.getexif()\n            assert exif == {274: 1}\n\n            out = str(tmp_path / \"temp.png\")\n            exif[258] = 8\n            del exif[274]\n            exif[40963] = 455\n            exif[305] = \"Pillow test\"\n            im.save(out, exif=exif)\n\n        with Image.open(out) as reloaded:\n            reloaded_exif = reloaded.getexif()\n            assert reloaded_exif == {258: 8, 40963: 455, 305: \"Pillow test\"}\n\n    def test_exif_interop(self) -> None:\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            exif = im.getexif()\n            assert exif.get_ifd(0xA005) == {\n                1: \"R98\",\n                2: b\"0100\",\n                4097: 2272,\n                4098: 1704,\n            }\n\n            reloaded_exif = Image.Exif()\n            reloaded_exif.load(exif.tobytes())\n            assert reloaded_exif.get_ifd(0xA005) == exif.get_ifd(0xA005)\n\n    def test_exif_ifd1(self) -> None:\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            exif = im.getexif()\n            assert exif.get_ifd(ExifTags.IFD.IFD1) == {\n                513: 2036,\n                514: 5448,\n                259: 6,\n                296: 2,\n                282: 180.0,\n                283: 180.0,\n            }\n\n    def test_exif_ifd(self) -> None:\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            exif = im.getexif()\n        del exif.get_ifd(0x8769)[0xA005]\n\n        reloaded_exif = Image.Exif()\n        reloaded_exif.load(exif.tobytes())\n        assert reloaded_exif.get_ifd(0x8769) == exif.get_ifd(0x8769)\n\n    def test_exif_load_from_fp(self) -> None:\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            data = im.info[\"exif\"]\n            if data.startswith(b\"Exif\\x00\\x00\"):\n                data = data[6:]\n            fp = io.BytesIO(data)\n\n            exif = Image.Exif()\n            exif.load_from_fp(fp)\n            assert exif == {\n                271: \"Canon\",\n                272: \"Canon PowerShot S40\",\n                274: 1,\n                282: 180.0,\n                283: 180.0,\n                296: 2,\n                306: \"2003:12:14 12:01:44\",\n                531: 1,\n                34665: 196,\n            }\n\n    def test_exif_hide_offsets(self) -> None:\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            exif = im.getexif()\n\n        # Check offsets are present initially\n        assert 0x8769 in exif\n        for tag in (0xA005, 0x927C):\n            assert tag in exif.get_ifd(0x8769)\n        assert exif.get_ifd(0xA005)\n        loaded_exif = exif\n\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            new_exif = im.getexif()\n\n            for exif in (loaded_exif, new_exif):\n                exif.hide_offsets()\n\n                # Assert they are hidden afterwards,\n                # but that the IFDs are still available\n                assert 0x8769 not in exif\n                assert exif.get_ifd(0x8769)\n                for tag in (0xA005, 0x927C):\n                    assert tag not in exif.get_ifd(0x8769)\n                assert exif.get_ifd(0xA005)\n\n    def test_empty_xmp(self) -> None:\n        with Image.open(\"Tests/images/hopper.gif\") as im:\n            assert im.getxmp() == {}\n\n    def test_getxmp_padded(self) -> None:\n        im = Image.new(\"RGB\", (1, 1))\n        im.info[\"xmp\"] = (\n            b'<?xpacket begin=\"\\xef\\xbb\\xbf\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\\n'\n            b'<x:xmpmeta xmlns:x=\"adobe:ns:meta/\" />\\n<?xpacket end=\"w\"?>\\x00\\x00'\n        )\n        if ElementTree is None:\n            with pytest.warns(\n                UserWarning,\n                match=\"XMP data cannot be read without defusedxml dependency\",\n            ):\n                assert im.getxmp() == {}\n        else:\n            assert im.getxmp() == {\"xmpmeta\": None}\n\n    @pytest.mark.parametrize(\"size\", ((1, 0), (0, 1), (0, 0)))\n    def test_zero_tobytes(self, size: tuple[int, int]) -> None:\n        im = Image.new(\"RGB\", size)\n        assert im.tobytes() == b\"\"\n\n    @pytest.mark.parametrize(\"size\", ((1, 0), (0, 1), (0, 0)))\n    def test_zero_frombytes(self, size: tuple[int, int]) -> None:\n        Image.frombytes(\"RGB\", size, b\"\")\n\n        im = Image.new(\"RGB\", size)\n        im.frombytes(b\"\")\n\n    def test_has_transparency_data(self) -> None:\n        for mode in (\"1\", \"L\", \"P\", \"RGB\"):\n            im = Image.new(mode, (1, 1))\n            assert not im.has_transparency_data\n\n        for mode in (\"LA\", \"La\", \"PA\", \"RGBA\", \"RGBa\"):\n            im = Image.new(mode, (1, 1))\n            assert im.has_transparency_data\n\n        # P mode with \"transparency\" info\n        with Image.open(\"Tests/images/first_frame_transparency.gif\") as im:\n            assert \"transparency\" in im.info\n            assert im.has_transparency_data\n\n        # RGB mode with \"transparency\" info\n        with Image.open(\"Tests/images/rgb_trns.png\") as im:\n            assert \"transparency\" in im.info\n            assert im.has_transparency_data\n\n        # P mode with RGBA palette\n        im = Image.new(\"RGBA\", (1, 1)).convert(\"P\")\n        assert im.mode == \"P\"\n        assert im.palette.mode == \"RGBA\"\n        assert im.has_transparency_data\n\n    def test_apply_transparency(self) -> None:\n        im = Image.new(\"P\", (1, 1))\n        im.putpalette((0, 0, 0, 1, 1, 1))\n        assert im.palette.colors == {(0, 0, 0): 0, (1, 1, 1): 1}\n\n        # Test that no transformation is applied without transparency\n        im.apply_transparency()\n        assert im.palette.colors == {(0, 0, 0): 0, (1, 1, 1): 1}\n\n        # Test that a transparency index is applied\n        im.info[\"transparency\"] = 0\n        im.apply_transparency()\n        assert \"transparency\" not in im.info\n        assert im.palette.colors == {(0, 0, 0, 0): 0, (1, 1, 1, 255): 1}\n\n        # Test that existing transparency is kept\n        im = Image.new(\"P\", (1, 1))\n        im.putpalette((0, 0, 0, 255, 1, 1, 1, 128), \"RGBA\")\n        im.info[\"transparency\"] = 0\n        im.apply_transparency()\n        assert im.palette.colors == {(0, 0, 0, 0): 0, (1, 1, 1, 128): 1}\n\n        # Test that transparency bytes are applied\n        with Image.open(\"Tests/images/pil123p.png\") as im:\n            assert isinstance(im.info[\"transparency\"], bytes)\n            assert im.palette.colors[(27, 35, 6)] == 24\n            im.apply_transparency()\n            assert im.palette.colors[(27, 35, 6, 214)] == 24\n\n    def test_constants(self) -> None:\n        for enum in (\n            Image.Transpose,\n            Image.Transform,\n            Image.Resampling,\n            Image.Dither,\n            Image.Palette,\n            Image.Quantize,\n        ):\n            for name in enum.__members__:\n                assert getattr(Image, name) == enum[name]\n\n    @pytest.mark.parametrize(\n        \"path\",\n        [\n            \"fli_overrun.bin\",\n            \"sgi_overrun.bin\",\n            \"sgi_overrun_expandrow.bin\",\n            \"sgi_overrun_expandrow2.bin\",\n            \"pcx_overrun.bin\",\n            \"pcx_overrun2.bin\",\n            \"ossfuzz-4836216264589312.pcx\",\n            \"01r_00.pcx\",\n        ],\n    )\n    def test_overrun(self, path: str) -> None:\n        \"\"\"For overrun completeness, test as:\n        valgrind pytest -qq Tests/test_image.py::TestImage::test_overrun | grep decode.c\n        \"\"\"\n        with Image.open(os.path.join(\"Tests/images\", path)) as im:\n            try:\n                im.load()\n                pytest.fail()\n            except OSError as e:\n                buffer_overrun = str(e) == \"buffer overrun when reading image file\"\n                truncated = \"image file is truncated\" in str(e)\n\n                assert buffer_overrun or truncated\n\n    def test_fli_overrun2(self) -> None:\n        with Image.open(\"Tests/images/fli_overrun2.bin\") as im:\n            try:\n                im.seek(1)\n                pytest.fail()\n            except OSError as e:\n                assert str(e) == \"buffer overrun when reading image file\"\n\n    def test_exit_fp(self) -> None:\n        with Image.new(\"L\", (1, 1)) as im:\n            pass\n        assert not hasattr(im, \"fp\")\n\n    def test_close_graceful(self, caplog: pytest.LogCaptureFixture) -> None:\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            copy = im.copy()\n            with caplog.at_level(logging.DEBUG):\n                im.close()\n                copy.close()\n            assert len(caplog.records) == 0\n            assert im.fp is None",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 135,
                            "end_lineno": 142,
                            "parent": {
                                "file_name": "Tests/test_image.py",
                                "type": "class",
                                "name": "TestImage",
                                "content": "class TestImage:\n    @pytest.mark.parametrize(\"mode\", Image.MODES + [\"BGR;15\", \"BGR;16\", \"BGR;24\"])\n    def test_image_modes_success(self, mode: str) -> None:\n        helper_image_new(mode, (1, 1))\n\n    @pytest.mark.parametrize(\"mode\", (\"\", \"bad\", \"very very long\"))\n    def test_image_modes_fail(self, mode: str) -> None:\n        with pytest.raises(ValueError) as e:\n            Image.new(mode, (1, 1))\n        assert str(e.value) == \"unrecognized image mode\"\n\n    def test_exception_inheritance(self) -> None:\n        assert issubclass(UnidentifiedImageError, OSError)\n\n    def test_sanity(self) -> None:\n        im = Image.new(\"L\", (100, 100))\n        assert repr(im)[:45] == \"<PIL.Image.Image image mode=L size=100x100 at\"\n        assert im.mode == \"L\"\n        assert im.size == (100, 100)\n\n        im = Image.new(\"RGB\", (100, 100))\n        assert repr(im)[:45] == \"<PIL.Image.Image image mode=RGB size=100x100 \"\n        assert im.mode == \"RGB\"\n        assert im.size == (100, 100)\n\n        Image.new(\"L\", (100, 100), None)\n        im2 = Image.new(\"L\", (100, 100), 0)\n        im3 = Image.new(\"L\", (100, 100), \"black\")\n\n        assert im2.getcolors() == [(10000, 0)]\n        assert im3.getcolors() == [(10000, 0)]\n\n        with pytest.raises(ValueError):\n            Image.new(\"X\", (100, 100))\n        with pytest.raises(ValueError):\n            Image.new(\"\", (100, 100))\n        # with pytest.raises(MemoryError):\n        #   Image.new(\"L\", (1000000, 1000000))\n\n    def test_repr_pretty(self) -> None:\n        class Pretty:\n            def text(self, text: str) -> None:\n                self.pretty_output = text\n\n        im = Image.new(\"L\", (100, 100))\n\n        p = Pretty()\n        im._repr_pretty_(p, None)\n        assert p.pretty_output == \"<PIL.Image.Image image mode=L size=100x100>\"\n\n    def test_open_formats(self) -> None:\n        PNGFILE = \"Tests/images/hopper.png\"\n        JPGFILE = \"Tests/images/hopper.jpg\"\n\n        with pytest.raises(TypeError):\n            with Image.open(PNGFILE, formats=123):  # type: ignore[arg-type]\n                pass\n\n        format_list: list[list[str] | tuple[str, ...]] = [\n            [\"JPEG\"],\n            (\"JPEG\",),\n            [\"jpeg\"],\n            [\"Jpeg\"],\n            [\"jPeG\"],\n            [\"JpEg\"],\n        ]\n        for formats in format_list:\n            with pytest.raises(UnidentifiedImageError):\n                with Image.open(PNGFILE, formats=formats):\n                    pass\n\n            with Image.open(JPGFILE, formats=formats) as im:\n                assert im.mode == \"RGB\"\n                assert im.size == (128, 128)\n\n        for file in [PNGFILE, JPGFILE]:\n            with Image.open(file, formats=None) as im:\n                assert im.mode == \"RGB\"\n                assert im.size == (128, 128)\n\n    def test_open_verbose_failure(self, monkeypatch: pytest.MonkeyPatch) -> None:\n        monkeypatch.setattr(Image, \"WARN_POSSIBLE_FORMATS\", True)\n\n        im = io.BytesIO(b\"\")\n        with pytest.warns(UserWarning):\n            with pytest.raises(UnidentifiedImageError):\n                with Image.open(im):\n                    pass\n\n    def test_width_height(self) -> None:\n        im = Image.new(\"RGB\", (1, 2))\n        assert im.width == 1\n        assert im.height == 2\n\n        with pytest.raises(AttributeError):\n            im.size = (3, 4)  # type: ignore[misc]\n\n    def test_set_mode(self) -> None:\n        im = Image.new(\"RGB\", (1, 1))\n\n        with pytest.raises(AttributeError):\n            im.mode = \"P\"  # type: ignore[misc]\n\n    def test_invalid_image(self) -> None:\n        im = io.BytesIO(b\"\")\n        with pytest.raises(UnidentifiedImageError):\n            with Image.open(im):\n                pass\n\n    def test_bad_mode(self) -> None:\n        with pytest.raises(ValueError):\n            with Image.open(\"filename\", \"bad mode\"):  # type: ignore[arg-type]\n                pass\n\n    def test_stringio(self) -> None:\n        with pytest.raises(ValueError):\n            with Image.open(io.StringIO()):  # type: ignore[arg-type]\n                pass\n\n    def test_pathlib(self, tmp_path: Path) -> None:\n        with Image.open(Path(\"Tests/images/multipage-mmap.tiff\")) as im:\n            assert im.mode == \"P\"\n            assert im.size == (10, 10)\n\n        with Image.open(Path(\"Tests/images/hopper.jpg\")) as im:\n            assert im.mode == \"RGB\"\n            assert im.size == (128, 128)\n\n            for ext in (\".jpg\", \".jp2\"):\n                if ext == \".jp2\" and not features.check_codec(\"jpg_2000\"):\n                    pytest.skip(\"jpg_2000 not available\")\n                temp_file = str(tmp_path / (\"temp.\" + ext))\n                if os.path.exists(temp_file):\n                    os.remove(temp_file)\n                im.save(Path(temp_file))\n\n    def test_fp_name(self, tmp_path: Path) -> None:\n        temp_file = str(tmp_path / \"temp.jpg\")\n\n        class FP(io.BytesIO):\n            name: str\n\n            if sys.version_info >= (3, 12):\n                from collections.abc import Buffer\n\n                def write(self, data: Buffer) -> int:\n                    return len(data)\n\n            else:\n\n                def write(self, data: Any) -> int:\n                    return len(data)\n\n        fp = FP()\n        fp.name = temp_file\n\n        im = hopper()\n        im.save(fp)\n\n    def test_tempfile(self) -> None:\n        # see #1460, pathlib support breaks tempfile.TemporaryFile on py27\n        # Will error out on save on 3.0.0\n        im = hopper()\n        with tempfile.TemporaryFile() as fp:\n            im.save(fp, \"JPEG\")\n            fp.seek(0)\n            with Image.open(fp) as reloaded:\n                assert_image_similar(im, reloaded, 20)\n\n    def test_unknown_extension(self, tmp_path: Path) -> None:\n        im = hopper()\n        temp_file = str(tmp_path / \"temp.unknown\")\n        with pytest.raises(ValueError):\n            im.save(temp_file)\n\n    def test_internals(self) -> None:\n        im = Image.new(\"L\", (100, 100))\n        im.readonly = 1\n        im._copy()\n        assert not im.readonly\n\n        im.readonly = 1\n        im.paste(0, (0, 0, 100, 100))\n        assert not im.readonly\n\n    @pytest.mark.skipif(is_win32(), reason=\"Test requires opening tempfile twice\")\n    @pytest.mark.skipif(\n        sys.platform == \"cygwin\",\n        reason=\"Test requires opening an mmaped file for writing\",\n    )\n    def test_readonly_save(self, tmp_path: Path) -> None:\n        temp_file = str(tmp_path / \"temp.bmp\")\n        shutil.copy(\"Tests/images/rgb32bf-rgba.bmp\", temp_file)\n\n        with Image.open(temp_file) as im:\n            assert im.readonly\n            im.save(temp_file)\n\n    def test_dump(self, tmp_path: Path) -> None:\n        im = Image.new(\"L\", (10, 10))\n        im._dump(str(tmp_path / \"temp_L.ppm\"))\n\n        im = Image.new(\"RGB\", (10, 10))\n        im._dump(str(tmp_path / \"temp_RGB.ppm\"))\n\n        im = Image.new(\"HSV\", (10, 10))\n        with pytest.raises(ValueError):\n            im._dump(str(tmp_path / \"temp_HSV.ppm\"))\n\n    def test_comparison_with_other_type(self) -> None:\n        # Arrange\n        item = Image.new(\"RGB\", (25, 25), \"#000\")\n        num = 12\n\n        # Act/Assert\n        # Shouldn't cause AttributeError (#774)\n        assert item is not None\n        assert item != num\n\n    def test_expand_x(self) -> None:\n        # Arrange\n        im = hopper()\n        orig_size = im.size\n        xmargin = 5\n\n        # Act\n        im = im._expand(xmargin)\n\n        # Assert\n        assert im.size[0] == orig_size[0] + 2 * xmargin\n        assert im.size[1] == orig_size[1] + 2 * xmargin\n\n    def test_expand_xy(self) -> None:\n        # Arrange\n        im = hopper()\n        orig_size = im.size\n        xmargin = 5\n        ymargin = 3\n\n        # Act\n        im = im._expand(xmargin, ymargin)\n\n        # Assert\n        assert im.size[0] == orig_size[0] + 2 * xmargin\n        assert im.size[1] == orig_size[1] + 2 * ymargin\n\n    def test_getbands(self) -> None:\n        # Assert\n        assert hopper(\"RGB\").getbands() == (\"R\", \"G\", \"B\")\n        assert hopper(\"YCbCr\").getbands() == (\"Y\", \"Cb\", \"Cr\")\n\n    def test_getchannel_wrong_params(self) -> None:\n        im = hopper()\n\n        with pytest.raises(ValueError):\n            im.getchannel(-1)\n        with pytest.raises(ValueError):\n            im.getchannel(3)\n        with pytest.raises(ValueError):\n            im.getchannel(\"Z\")\n        with pytest.raises(ValueError):\n            im.getchannel(\"1\")\n\n    def test_getchannel(self) -> None:\n        im = hopper(\"YCbCr\")\n        Y, Cb, Cr = im.split()\n\n        assert_image_equal(Y, im.getchannel(0))\n        assert_image_equal(Y, im.getchannel(\"Y\"))\n        assert_image_equal(Cb, im.getchannel(1))\n        assert_image_equal(Cb, im.getchannel(\"Cb\"))\n        assert_image_equal(Cr, im.getchannel(2))\n        assert_image_equal(Cr, im.getchannel(\"Cr\"))\n\n    def test_getbbox(self) -> None:\n        # Arrange\n        im = hopper()\n\n        # Act\n        bbox = im.getbbox()\n\n        # Assert\n        assert bbox == (0, 0, 128, 128)\n\n    def test_ne(self) -> None:\n        # Arrange\n        im1 = Image.new(\"RGB\", (25, 25), \"black\")\n        im2 = Image.new(\"RGB\", (25, 25), \"white\")\n\n        # Act / Assert\n        assert im1 != im2\n\n    def test_alpha_composite(self) -> None:\n        # https://stackoverflow.com/questions/3374878\n        # Arrange\n        expected_colors = sorted(\n            [\n                (1122, (128, 127, 0, 255)),\n                (1089, (0, 255, 0, 255)),\n                (3300, (255, 0, 0, 255)),\n                (1156, (170, 85, 0, 192)),\n                (1122, (0, 255, 0, 128)),\n                (1122, (255, 0, 0, 128)),\n                (1089, (0, 255, 0, 0)),\n            ]\n        )\n\n        dst = Image.new(\"RGBA\", size=(100, 100), color=(0, 255, 0, 255))\n        draw = ImageDraw.Draw(dst)\n        draw.rectangle((0, 33, 100, 66), fill=(0, 255, 0, 128))\n        draw.rectangle((0, 67, 100, 100), fill=(0, 255, 0, 0))\n        src = Image.new(\"RGBA\", size=(100, 100), color=(255, 0, 0, 255))\n        draw = ImageDraw.Draw(src)\n        draw.rectangle((33, 0, 66, 100), fill=(255, 0, 0, 128))\n        draw.rectangle((67, 0, 100, 100), fill=(255, 0, 0, 0))\n\n        # Act\n        img = Image.alpha_composite(dst, src)\n\n        # Assert\n        img_colors = sorted(img.getcolors())\n        assert img_colors == expected_colors\n\n    def test_alpha_inplace(self) -> None:\n        src = Image.new(\"RGBA\", (128, 128), \"blue\")\n\n        over = Image.new(\"RGBA\", (128, 128), \"red\")\n        mask = hopper(\"L\")\n        over.putalpha(mask)\n\n        target = Image.alpha_composite(src, over)\n\n        # basic\n        full = src.copy()\n        full.alpha_composite(over)\n        assert_image_equal(full, target)\n\n        # with offset down to right\n        offset = src.copy()\n        offset.alpha_composite(over, (64, 64))\n        assert_image_equal(offset.crop((64, 64, 127, 127)), target.crop((0, 0, 63, 63)))\n        assert offset.size == (128, 128)\n\n        # with negative offset\n        offset = src.copy()\n        offset.alpha_composite(over, (-64, -64))\n        assert_image_equal(offset.crop((0, 0, 63, 63)), target.crop((64, 64, 127, 127)))\n        assert offset.size == (128, 128)\n\n        # offset and crop\n        box = src.copy()\n        box.alpha_composite(over, (64, 64), (0, 0, 32, 32))\n        assert_image_equal(box.crop((64, 64, 96, 96)), target.crop((0, 0, 32, 32)))\n        assert_image_equal(box.crop((96, 96, 128, 128)), src.crop((0, 0, 32, 32)))\n        assert box.size == (128, 128)\n\n        # source point\n        source = src.copy()\n        source.alpha_composite(over, (32, 32), (32, 32, 96, 96))\n\n        assert_image_equal(source.crop((32, 32, 96, 96)), target.crop((32, 32, 96, 96)))\n        assert source.size == (128, 128)\n\n        # errors\n        with pytest.raises(ValueError):\n            source.alpha_composite(over, \"invalid destination\")  # type: ignore[arg-type]\n        with pytest.raises(ValueError):\n            source.alpha_composite(over, (0, 0), \"invalid source\")  # type: ignore[arg-type]\n        with pytest.raises(ValueError):\n            source.alpha_composite(over, 0)  # type: ignore[arg-type]\n        with pytest.raises(ValueError):\n            source.alpha_composite(over, (0, 0), 0)  # type: ignore[arg-type]\n        with pytest.raises(ValueError):\n            source.alpha_composite(over, (0, 0), (0, -1))\n\n    def test_register_open_duplicates(self) -> None:\n        # Arrange\n        factory, accept = Image.OPEN[\"JPEG\"]\n        id_length = len(Image.ID)\n\n        # Act\n        Image.register_open(\"JPEG\", factory, accept)\n\n        # Assert\n        assert len(Image.ID) == id_length\n\n    def test_registered_extensions_uninitialized(self) -> None:\n        # Arrange\n        Image._initialized = 0\n\n        # Act\n        Image.registered_extensions()\n\n        # Assert\n        assert Image._initialized == 2\n\n    def test_registered_extensions(self) -> None:\n        # Arrange\n        # Open an image to trigger plugin registration\n        with Image.open(\"Tests/images/rgb.jpg\"):\n            pass\n\n        # Act\n        extensions = Image.registered_extensions()\n\n        # Assert\n        assert extensions\n        for ext in [\".cur\", \".icns\", \".tif\", \".tiff\"]:\n            assert ext in extensions\n\n    def test_effect_mandelbrot(self) -> None:\n        # Arrange\n        size = (512, 512)\n        extent = (-3, -2.5, 2, 2.5)\n        quality = 100\n\n        # Act\n        im = Image.effect_mandelbrot(size, extent, quality)\n\n        # Assert\n        assert im.size == (512, 512)\n        assert_image_equal_tofile(im, \"Tests/images/effect_mandelbrot.png\")\n\n    def test_effect_mandelbrot_bad_arguments(self) -> None:\n        # Arrange\n        size = (512, 512)\n        # Get coordinates the wrong way round:\n        extent = (+3, +2.5, -2, -2.5)\n        # Quality < 2:\n        quality = 1\n\n        # Act/Assert\n        with pytest.raises(ValueError):\n            Image.effect_mandelbrot(size, extent, quality)\n\n    def test_effect_noise(self) -> None:\n        # Arrange\n        size = (100, 100)\n        sigma = 128\n\n        # Act\n        im = Image.effect_noise(size, sigma)\n\n        # Assert\n        assert im.size == (100, 100)\n        assert im.mode == \"L\"\n        p0 = im.getpixel((0, 0))\n        p1 = im.getpixel((0, 1))\n        p2 = im.getpixel((0, 2))\n        p3 = im.getpixel((0, 3))\n        p4 = im.getpixel((0, 4))\n        assert_not_all_same([p0, p1, p2, p3, p4])\n\n    def test_effect_spread(self) -> None:\n        # Arrange\n        im = hopper()\n        distance = 10\n\n        # Act\n        im2 = im.effect_spread(distance)\n\n        # Assert\n        assert im.size == (128, 128)\n        assert_image_similar_tofile(im2, \"Tests/images/effect_spread.png\", 110)\n\n    def test_effect_spread_zero(self) -> None:\n        # Arrange\n        im = hopper()\n        distance = 0\n\n        # Act\n        im2 = im.effect_spread(distance)\n\n        # Assert\n        assert_image_equal(im, im2)\n\n    def test_check_size(self) -> None:\n        # Checking that the _check_size function throws value errors when we want it to\n        with pytest.raises(ValueError):\n            # not a tuple\n            Image.new(\"RGB\", 0)  # type: ignore[arg-type]\n        with pytest.raises(ValueError):\n            # tuple too short\n            Image.new(\"RGB\", (0,))  # type: ignore[arg-type]\n        with pytest.raises(ValueError):\n            Image.new(\"RGB\", (-1, -1))  # w,h < 0\n\n        # this should pass with 0 sized images, #2259\n        im = Image.new(\"L\", (0, 0))\n        assert im.size == (0, 0)\n\n        im = Image.new(\"L\", (0, 100))\n        assert im.size == (0, 100)\n\n        im = Image.new(\"L\", (100, 0))\n        assert im.size == (100, 0)\n\n        assert Image.new(\"RGB\", (1, 1))\n        # Should pass lists too\n        i = Image.new(\"RGB\", [1, 1])\n        assert isinstance(i.size, tuple)\n\n    @pytest.mark.timeout(0.75)\n    @pytest.mark.skipif(\n        \"PILLOW_VALGRIND_TEST\" in os.environ, reason=\"Valgrind is slower\"\n    )\n    @pytest.mark.parametrize(\"size\", ((0, 100000000), (100000000, 0)))\n    def test_empty_image(self, size: tuple[int, int]) -> None:\n        Image.new(\"RGB\", size)\n\n    def test_storage_neg(self) -> None:\n        # Storage.c accepted negative values for xsize, ysize.  Was\n        # test_neg_ppm, but the core function for that has been\n        # removed Calling directly into core to test the error in\n        # Storage.c, rather than the size check above\n\n        with pytest.raises(ValueError):\n            Image.core.fill(\"RGB\", (2, -2), (0, 0, 0))\n\n    def test_one_item_tuple(self) -> None:\n        for mode in (\"I\", \"F\", \"L\"):\n            im = Image.new(mode, (100, 100), (5,))\n            px = im.load()\n            assert px[0, 0] == 5\n\n    def test_linear_gradient_wrong_mode(self) -> None:\n        # Arrange\n        wrong_mode = \"RGB\"\n\n        # Act / Assert\n        with pytest.raises(ValueError):\n            Image.linear_gradient(wrong_mode)\n\n    @pytest.mark.parametrize(\"mode\", (\"L\", \"P\", \"I\", \"F\"))\n    def test_linear_gradient(self, mode: str) -> None:\n        # Arrange\n        target_file = \"Tests/images/linear_gradient.png\"\n\n        # Act\n        im = Image.linear_gradient(mode)\n\n        # Assert\n        assert im.size == (256, 256)\n        assert im.mode == mode\n        assert im.getpixel((0, 0)) == 0\n        assert im.getpixel((255, 255)) == 255\n        with Image.open(target_file) as target:\n            target = target.convert(mode)\n        assert_image_equal(im, target)\n\n    def test_radial_gradient_wrong_mode(self) -> None:\n        # Arrange\n        wrong_mode = \"RGB\"\n\n        # Act / Assert\n        with pytest.raises(ValueError):\n            Image.radial_gradient(wrong_mode)\n\n    @pytest.mark.parametrize(\"mode\", (\"L\", \"P\", \"I\", \"F\"))\n    def test_radial_gradient(self, mode: str) -> None:\n        # Arrange\n        target_file = \"Tests/images/radial_gradient.png\"\n\n        # Act\n        im = Image.radial_gradient(mode)\n\n        # Assert\n        assert im.size == (256, 256)\n        assert im.mode == mode\n        assert im.getpixel((0, 0)) == 255\n        assert im.getpixel((128, 128)) == 0\n        with Image.open(target_file) as target:\n            target = target.convert(mode)\n        assert_image_equal(im, target)\n\n    def test_register_extensions(self) -> None:\n        test_format = \"a\"\n        exts = [\"b\", \"c\"]\n        for ext in exts:\n            Image.register_extension(test_format, ext)\n        ext_individual = Image.EXTENSION.copy()\n        for ext in exts:\n            del Image.EXTENSION[ext]\n\n        Image.register_extensions(test_format, exts)\n        ext_multiple = Image.EXTENSION.copy()\n        for ext in exts:\n            del Image.EXTENSION[ext]\n\n        assert ext_individual == ext_multiple\n\n    def test_remap_palette(self) -> None:\n        # Test identity transform\n        with Image.open(\"Tests/images/hopper.gif\") as im:\n            assert_image_equal(im, im.remap_palette(list(range(256))))\n\n        # Test identity transform with an RGBA palette\n        im = Image.new(\"P\", (256, 1))\n        for x in range(256):\n            im.putpixel((x, 0), x)\n        im.putpalette(list(range(256)) * 4, \"RGBA\")\n        im_remapped = im.remap_palette(list(range(256)))\n        assert_image_equal(im, im_remapped)\n        assert im.palette.palette == im_remapped.palette.palette\n\n        # Test illegal image mode\n        with hopper() as im:\n            with pytest.raises(ValueError):\n                im.remap_palette(None)\n\n    def test_remap_palette_transparency(self) -> None:\n        im = Image.new(\"P\", (1, 2), (0, 0, 0))\n        im.putpixel((0, 1), (255, 0, 0))\n        im.info[\"transparency\"] = 0\n\n        im_remapped = im.remap_palette([1, 0])\n        assert im_remapped.info[\"transparency\"] == 1\n        assert len(im_remapped.getpalette()) == 6\n\n        # Test unused transparency\n        im.info[\"transparency\"] = 2\n\n        im_remapped = im.remap_palette([1, 0])\n        assert \"transparency\" not in im_remapped.info\n\n    def test__new(self) -> None:\n        im = hopper(\"RGB\")\n        im_p = hopper(\"P\")\n\n        blank_p = Image.new(\"P\", (10, 10))\n        blank_pa = Image.new(\"PA\", (10, 10))\n        blank_p.palette = None\n        blank_pa.palette = None\n\n        def _make_new(\n            base_image: Image.Image,\n            image: Image.Image,\n            palette_result: ImagePalette.ImagePalette | None = None,\n        ) -> None:\n            new_image = base_image._new(image.im)\n            assert new_image.mode == image.mode\n            assert new_image.size == image.size\n            assert new_image.info == base_image.info\n            if palette_result is not None:\n                assert new_image.palette.tobytes() == palette_result.tobytes()\n            else:\n                assert new_image.palette is None\n\n        _make_new(im, im_p, ImagePalette.ImagePalette(list(range(256)) * 3))\n        _make_new(im_p, im, None)\n        _make_new(im, blank_p, ImagePalette.ImagePalette())\n        _make_new(im, blank_pa, ImagePalette.ImagePalette())\n\n    @pytest.mark.parametrize(\n        \"mode, color\",\n        (\n            (\"RGB\", \"#DDEEFF\"),\n            (\"RGB\", (221, 238, 255)),\n            (\"RGBA\", (221, 238, 255, 255)),\n        ),\n    )\n    def test_p_from_rgb_rgba(self, mode: str, color: str | tuple[int, ...]) -> None:\n        im = Image.new(\"P\", (100, 100), color)\n        expected = Image.new(mode, (100, 100), color)\n        assert_image_equal(im.convert(mode), expected)\n\n    def test_no_resource_warning_on_save(self, tmp_path: Path) -> None:\n        # https://github.com/python-pillow/Pillow/issues/835\n        # Arrange\n        test_file = \"Tests/images/hopper.png\"\n        temp_file = str(tmp_path / \"temp.jpg\")\n\n        # Act/Assert\n        with Image.open(test_file) as im:\n            with warnings.catch_warnings():\n                im.save(temp_file)\n\n    def test_no_new_file_on_error(self, tmp_path: Path) -> None:\n        temp_file = str(tmp_path / \"temp.jpg\")\n\n        im = Image.new(\"RGB\", (0, 0))\n        with pytest.raises(ValueError):\n            im.save(temp_file)\n\n        assert not os.path.exists(temp_file)\n\n    def test_load_on_nonexclusive_multiframe(self) -> None:\n        with open(\"Tests/images/frozenpond.mpo\", \"rb\") as fp:\n\n            def act(fp: IO[bytes]) -> None:\n                im = Image.open(fp)\n                im.load()\n\n            act(fp)\n\n            with Image.open(fp) as im:\n                im.load()\n\n            assert not fp.closed\n\n    def test_empty_exif(self) -> None:\n        with Image.open(\"Tests/images/exif.png\") as im:\n            exif = im.getexif()\n        assert dict(exif)\n\n        # Test that exif data is cleared after another load\n        exif.load(None)\n        assert not dict(exif)\n\n        # Test loading just the EXIF header\n        exif.load(b\"Exif\\x00\\x00\")\n        assert not dict(exif)\n\n    @mark_if_feature_version(\n        pytest.mark.valgrind_known_error, \"libjpeg_turbo\", \"2.0\", reason=\"Known Failing\"\n    )\n    def test_exif_jpeg(self, tmp_path: Path) -> None:\n        with Image.open(\"Tests/images/exif-72dpi-int.jpg\") as im:  # Little endian\n            exif = im.getexif()\n            assert 258 not in exif\n            assert 274 in exif\n            assert 282 in exif\n            assert exif[296] == 2\n            assert exif[11] == \"gThumb 3.0.1\"\n\n            out = str(tmp_path / \"temp.jpg\")\n            exif[258] = 8\n            del exif[274]\n            del exif[282]\n            exif[296] = 455\n            exif[11] = \"Pillow test\"\n            im.save(out, exif=exif)\n        with Image.open(out) as reloaded:\n            reloaded_exif = reloaded.getexif()\n            assert reloaded_exif[258] == 8\n            assert 274 not in reloaded_exif\n            assert 282 not in reloaded_exif\n            assert reloaded_exif[296] == 455\n            assert reloaded_exif[11] == \"Pillow test\"\n\n        with Image.open(\"Tests/images/no-dpi-in-exif.jpg\") as im:  # Big endian\n            exif = im.getexif()\n            assert 258 not in exif\n            assert 306 in exif\n            assert exif[274] == 1\n            assert exif[305] == \"Adobe Photoshop CC 2017 (Macintosh)\"\n\n            out = str(tmp_path / \"temp.jpg\")\n            exif[258] = 8\n            del exif[306]\n            exif[274] = 455\n            exif[305] = \"Pillow test\"\n            im.save(out, exif=exif)\n        with Image.open(out) as reloaded:\n            reloaded_exif = reloaded.getexif()\n            assert reloaded_exif[258] == 8\n            assert 306 not in reloaded_exif\n            assert reloaded_exif[274] == 455\n            assert reloaded_exif[305] == \"Pillow test\"\n\n    @skip_unless_feature(\"webp\")\n    @skip_unless_feature(\"webp_anim\")\n    def test_exif_webp(self, tmp_path: Path) -> None:\n        with Image.open(\"Tests/images/hopper.webp\") as im:\n            exif = im.getexif()\n            assert exif == {}\n\n            out = str(tmp_path / \"temp.webp\")\n            exif[258] = 8\n            exif[40963] = 455\n            exif[305] = \"Pillow test\"\n\n            def check_exif() -> None:\n                with Image.open(out) as reloaded:\n                    reloaded_exif = reloaded.getexif()\n                    assert reloaded_exif[258] == 8\n                    assert reloaded_exif[40963] == 455\n                    assert reloaded_exif[305] == \"Pillow test\"\n\n            im.save(out, exif=exif)\n            check_exif()\n            im.save(out, exif=exif, save_all=True)\n            check_exif()\n\n    def test_exif_png(self, tmp_path: Path) -> None:\n        with Image.open(\"Tests/images/exif.png\") as im:\n            exif = im.getexif()\n            assert exif == {274: 1}\n\n            out = str(tmp_path / \"temp.png\")\n            exif[258] = 8\n            del exif[274]\n            exif[40963] = 455\n            exif[305] = \"Pillow test\"\n            im.save(out, exif=exif)\n\n        with Image.open(out) as reloaded:\n            reloaded_exif = reloaded.getexif()\n            assert reloaded_exif == {258: 8, 40963: 455, 305: \"Pillow test\"}\n\n    def test_exif_interop(self) -> None:\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            exif = im.getexif()\n            assert exif.get_ifd(0xA005) == {\n                1: \"R98\",\n                2: b\"0100\",\n                4097: 2272,\n                4098: 1704,\n            }\n\n            reloaded_exif = Image.Exif()\n            reloaded_exif.load(exif.tobytes())\n            assert reloaded_exif.get_ifd(0xA005) == exif.get_ifd(0xA005)\n\n    def test_exif_ifd1(self) -> None:\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            exif = im.getexif()\n            assert exif.get_ifd(ExifTags.IFD.IFD1) == {\n                513: 2036,\n                514: 5448,\n                259: 6,\n                296: 2,\n                282: 180.0,\n                283: 180.0,\n            }\n\n    def test_exif_ifd(self) -> None:\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            exif = im.getexif()\n        del exif.get_ifd(0x8769)[0xA005]\n\n        reloaded_exif = Image.Exif()\n        reloaded_exif.load(exif.tobytes())\n        assert reloaded_exif.get_ifd(0x8769) == exif.get_ifd(0x8769)\n\n    def test_exif_load_from_fp(self) -> None:\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            data = im.info[\"exif\"]\n            if data.startswith(b\"Exif\\x00\\x00\"):\n                data = data[6:]\n            fp = io.BytesIO(data)\n\n            exif = Image.Exif()\n            exif.load_from_fp(fp)\n            assert exif == {\n                271: \"Canon\",\n                272: \"Canon PowerShot S40\",\n                274: 1,\n                282: 180.0,\n                283: 180.0,\n                296: 2,\n                306: \"2003:12:14 12:01:44\",\n                531: 1,\n                34665: 196,\n            }\n\n    def test_exif_hide_offsets(self) -> None:\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            exif = im.getexif()\n\n        # Check offsets are present initially\n        assert 0x8769 in exif\n        for tag in (0xA005, 0x927C):\n            assert tag in exif.get_ifd(0x8769)\n        assert exif.get_ifd(0xA005)\n        loaded_exif = exif\n\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            new_exif = im.getexif()\n\n            for exif in (loaded_exif, new_exif):\n                exif.hide_offsets()\n\n                # Assert they are hidden afterwards,\n                # but that the IFDs are still available\n                assert 0x8769 not in exif\n                assert exif.get_ifd(0x8769)\n                for tag in (0xA005, 0x927C):\n                    assert tag not in exif.get_ifd(0x8769)\n                assert exif.get_ifd(0xA005)\n\n    def test_empty_xmp(self) -> None:\n        with Image.open(\"Tests/images/hopper.gif\") as im:\n            assert im.getxmp() == {}\n\n    def test_getxmp_padded(self) -> None:\n        im = Image.new(\"RGB\", (1, 1))\n        im.info[\"xmp\"] = (\n            b'<?xpacket begin=\"\\xef\\xbb\\xbf\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\\n'\n            b'<x:xmpmeta xmlns:x=\"adobe:ns:meta/\" />\\n<?xpacket end=\"w\"?>\\x00\\x00'\n        )\n        if ElementTree is None:\n            with pytest.warns(\n                UserWarning,\n                match=\"XMP data cannot be read without defusedxml dependency\",\n            ):\n                assert im.getxmp() == {}\n        else:\n            assert im.getxmp() == {\"xmpmeta\": None}\n\n    @pytest.mark.parametrize(\"size\", ((1, 0), (0, 1), (0, 0)))\n    def test_zero_tobytes(self, size: tuple[int, int]) -> None:\n        im = Image.new(\"RGB\", size)\n        assert im.tobytes() == b\"\"\n\n    @pytest.mark.parametrize(\"size\", ((1, 0), (0, 1), (0, 0)))\n    def test_zero_frombytes(self, size: tuple[int, int]) -> None:\n        Image.frombytes(\"RGB\", size, b\"\")\n\n        im = Image.new(\"RGB\", size)\n        im.frombytes(b\"\")\n\n    def test_has_transparency_data(self) -> None:\n        for mode in (\"1\", \"L\", \"P\", \"RGB\"):\n            im = Image.new(mode, (1, 1))\n            assert not im.has_transparency_data\n\n        for mode in (\"LA\", \"La\", \"PA\", \"RGBA\", \"RGBa\"):\n            im = Image.new(mode, (1, 1))\n            assert im.has_transparency_data\n\n        # P mode with \"transparency\" info\n        with Image.open(\"Tests/images/first_frame_transparency.gif\") as im:\n            assert \"transparency\" in im.info\n            assert im.has_transparency_data\n\n        # RGB mode with \"transparency\" info\n        with Image.open(\"Tests/images/rgb_trns.png\") as im:\n            assert \"transparency\" in im.info\n            assert im.has_transparency_data\n\n        # P mode with RGBA palette\n        im = Image.new(\"RGBA\", (1, 1)).convert(\"P\")\n        assert im.mode == \"P\"\n        assert im.palette.mode == \"RGBA\"\n        assert im.has_transparency_data\n\n    def test_apply_transparency(self) -> None:\n        im = Image.new(\"P\", (1, 1))\n        im.putpalette((0, 0, 0, 1, 1, 1))\n        assert im.palette.colors == {(0, 0, 0): 0, (1, 1, 1): 1}\n\n        # Test that no transformation is applied without transparency\n        im.apply_transparency()\n        assert im.palette.colors == {(0, 0, 0): 0, (1, 1, 1): 1}\n\n        # Test that a transparency index is applied\n        im.info[\"transparency\"] = 0\n        im.apply_transparency()\n        assert \"transparency\" not in im.info\n        assert im.palette.colors == {(0, 0, 0, 0): 0, (1, 1, 1, 255): 1}\n\n        # Test that existing transparency is kept\n        im = Image.new(\"P\", (1, 1))\n        im.putpalette((0, 0, 0, 255, 1, 1, 1, 128), \"RGBA\")\n        im.info[\"transparency\"] = 0\n        im.apply_transparency()\n        assert im.palette.colors == {(0, 0, 0, 0): 0, (1, 1, 1, 128): 1}\n\n        # Test that transparency bytes are applied\n        with Image.open(\"Tests/images/pil123p.png\") as im:\n            assert isinstance(im.info[\"transparency\"], bytes)\n            assert im.palette.colors[(27, 35, 6)] == 24\n            im.apply_transparency()\n            assert im.palette.colors[(27, 35, 6, 214)] == 24\n\n    def test_constants(self) -> None:\n        for enum in (\n            Image.Transpose,\n            Image.Transform,\n            Image.Resampling,\n            Image.Dither,\n            Image.Palette,\n            Image.Quantize,\n        ):\n            for name in enum.__members__:\n                assert getattr(Image, name) == enum[name]\n\n    @pytest.mark.parametrize(\n        \"path\",\n        [\n            \"fli_overrun.bin\",\n            \"sgi_overrun.bin\",\n            \"sgi_overrun_expandrow.bin\",\n            \"sgi_overrun_expandrow2.bin\",\n            \"pcx_overrun.bin\",\n            \"pcx_overrun2.bin\",\n            \"ossfuzz-4836216264589312.pcx\",\n            \"01r_00.pcx\",\n        ],\n    )\n    def test_overrun(self, path: str) -> None:\n        \"\"\"For overrun completeness, test as:\n        valgrind pytest -qq Tests/test_image.py::TestImage::test_overrun | grep decode.c\n        \"\"\"\n        with Image.open(os.path.join(\"Tests/images\", path)) as im:\n            try:\n                im.load()\n                pytest.fail()\n            except OSError as e:\n                buffer_overrun = str(e) == \"buffer overrun when reading image file\"\n                truncated = \"image file is truncated\" in str(e)\n\n                assert buffer_overrun or truncated\n\n    def test_fli_overrun2(self) -> None:\n        with Image.open(\"Tests/images/fli_overrun2.bin\") as im:\n            try:\n                im.seek(1)\n                pytest.fail()\n            except OSError as e:\n                assert str(e) == \"buffer overrun when reading image file\"\n\n    def test_exit_fp(self) -> None:\n        with Image.new(\"L\", (1, 1)) as im:\n            pass\n        assert not hasattr(im, \"fp\")\n\n    def test_close_graceful(self, caplog: pytest.LogCaptureFixture) -> None:\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            copy = im.copy()\n            with caplog.at_level(logging.DEBUG):\n                im.close()\n                copy.close()\n            assert len(caplog.records) == 0\n            assert im.fp is None",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 55,
                                "end_lineno": 1080,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": ".. py:module:: PIL.Image\n.. py:currentmodule:: PIL.Image\n\n:py:mod:`~PIL.Image` Module\n===========================\n\nThe :py:mod:`~PIL.Image` module provides a class with the same name which is\nused to represent a PIL image. The module also provides a number of factory\nfunctions, including functions to load images from files, and to create new\nimages.\n\nExamples\n--------\n\nOpen, rotate, and display an image (using the default viewer)\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nThe following script loads an image, rotates it 45 degrees, and displays it\nusing an external viewer (usually xv on Unix, and the Paint program on\nWindows). ::\n\n    from PIL import Image\n    with Image.open(\"hopper.jpg\") as im:\n        im.rotate(45).show()\n\nCreate thumbnails\n^^^^^^^^^^^^^^^^^\n\nThe following script creates nice thumbnails of all JPEG images in the\ncurrent directory preserving aspect ratios with 128x128 max resolution. ::\n\n    from PIL import Image\n    import glob, os\n\n    size = 128, 128\n\n    for infile in glob.glob(\"*.jpg\"):\n        file, ext = os.path.splitext(infile)\n        with Image.open(infile) as im:\n            im.thumbnail(size)\n            im.save(file + \".thumbnail\", \"JPEG\")\n\nFunctions\n---------\n\n.. autofunction:: open\n\n    .. warning::\n        To protect against potential DOS attacks caused by \"`decompression bombs`_\" (i.e. malicious files\n        which decompress into a huge amount of data and are designed to crash or cause disruption by using up\n        a lot of memory), Pillow will issue a ``DecompressionBombWarning`` if the number of pixels in an\n        image is over a certain limit, :py:data:`MAX_IMAGE_PIXELS`.\n\n        This threshold can be changed by setting :py:data:`MAX_IMAGE_PIXELS`. It can be disabled\n        by setting ``Image.MAX_IMAGE_PIXELS = None``.\n\n        If desired, the warning can be turned into an error with\n        ``warnings.simplefilter('error', Image.DecompressionBombWarning)`` or suppressed entirely with\n        ``warnings.simplefilter('ignore', Image.DecompressionBombWarning)``. See also\n        `the logging documentation`_ to have warnings output to the logging facility instead of stderr.\n\n        If the number of pixels is greater than twice :py:data:`MAX_IMAGE_PIXELS`, then a\n        ``DecompressionBombError`` will be raised instead.\n\n    .. _decompression bombs: https://en.wikipedia.org/wiki/Zip_bomb\n    .. _the logging documentation: https://docs.python.org/3/library/logging.html#integration-with-the-warnings-module\n\nImage processing\n^^^^^^^^^^^^^^^^\n\n.. autofunction:: alpha_composite\n.. autofunction:: blend\n.. autofunction:: composite\n.. autofunction:: eval\n.. autofunction:: merge\n\nConstructing images\n^^^^^^^^^^^^^^^^^^^\n\n.. autofunction:: new\n.. autofunction:: fromarray\n.. autofunction:: frombytes\n.. autofunction:: frombuffer\n\nGenerating images\n^^^^^^^^^^^^^^^^^\n\n.. autofunction:: effect_mandelbrot\n.. autofunction:: effect_noise\n.. autofunction:: linear_gradient\n.. autofunction:: radial_gradient\n\nRegistering plugins\n^^^^^^^^^^^^^^^^^^^\n\n.. autofunction:: preinit\n.. autofunction:: init\n\n.. note::\n\n    These functions are for use by plugin authors. They are called when a\n    plugin is loaded as part of :py:meth:`~preinit()` or :py:meth:`~init()`.\n    Application authors can ignore them.\n\n.. autofunction:: register_open\n.. autofunction:: register_mime\n.. autofunction:: register_save\n.. autofunction:: register_save_all\n.. autofunction:: register_extension\n.. autofunction:: register_extensions\n.. autofunction:: registered_extensions\n.. autofunction:: register_decoder\n.. autofunction:: register_encoder\n\nThe Image Class\n---------------\n\n.. autoclass:: PIL.Image.Image\n\nAn instance of the :py:class:`~PIL.Image.Image` class has the following\nmethods. Unless otherwise stated, all methods return a new instance of the\n:py:class:`~PIL.Image.Image` class, holding the resulting image.\n\n\n.. automethod:: PIL.Image.Image.alpha_composite\n.. automethod:: PIL.Image.Image.apply_transparency\n.. automethod:: PIL.Image.Image.convert\n\nThe following example converts an RGB image (linearly calibrated according to\nITU-R 709, using the D65 luminant) to the CIE XYZ color space::\n\n    rgb2xyz = (\n        0.412453, 0.357580, 0.180423, 0,\n        0.212671, 0.715160, 0.072169, 0,\n        0.019334, 0.119193, 0.950227, 0)\n    out = im.convert(\"RGB\", rgb2xyz)\n\n.. automethod:: PIL.Image.Image.copy\n.. automethod:: PIL.Image.Image.crop\n\nThis crops the input image with the provided coordinates::\n\n    from PIL import Image\n\n    with Image.open(\"hopper.jpg\") as im:\n\n        # The crop method from the Image module takes four coordinates as input.\n        # The right can also be represented as (left+width)\n        # and lower can be represented as (upper+height).\n        (left, upper, right, lower) = (20, 20, 100, 100)\n\n        # Here the image \"im\" is cropped and assigned to new variable im_crop\n        im_crop = im.crop((left, upper, right, lower))\n\n\n.. automethod:: PIL.Image.Image.draft\n.. automethod:: PIL.Image.Image.effect_spread\n.. automethod:: PIL.Image.Image.entropy\n.. automethod:: PIL.Image.Image.filter\n\nThis blurs the input image using a filter from the ``ImageFilter`` module::\n\n    from PIL import Image, ImageFilter\n\n    with Image.open(\"hopper.jpg\") as im:\n\n        # Blur the input image using the filter ImageFilter.BLUR\n        im_blurred = im.filter(filter=ImageFilter.BLUR)\n\n.. automethod:: PIL.Image.Image.frombytes\n.. automethod:: PIL.Image.Image.getbands\n\nThis helps to get the bands of the input image::\n\n    from PIL import Image\n\n    with Image.open(\"hopper.jpg\") as im:\n        print(im.getbands())  # Returns ('R', 'G', 'B')\n\n.. automethod:: PIL.Image.Image.getbbox\n\nThis helps to get the bounding box coordinates of the input image::\n\n    from PIL import Image\n\n    with Image.open(\"hopper.jpg\") as im:\n        print(im.getbbox())\n        # Returns four coordinates in the format (left, upper, right, lower)\n\n.. automethod:: PIL.Image.Image.getchannel\n.. automethod:: PIL.Image.Image.getcolors\n.. automethod:: PIL.Image.Image.getdata\n.. automethod:: PIL.Image.Image.getexif\n.. automethod:: PIL.Image.Image.getextrema\n.. automethod:: PIL.Image.Image.getpalette\n.. automethod:: PIL.Image.Image.getpixel\n.. automethod:: PIL.Image.Image.getprojection\n.. automethod:: PIL.Image.Image.getxmp\n.. automethod:: PIL.Image.Image.histogram\n.. automethod:: PIL.Image.Image.paste\n.. automethod:: PIL.Image.Image.point\n.. automethod:: PIL.Image.Image.putalpha\n.. automethod:: PIL.Image.Image.putdata\n.. automethod:: PIL.Image.Image.putpalette\n.. automethod:: PIL.Image.Image.putpixel\n.. automethod:: PIL.Image.Image.quantize\n.. automethod:: PIL.Image.Image.reduce\n.. automethod:: PIL.Image.Image.remap_palette\n.. automethod:: PIL.Image.Image.resize\n\nThis resizes the given image from ``(width, height)`` to ``(width/2, height/2)``::\n\n    from PIL import Image\n\n    with Image.open(\"hopper.jpg\") as im:\n\n        # Provide the target width and height of the image\n        (width, height) = (im.width // 2, im.height // 2)\n        im_resized = im.resize((width, height))\n\n.. automethod:: PIL.Image.Image.rotate\n\nThis rotates the input image by ``theta`` degrees counter clockwise::\n\n    from PIL import Image\n\n    with Image.open(\"hopper.jpg\") as im:\n\n        # Rotate the image by 60 degrees counter clockwise\n        theta = 60\n        # Angle is in degrees counter clockwise\n        im_rotated = im.rotate(angle=theta)\n\n.. automethod:: PIL.Image.Image.save\n.. automethod:: PIL.Image.Image.seek\n.. automethod:: PIL.Image.Image.show\n.. automethod:: PIL.Image.Image.split\n.. automethod:: PIL.Image.Image.tell\n.. automethod:: PIL.Image.Image.thumbnail\n.. automethod:: PIL.Image.Image.tobitmap\n.. automethod:: PIL.Image.Image.tobytes\n.. automethod:: PIL.Image.Image.transform\n.. automethod:: PIL.Image.Image.transpose\n\nThis flips the input image by using the :data:`Transpose.FLIP_LEFT_RIGHT`\nmethod. ::\n\n    from PIL import Image\n\n    with Image.open(\"hopper.jpg\") as im:\n\n        # Flip the image from left to right\n        im_flipped = im.transpose(method=Image.Transpose.FLIP_LEFT_RIGHT)\n        # To flip the image from top to bottom,\n        # use the method \"Image.Transpose.FLIP_TOP_BOTTOM\"\n\n\n.. automethod:: PIL.Image.Image.verify\n\n.. automethod:: PIL.Image.Image.load\n.. automethod:: PIL.Image.Image.close\n\nImage Attributes\n----------------\n\nInstances of the :py:class:`Image` class have the following attributes:\n\n.. py:attribute:: Image.filename\n    :type: str\n\n    The filename or path of the source file. Only images created with the\n    factory function ``open`` have a filename attribute. If the input is a\n    file like object, the filename attribute is set to an empty string.\n\n.. py:attribute:: Image.format\n    :type: Optional[str]\n\n    The file format of the source file. For images created by the library\n    itself (via a factory function, or by running a method on an existing\n    image), this attribute is set to :data:`None`.\n\n.. py:attribute:: Image.mode\n    :type: str\n\n    Image mode. This is a string specifying the pixel format used by the image.\n    Typical values are “1”, “L”, “RGB”, or “CMYK.” See\n    :ref:`concept-modes` for a full list.\n\n.. py:attribute:: Image.size\n    :type: tuple[int]\n\n    Image size, in pixels. The size is given as a 2-tuple (width, height).\n\n.. py:attribute:: Image.width\n    :type: int\n\n    Image width, in pixels.\n\n.. py:attribute:: Image.height\n    :type: int\n\n    Image height, in pixels.\n\n.. py:attribute:: Image.palette\n    :type: Optional[PIL.ImagePalette.ImagePalette]\n\n    Colour palette table, if any. If mode is \"P\" or \"PA\", this should be an\n    instance of the :py:class:`~PIL.ImagePalette.ImagePalette` class.\n    Otherwise, it should be set to :data:`None`.\n\n.. py:attribute:: Image.info\n    :type: dict\n\n    A dictionary holding data associated with the image. This dictionary is\n    used by file handlers to pass on various non-image information read from\n    the file. See documentation for the various file handlers for details.\n\n    Most methods ignore the dictionary when returning new images; since the\n    keys are not standardized, it’s not possible for a method to know if the\n    operation affects the dictionary. If you need the information later on,\n    keep a reference to the info dictionary returned from the open method.\n\n    Unless noted elsewhere, this dictionary does not affect saving files.\n\n.. py:attribute:: Image.is_animated\n    :type: bool\n\n    ``True`` if this image has more than one frame, or ``False`` otherwise.\n\n    This attribute is only defined by image plugins that support animated images.\n    Plugins may leave this attribute undefined if they don't support loading\n    animated images, even if the given format supports animated images.\n\n    Given that this attribute is not present for all images use\n    ``getattr(image, \"is_animated\", False)`` to check if Pillow is aware of multiple\n    frames in an image regardless of its format.\n\n    .. seealso:: :attr:`~Image.n_frames`, :func:`~Image.seek` and :func:`~Image.tell`\n\n.. py:attribute:: Image.n_frames\n    :type: int\n\n    The number of frames in this image.\n\n    This attribute is only defined by image plugins that support animated images.\n    Plugins may leave this attribute undefined if they don't support loading\n    animated images, even if the given format supports animated images.\n\n    Given that this attribute is not present for all images use\n    ``getattr(image, \"n_frames\", 1)`` to check the number of frames that Pillow is\n    aware of in an image regardless of its format.\n\n    .. seealso:: :attr:`~Image.is_animated`, :func:`~Image.seek` and :func:`~Image.tell`\n\n.. autoattribute:: PIL.Image.Image.has_transparency_data\n\nClasses\n-------\n\n.. autoclass:: PIL.Image.Exif\n    :members:\n    :undoc-members:\n    :show-inheritance:\n.. autoclass:: PIL.Image.ImagePointHandler\n.. autoclass:: PIL.Image.ImageTransformHandler\n\nProtocols\n---------\n\n.. autoclass:: SupportsArrayInterface\n    :show-inheritance:\n.. autoclass:: SupportsGetData\n    :show-inheritance:\n\nConstants\n---------\n\n.. data:: NONE\n.. data:: MAX_IMAGE_PIXELS\n\n    Set to 89,478,485, approximately 0.25GB for a 24-bit (3 bpp) image.\n    See :py:meth:`~PIL.Image.open` for more information about how this is used.\n\nTranspose methods\n^^^^^^^^^^^^^^^^^\n\nUsed to specify the :meth:`Image.transpose` method to use.\n\n.. autoclass:: Transpose\n    :members:\n    :undoc-members:\n\nTransform methods\n^^^^^^^^^^^^^^^^^\n\nUsed to specify the :meth:`Image.transform` method to use.\n\n.. py:class:: Transform\n\n    .. py:attribute:: AFFINE\n\n        Affine transform\n\n    .. py:attribute:: EXTENT\n\n        Cut out a rectangular subregion\n\n    .. py:attribute:: PERSPECTIVE\n\n        Perspective transform\n\n    .. py:attribute:: QUAD\n\n        Map a quadrilateral to a rectangle\n\n    .. py:attribute:: MESH\n\n        Map a number of source quadrilaterals in one operation\n\nResampling filters\n^^^^^^^^^^^^^^^^^^\n\nSee :ref:`concept-filters` for details.\n\n.. autoclass:: Resampling\n    :members:\n    :undoc-members:\n\nDither modes\n^^^^^^^^^^^^\n\nUsed to specify the dithering method to use for the\n:meth:`~Image.convert` and :meth:`~Image.quantize` methods.\n\n.. py:class:: Dither\n\n    .. py:attribute:: NONE\n\n      No dither\n\n    .. py:attribute:: ORDERED\n\n      Not implemented\n\n    .. py:attribute:: RASTERIZE\n\n      Not implemented\n\n    .. py:attribute:: FLOYDSTEINBERG\n\n      Floyd-Steinberg dither\n\nPalettes\n^^^^^^^^\n\nUsed to specify the palette to use for the :meth:`~Image.convert` method.\n\n.. autoclass:: Palette\n    :members:\n    :undoc-members:\n\nQuantization methods\n^^^^^^^^^^^^^^^^^^^^\n\nUsed to specify the quantization method to use for the :meth:`~Image.quantize` method.\n\n.. py:class:: Quantize\n\n    .. py:attribute:: MEDIANCUT\n\n      Median cut. Default method, except for RGBA images. This method does not support\n      RGBA images.\n\n    .. py:attribute:: MAXCOVERAGE\n\n      Maximum coverage. This method does not support RGBA images.\n\n    .. py:attribute:: FASTOCTREE\n\n      Fast octree. Default method for RGBA images.\n\n    .. py:attribute:: LIBIMAGEQUANT\n\n      libimagequant\n\n      Check support using :py:func:`PIL.features.check_feature` with\n      ``feature=\"libimagequant\"``.\n",
            "new_file_content": ".. py:module:: PIL.Image\n.. py:currentmodule:: PIL.Image\n\n:py:mod:`~PIL.Image` Module\n===========================\n\nThe :py:mod:`~PIL.Image` module provides a class with the same name which is\nused to represent a PIL image. The module also provides a number of factory\nfunctions, including functions to load images from files, and to create new\nimages.\n\nExamples\n--------\n\nOpen, rotate, and display an image (using the default viewer)\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nThe following script loads an image, rotates it 45 degrees, and displays it\nusing an external viewer (usually xv on Unix, and the Paint program on\nWindows). ::\n\n    from PIL import Image\n    with Image.open(\"hopper.jpg\") as im:\n        im.rotate(45).show()\n\nCreate thumbnails\n^^^^^^^^^^^^^^^^^\n\nThe following script creates nice thumbnails of all JPEG images in the\ncurrent directory preserving aspect ratios with 128x128 max resolution. ::\n\n    from PIL import Image\n    import glob, os\n\n    size = 128, 128\n\n    for infile in glob.glob(\"*.jpg\"):\n        file, ext = os.path.splitext(infile)\n        with Image.open(infile) as im:\n            im.thumbnail(size)\n            im.save(file + \".thumbnail\", \"JPEG\")\n\nFunctions\n---------\n\n.. autofunction:: open\n\n    .. warning::\n        To protect against potential DOS attacks caused by \"`decompression bombs`_\" (i.e. malicious files\n        which decompress into a huge amount of data and are designed to crash or cause disruption by using up\n        a lot of memory), Pillow will issue a ``DecompressionBombWarning`` if the number of pixels in an\n        image is over a certain limit, :py:data:`MAX_IMAGE_PIXELS`.\n\n        This threshold can be changed by setting :py:data:`MAX_IMAGE_PIXELS`. It can be disabled\n        by setting ``Image.MAX_IMAGE_PIXELS = None``.\n\n        If desired, the warning can be turned into an error with\n        ``warnings.simplefilter('error', Image.DecompressionBombWarning)`` or suppressed entirely with\n        ``warnings.simplefilter('ignore', Image.DecompressionBombWarning)``. See also\n        `the logging documentation`_ to have warnings output to the logging facility instead of stderr.\n\n        If the number of pixels is greater than twice :py:data:`MAX_IMAGE_PIXELS`, then a\n        ``DecompressionBombError`` will be raised instead.\n\n    .. _decompression bombs: https://en.wikipedia.org/wiki/Zip_bomb\n    .. _the logging documentation: https://docs.python.org/3/library/logging.html#integration-with-the-warnings-module\n\nImage processing\n^^^^^^^^^^^^^^^^\n\n.. autofunction:: alpha_composite\n.. autofunction:: blend\n.. autofunction:: composite\n.. autofunction:: eval\n.. autofunction:: merge\n\nConstructing images\n^^^^^^^^^^^^^^^^^^^\n\n.. autofunction:: new\n.. autofunction:: fromarray\n.. autofunction:: frombytes\n.. autofunction:: frombuffer\n\nGenerating images\n^^^^^^^^^^^^^^^^^\n\n.. autofunction:: effect_mandelbrot\n.. autofunction:: effect_noise\n.. autofunction:: linear_gradient\n.. autofunction:: radial_gradient\n\nRegistering plugins\n^^^^^^^^^^^^^^^^^^^\n\n.. autofunction:: preinit\n.. autofunction:: init\n\n.. note::\n\n    These functions are for use by plugin authors. They are called when a\n    plugin is loaded as part of :py:meth:`~preinit()` or :py:meth:`~init()`.\n    Application authors can ignore them.\n\n.. autofunction:: register_open\n.. autofunction:: register_mime\n.. autofunction:: register_save\n.. autofunction:: register_save_all\n.. autofunction:: register_extension\n.. autofunction:: register_extensions\n.. autofunction:: registered_extensions\n.. autofunction:: register_decoder\n.. autofunction:: register_encoder\n\nThe Image Class\n---------------\n\n.. autoclass:: PIL.Image.Image\n\nAn instance of the :py:class:`~PIL.Image.Image` class has the following\nmethods. Unless otherwise stated, all methods return a new instance of the\n:py:class:`~PIL.Image.Image` class, holding the resulting image.\n\n\n.. automethod:: PIL.Image.Image.alpha_composite\n.. automethod:: PIL.Image.Image.apply_transparency\n.. automethod:: PIL.Image.Image.convert\n\nThe following example converts an RGB image (linearly calibrated according to\nITU-R 709, using the D65 luminant) to the CIE XYZ color space::\n\n    rgb2xyz = (\n        0.412453, 0.357580, 0.180423, 0,\n        0.212671, 0.715160, 0.072169, 0,\n        0.019334, 0.119193, 0.950227, 0)\n    out = im.convert(\"RGB\", rgb2xyz)\n\n.. automethod:: PIL.Image.Image.copy\n.. automethod:: PIL.Image.Image.crop\n\nThis crops the input image with the provided coordinates::\n\n    from PIL import Image\n\n    with Image.open(\"hopper.jpg\") as im:\n\n        # The crop method from the Image module takes four coordinates as input.\n        # The right can also be represented as (left+width)\n        # and lower can be represented as (upper+height).\n        (left, upper, right, lower) = (20, 20, 100, 100)\n\n        # Here the image \"im\" is cropped and assigned to new variable im_crop\n        im_crop = im.crop((left, upper, right, lower))\n\n\n.. automethod:: PIL.Image.Image.draft\n.. automethod:: PIL.Image.Image.effect_spread\n.. automethod:: PIL.Image.Image.entropy\n.. automethod:: PIL.Image.Image.filter\n\nThis blurs the input image using a filter from the ``ImageFilter`` module::\n\n    from PIL import Image, ImageFilter\n\n    with Image.open(\"hopper.jpg\") as im:\n\n        # Blur the input image using the filter ImageFilter.BLUR\n        im_blurred = im.filter(filter=ImageFilter.BLUR)\n\n.. automethod:: PIL.Image.Image.frombytes\n.. automethod:: PIL.Image.Image.getbands\n\nThis helps to get the bands of the input image::\n\n    from PIL import Image\n\n    with Image.open(\"hopper.jpg\") as im:\n        print(im.getbands())  # Returns ('R', 'G', 'B')\n\n.. automethod:: PIL.Image.Image.getbbox\n\nThis helps to get the bounding box coordinates of the input image::\n\n    from PIL import Image\n\n    with Image.open(\"hopper.jpg\") as im:\n        print(im.getbbox())\n        # Returns four coordinates in the format (left, upper, right, lower)\n\n.. automethod:: PIL.Image.Image.getchannel\n.. automethod:: PIL.Image.Image.getcolors\n.. automethod:: PIL.Image.Image.getdata\n.. automethod:: PIL.Image.Image.getexif\n.. automethod:: PIL.Image.Image.getextrema\n.. automethod:: PIL.Image.Image.getpalette\n.. automethod:: PIL.Image.Image.getpixel\n.. automethod:: PIL.Image.Image.getprojection\n.. automethod:: PIL.Image.Image.getxmp\n.. automethod:: PIL.Image.Image.histogram\n.. automethod:: PIL.Image.Image.paste\n.. automethod:: PIL.Image.Image.point\n.. automethod:: PIL.Image.Image.putalpha\n.. automethod:: PIL.Image.Image.putdata\n.. automethod:: PIL.Image.Image.putpalette\n.. automethod:: PIL.Image.Image.putpixel\n.. automethod:: PIL.Image.Image.quantize\n.. automethod:: PIL.Image.Image.reduce\n.. automethod:: PIL.Image.Image.remap_palette\n.. automethod:: PIL.Image.Image.resize\n\nThis resizes the given image from ``(width, height)`` to ``(width/2, height/2)``::\n\n    from PIL import Image\n\n    with Image.open(\"hopper.jpg\") as im:\n\n        # Provide the target width and height of the image\n        (width, height) = (im.width // 2, im.height // 2)\n        im_resized = im.resize((width, height))\n\n.. automethod:: PIL.Image.Image.rotate\n\nThis rotates the input image by ``theta`` degrees counter clockwise::\n\n    from PIL import Image\n\n    with Image.open(\"hopper.jpg\") as im:\n\n        # Rotate the image by 60 degrees counter clockwise\n        theta = 60\n        # Angle is in degrees counter clockwise\n        im_rotated = im.rotate(angle=theta)\n\n.. automethod:: PIL.Image.Image.save\n.. automethod:: PIL.Image.Image.seek\n.. automethod:: PIL.Image.Image.show\n.. automethod:: PIL.Image.Image.split\n.. automethod:: PIL.Image.Image.tell\n.. automethod:: PIL.Image.Image.thumbnail\n.. automethod:: PIL.Image.Image.tobitmap\n.. automethod:: PIL.Image.Image.tobytes\n.. automethod:: PIL.Image.Image.transform\n.. automethod:: PIL.Image.Image.transpose\n\nThis flips the input image by using the :data:`Transpose.FLIP_LEFT_RIGHT`\nmethod. ::\n\n    from PIL import Image\n\n    with Image.open(\"hopper.jpg\") as im:\n\n        # Flip the image from left to right\n        im_flipped = im.transpose(method=Image.Transpose.FLIP_LEFT_RIGHT)\n        # To flip the image from top to bottom,\n        # use the method \"Image.Transpose.FLIP_TOP_BOTTOM\"\n\n\n.. automethod:: PIL.Image.Image.verify\n\n.. automethod:: PIL.Image.Image.load\n.. automethod:: PIL.Image.Image.close\n\nImage Attributes\n----------------\n\nInstances of the :py:class:`Image` class have the following attributes:\n\n.. py:attribute:: Image.filename\n    :type: str\n\n    The filename or path of the source file. Only images created with the\n    factory function ``open`` have a filename attribute. If the input is a\n    file like object, the filename attribute is set to an empty string.\n\n.. py:attribute:: Image.format\n    :type: Optional[str]\n\n    The file format of the source file. For images created by the library\n    itself (via a factory function, or by running a method on an existing\n    image), this attribute is set to :data:`None`.\n\n.. py:attribute:: Image.mode\n    :type: str\n\n    Image mode. This is a string specifying the pixel format used by the image.\n    Typical values are “1”, “L”, “RGB”, or “CMYK.” See\n    :ref:`concept-modes` for a full list.\n\n.. py:attribute:: Image.size\n    :type: tuple[int]\n\n    Image size, in pixels. The size is given as a 2-tuple (width, height).\n\n.. py:attribute:: Image.width\n    :type: int\n\n    Image width, in pixels.\n\n.. py:attribute:: Image.height\n    :type: int\n\n    Image height, in pixels.\n\n.. py:attribute:: Image.palette\n    :type: Optional[PIL.ImagePalette.ImagePalette]\n\n    Colour palette table, if any. If mode is \"P\" or \"PA\", this should be an\n    instance of the :py:class:`~PIL.ImagePalette.ImagePalette` class.\n    Otherwise, it should be set to :data:`None`.\n\n.. py:attribute:: Image.info\n    :type: dict\n\n    A dictionary holding data associated with the image. This dictionary is\n    used by file handlers to pass on various non-image information read from\n    the file. See documentation for the various file handlers for details.\n\n    Most methods ignore the dictionary when returning new images; since the\n    keys are not standardized, it’s not possible for a method to know if the\n    operation affects the dictionary. If you need the information later on,\n    keep a reference to the info dictionary returned from the open method.\n\n    Unless noted elsewhere, this dictionary does not affect saving files.\n\n.. py:attribute:: Image.is_animated\n    :type: bool\n\n    ``True`` if this image has more than one frame, or ``False`` otherwise.\n\n    This attribute is only defined by image plugins that support animated images.\n    Plugins may leave this attribute undefined if they don't support loading\n    animated images, even if the given format supports animated images.\n\n    Given that this attribute is not present for all images use\n    ``getattr(image, \"is_animated\", False)`` to check if Pillow is aware of multiple\n    frames in an image regardless of its format.\n\n    .. seealso:: :attr:`~Image.n_frames`, :func:`~Image.seek` and :func:`~Image.tell`\n\n.. py:attribute:: Image.n_frames\n    :type: int\n\n    The number of frames in this image.\n\n    This attribute is only defined by image plugins that support animated images.\n    Plugins may leave this attribute undefined if they don't support loading\n    animated images, even if the given format supports animated images.\n\n    Given that this attribute is not present for all images use\n    ``getattr(image, \"n_frames\", 1)`` to check the number of frames that Pillow is\n    aware of in an image regardless of its format.\n\n    .. seealso:: :attr:`~Image.is_animated`, :func:`~Image.seek` and :func:`~Image.tell`\n\n.. autoattribute:: PIL.Image.Image.has_transparency_data\n\nClasses\n-------\n\n.. autoclass:: PIL.Image.Exif\n    :members:\n    :undoc-members:\n    :show-inheritance:\n.. autoclass:: PIL.Image.ImagePointHandler\n.. autoclass:: PIL.Image.ImageTransformHandler\n\nProtocols\n---------\n\n.. autoclass:: SupportsArrayInterface\n    :show-inheritance:\n.. autoclass:: SupportsGetData\n    :show-inheritance:\n\nConstants\n---------\n\n.. data:: NONE\n.. data:: MAX_IMAGE_PIXELS\n\n    Set to 89,478,485, approximately 0.25GB for a 24-bit (3 bpp) image.\n    See :py:meth:`~PIL.Image.open` for more information about how this is used.\n\n.. data:: WARN_POSSIBLE_FORMATS\n\n    Set to false. If true, when an image cannot be identified, warnings will be raised\n    from formats that attempted to read the data.\n\nTranspose methods\n^^^^^^^^^^^^^^^^^\n\nUsed to specify the :meth:`Image.transpose` method to use.\n\n.. autoclass:: Transpose\n    :members:\n    :undoc-members:\n\nTransform methods\n^^^^^^^^^^^^^^^^^\n\nUsed to specify the :meth:`Image.transform` method to use.\n\n.. py:class:: Transform\n\n    .. py:attribute:: AFFINE\n\n        Affine transform\n\n    .. py:attribute:: EXTENT\n\n        Cut out a rectangular subregion\n\n    .. py:attribute:: PERSPECTIVE\n\n        Perspective transform\n\n    .. py:attribute:: QUAD\n\n        Map a quadrilateral to a rectangle\n\n    .. py:attribute:: MESH\n\n        Map a number of source quadrilaterals in one operation\n\nResampling filters\n^^^^^^^^^^^^^^^^^^\n\nSee :ref:`concept-filters` for details.\n\n.. autoclass:: Resampling\n    :members:\n    :undoc-members:\n\nDither modes\n^^^^^^^^^^^^\n\nUsed to specify the dithering method to use for the\n:meth:`~Image.convert` and :meth:`~Image.quantize` methods.\n\n.. py:class:: Dither\n\n    .. py:attribute:: NONE\n\n      No dither\n\n    .. py:attribute:: ORDERED\n\n      Not implemented\n\n    .. py:attribute:: RASTERIZE\n\n      Not implemented\n\n    .. py:attribute:: FLOYDSTEINBERG\n\n      Floyd-Steinberg dither\n\nPalettes\n^^^^^^^^\n\nUsed to specify the palette to use for the :meth:`~Image.convert` method.\n\n.. autoclass:: Palette\n    :members:\n    :undoc-members:\n\nQuantization methods\n^^^^^^^^^^^^^^^^^^^^\n\nUsed to specify the quantization method to use for the :meth:`~Image.quantize` method.\n\n.. py:class:: Quantize\n\n    .. py:attribute:: MEDIANCUT\n\n      Median cut. Default method, except for RGBA images. This method does not support\n      RGBA images.\n\n    .. py:attribute:: MAXCOVERAGE\n\n      Maximum coverage. This method does not support RGBA images.\n\n    .. py:attribute:: FASTOCTREE\n\n      Fast octree. Default method for RGBA images.\n\n    .. py:attribute:: LIBIMAGEQUANT\n\n      libimagequant\n\n      Check support using :py:func:`PIL.features.check_feature` with\n      ``feature=\"libimagequant\"``.\n",
            "header": {
                "file": {
                    "path": "docs/reference/Image.rst"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "e83c8787f",
                "new_commit_hash": "66c5e5422",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/docs/reference/Image.rst"
            },
            "plus_file": {
                "path": "b/docs/reference/Image.rst"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 381,
                            "length": 6
                        },
                        "new_range": {
                            "start": 381,
                            "length": 11
                        },
                        "section": "Constants"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "    Set to 89,478,485, approximately 0.25GB for a 24-bit (3 bpp) image.",
                                "type": "context"
                            },
                            {
                                "content": "    See :py:meth:`~PIL.Image.open` for more information about how this is used.",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": ".. data:: WARN_POSSIBLE_FORMATS",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    Set to false. If true, when an image cannot be identified, warnings will be raised",
                                "type": "added"
                            },
                            {
                                "content": "    from formats that attempted to read the data.",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "Transpose methods",
                                "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# the Image class wrapper\n#\n# partial release history:\n# 1995-09-09 fl   Created\n# 1996-03-11 fl   PIL release 0.0 (proof of concept)\n# 1996-04-30 fl   PIL release 0.1b1\n# 1999-07-28 fl   PIL release 1.0 final\n# 2000-06-07 fl   PIL release 1.1\n# 2000-10-20 fl   PIL release 1.1.1\n# 2001-05-07 fl   PIL release 1.1.2\n# 2002-03-15 fl   PIL release 1.1.3\n# 2003-05-10 fl   PIL release 1.1.4\n# 2005-03-28 fl   PIL release 1.1.5\n# 2006-12-02 fl   PIL release 1.1.6\n# 2009-11-15 fl   PIL release 1.1.7\n#\n# Copyright (c) 1997-2009 by Secret Labs AB.  All rights reserved.\n# Copyright (c) 1995-2009 by Fredrik Lundh.\n#\n# See the README file for information on usage and redistribution.\n#\n\nfrom __future__ import annotations\n\nimport abc\nimport atexit\nimport builtins\nimport io\nimport logging\nimport math\nimport os\nimport re\nimport struct\nimport sys\nimport tempfile\nimport warnings\nfrom collections.abc import Callable, MutableMapping\nfrom enum import IntEnum\nfrom types import ModuleType\nfrom typing import (\n    IO,\n    TYPE_CHECKING,\n    Any,\n    Literal,\n    Protocol,\n    Sequence,\n    Tuple,\n    cast,\n)\n\n# VERSION was removed in Pillow 6.0.0.\n# PILLOW_VERSION was removed in Pillow 9.0.0.\n# Use __version__ instead.\nfrom . import (\n    ExifTags,\n    ImageMode,\n    TiffTags,\n    UnidentifiedImageError,\n    __version__,\n    _plugins,\n)\nfrom ._binary import i32le, o32be, o32le\nfrom ._deprecate import deprecate\nfrom ._typing import StrOrBytesPath, TypeGuard\nfrom ._util import DeferredError, is_path\n\nElementTree: ModuleType | None\ntry:\n    from defusedxml import ElementTree\nexcept ImportError:\n    ElementTree = None\n\nlogger = logging.getLogger(__name__)\n\n\nclass DecompressionBombWarning(RuntimeWarning):\n    pass\n\n\nclass DecompressionBombError(Exception):\n    pass\n\n\n# Limit to around a quarter gigabyte for a 24-bit (3 bpp) image\nMAX_IMAGE_PIXELS: int | None = int(1024 * 1024 * 1024 // 4 // 3)\n\n\ntry:\n    # If the _imaging C module is not present, Pillow will not load.\n    # Note that other modules should not refer to _imaging directly;\n    # import Image and use the Image.core variable instead.\n    # Also note that Image.core is not a publicly documented interface,\n    # and should be considered private and subject to change.\n    from . import _imaging as core\n\n    if __version__ != getattr(core, \"PILLOW_VERSION\", None):\n        msg = (\n            \"The _imaging extension was built for another version of Pillow or PIL:\\n\"\n            f\"Core version: {getattr(core, 'PILLOW_VERSION', None)}\\n\"\n            f\"Pillow version: {__version__}\"\n        )\n        raise ImportError(msg)\n\nexcept ImportError as v:\n    core = DeferredError.new(ImportError(\"The _imaging C module is not installed.\"))\n    # Explanations for ways that we know we might have an import error\n    if str(v).startswith(\"Module use of python\"):\n        # The _imaging C module is present, but not compiled for\n        # the right version (windows only).  Print a warning, if\n        # possible.\n        warnings.warn(\n            \"The _imaging extension was built for another version of Python.\",\n            RuntimeWarning,\n        )\n    elif str(v).startswith(\"The _imaging extension\"):\n        warnings.warn(str(v), RuntimeWarning)\n    # Fail here anyway. Don't let people run with a mostly broken Pillow.\n    # see docs/porting.rst\n    raise\n\n\nUSE_CFFI_ACCESS = False\ncffi: ModuleType | None\ntry:\n    import cffi\nexcept ImportError:\n    cffi = None\n\n\ndef isImageType(t: Any) -> TypeGuard[Image]:\n    \"\"\"\n    Checks if an object is an image object.\n\n    .. warning::\n\n       This function is for internal use only.\n\n    :param t: object to check if it's an image\n    :returns: True if the object is an image\n    \"\"\"\n    return hasattr(t, \"im\")\n\n\n#\n# Constants\n\n\n# transpose\nclass Transpose(IntEnum):\n    FLIP_LEFT_RIGHT = 0\n    FLIP_TOP_BOTTOM = 1\n    ROTATE_90 = 2\n    ROTATE_180 = 3\n    ROTATE_270 = 4\n    TRANSPOSE = 5\n    TRANSVERSE = 6\n\n\n# transforms (also defined in Imaging.h)\nclass Transform(IntEnum):\n    AFFINE = 0\n    EXTENT = 1\n    PERSPECTIVE = 2\n    QUAD = 3\n    MESH = 4\n\n\n# resampling filters (also defined in Imaging.h)\nclass Resampling(IntEnum):\n    NEAREST = 0\n    BOX = 4\n    BILINEAR = 2\n    HAMMING = 5\n    BICUBIC = 3\n    LANCZOS = 1\n\n\n_filters_support = {\n    Resampling.BOX: 0.5,\n    Resampling.BILINEAR: 1.0,\n    Resampling.HAMMING: 1.0,\n    Resampling.BICUBIC: 2.0,\n    Resampling.LANCZOS: 3.0,\n}\n\n\n# dithers\nclass Dither(IntEnum):\n    NONE = 0\n    ORDERED = 1  # Not yet implemented\n    RASTERIZE = 2  # Not yet implemented\n    FLOYDSTEINBERG = 3  # default\n\n\n# palettes/quantizers\nclass Palette(IntEnum):\n    WEB = 0\n    ADAPTIVE = 1\n\n\nclass Quantize(IntEnum):\n    MEDIANCUT = 0\n    MAXCOVERAGE = 1\n    FASTOCTREE = 2\n    LIBIMAGEQUANT = 3\n\n\nmodule = sys.modules[__name__]\nfor enum in (Transpose, Transform, Resampling, Dither, Palette, Quantize):\n    for item in enum:\n        setattr(module, item.name, item.value)\n\n\nif hasattr(core, \"DEFAULT_STRATEGY\"):\n    DEFAULT_STRATEGY = core.DEFAULT_STRATEGY\n    FILTERED = core.FILTERED\n    HUFFMAN_ONLY = core.HUFFMAN_ONLY\n    RLE = core.RLE\n    FIXED = core.FIXED\n\n\n# --------------------------------------------------------------------\n# Registries\n\nif TYPE_CHECKING:\n    from . import ImageFile, PyAccess\nID: list[str] = []\nOPEN: dict[\n    str,\n    tuple[\n        Callable[[IO[bytes], str | bytes], ImageFile.ImageFile],\n        Callable[[bytes], bool | str] | None,\n    ],\n] = {}\nMIME: dict[str, str] = {}\nSAVE: dict[str, Callable[[Image, IO[bytes], str | bytes], None]] = {}\nSAVE_ALL: dict[str, Callable[[Image, IO[bytes], str | bytes], None]] = {}\nEXTENSION: dict[str, str] = {}\nDECODERS: dict[str, type[ImageFile.PyDecoder]] = {}\nENCODERS: dict[str, type[ImageFile.PyEncoder]] = {}\n\n# --------------------------------------------------------------------\n# Modes\n\n_ENDIAN = \"<\" if sys.byteorder == \"little\" else \">\"\n\n\ndef _conv_type_shape(im):\n    m = ImageMode.getmode(im.mode)\n    shape = (im.height, im.width)\n    extra = len(m.bands)\n    if extra != 1:\n        shape += (extra,)\n    return shape, m.typestr\n\n\nMODES = [\n    \"1\",\n    \"CMYK\",\n    \"F\",\n    \"HSV\",\n    \"I\",\n    \"I;16\",\n    \"I;16B\",\n    \"I;16L\",\n    \"I;16N\",\n    \"L\",\n    \"LA\",\n    \"La\",\n    \"LAB\",\n    \"P\",\n    \"PA\",\n    \"RGB\",\n    \"RGBA\",\n    \"RGBa\",\n    \"RGBX\",\n    \"YCbCr\",\n]\n\n# raw modes that may be memory mapped.  NOTE: if you change this, you\n# may have to modify the stride calculation in map.c too!\n_MAPMODES = (\"L\", \"P\", \"RGBX\", \"RGBA\", \"CMYK\", \"I;16\", \"I;16L\", \"I;16B\")\n\n\ndef getmodebase(mode: str) -> str:\n    \"\"\"\n    Gets the \"base\" mode for given mode.  This function returns \"L\" for\n    images that contain grayscale data, and \"RGB\" for images that\n    contain color data.\n\n    :param mode: Input mode.\n    :returns: \"L\" or \"RGB\".\n    :exception KeyError: If the input mode was not a standard mode.\n    \"\"\"\n    return ImageMode.getmode(mode).basemode\n\n\ndef getmodetype(mode: str) -> str:\n    \"\"\"\n    Gets the storage type mode.  Given a mode, this function returns a\n    single-layer mode suitable for storing individual bands.\n\n    :param mode: Input mode.\n    :returns: \"L\", \"I\", or \"F\".\n    :exception KeyError: If the input mode was not a standard mode.\n    \"\"\"\n    return ImageMode.getmode(mode).basetype\n\n\ndef getmodebandnames(mode: str) -> tuple[str, ...]:\n    \"\"\"\n    Gets a list of individual band names.  Given a mode, this function returns\n    a tuple containing the names of individual bands (use\n    :py:method:`~PIL.Image.getmodetype` to get the mode used to store each\n    individual band.\n\n    :param mode: Input mode.\n    :returns: A tuple containing band names.  The length of the tuple\n        gives the number of bands in an image of the given mode.\n    :exception KeyError: If the input mode was not a standard mode.\n    \"\"\"\n    return ImageMode.getmode(mode).bands\n\n\ndef getmodebands(mode: str) -> int:\n    \"\"\"\n    Gets the number of individual bands for this mode.\n\n    :param mode: Input mode.\n    :returns: The number of bands in this mode.\n    :exception KeyError: If the input mode was not a standard mode.\n    \"\"\"\n    return len(ImageMode.getmode(mode).bands)\n\n\n# --------------------------------------------------------------------\n# Helpers\n\n_initialized = 0\n\n\ndef preinit() -> None:\n    \"\"\"\n    Explicitly loads BMP, GIF, JPEG, PPM and PPM file format drivers.\n\n    It is called when opening or saving images.\n    \"\"\"\n\n    global _initialized\n    if _initialized >= 1:\n        return\n\n    try:\n        from . import BmpImagePlugin\n\n        assert BmpImagePlugin\n    except ImportError:\n        pass\n    try:\n        from . import GifImagePlugin\n\n        assert GifImagePlugin\n    except ImportError:\n        pass\n    try:\n        from . import JpegImagePlugin\n\n        assert JpegImagePlugin\n    except ImportError:\n        pass\n    try:\n        from . import PpmImagePlugin\n\n        assert PpmImagePlugin\n    except ImportError:\n        pass\n    try:\n        from . import PngImagePlugin\n\n        assert PngImagePlugin\n    except ImportError:\n        pass\n\n    _initialized = 1\n\n\ndef init() -> bool:\n    \"\"\"\n    Explicitly initializes the Python Imaging Library. This function\n    loads all available file format drivers.\n\n    It is called when opening or saving images if :py:meth:`~preinit()` is\n    insufficient, and by :py:meth:`~PIL.features.pilinfo`.\n    \"\"\"\n\n    global _initialized\n    if _initialized >= 2:\n        return False\n\n    parent_name = __name__.rpartition(\".\")[0]\n    for plugin in _plugins:\n        try:\n            logger.debug(\"Importing %s\", plugin)\n            __import__(f\"{parent_name}.{plugin}\", globals(), locals(), [])\n        except ImportError as e:\n            logger.debug(\"Image: failed to import %s: %s\", plugin, e)\n\n    if OPEN or SAVE:\n        _initialized = 2\n        return True\n    return False\n\n\n# --------------------------------------------------------------------\n# Codec factories (used by tobytes/frombytes and ImageFile.load)\n\n\ndef _getdecoder(\n    mode: str, decoder_name: str, args: Any, extra: tuple[Any, ...] = ()\n) -> core.ImagingDecoder | ImageFile.PyDecoder:\n    # tweak arguments\n    if args is None:\n        args = ()\n    elif not isinstance(args, tuple):\n        args = (args,)\n\n    try:\n        decoder = DECODERS[decoder_name]\n    except KeyError:\n        pass\n    else:\n        return decoder(mode, *args + extra)\n\n    try:\n        # get decoder\n        decoder = getattr(core, f\"{decoder_name}_decoder\")\n    except AttributeError as e:\n        msg = f\"decoder {decoder_name} not available\"\n        raise OSError(msg) from e\n    return decoder(mode, *args + extra)\n\n\ndef _getencoder(\n    mode: str, encoder_name: str, args: Any, extra: tuple[Any, ...] = ()\n) -> core.ImagingEncoder | ImageFile.PyEncoder:\n    # tweak arguments\n    if args is None:\n        args = ()\n    elif not isinstance(args, tuple):\n        args = (args,)\n\n    try:\n        encoder = ENCODERS[encoder_name]\n    except KeyError:\n        pass\n    else:\n        return encoder(mode, *args + extra)\n\n    try:\n        # get encoder\n        encoder = getattr(core, f\"{encoder_name}_encoder\")\n    except AttributeError as e:\n        msg = f\"encoder {encoder_name} not available\"\n        raise OSError(msg) from e\n    return encoder(mode, *args + extra)\n\n\n# --------------------------------------------------------------------\n# Simple expression analyzer\n\n\nclass _E:\n    def __init__(self, scale, offset) -> None:\n        self.scale = scale\n        self.offset = offset\n\n    def __neg__(self):\n        return _E(-self.scale, -self.offset)\n\n    def __add__(self, other):\n        if isinstance(other, _E):\n            return _E(self.scale + other.scale, self.offset + other.offset)\n        return _E(self.scale, self.offset + other)\n\n    __radd__ = __add__\n\n    def __sub__(self, other):\n        return self + -other\n\n    def __rsub__(self, other):\n        return other + -self\n\n    def __mul__(self, other):\n        if isinstance(other, _E):\n            return NotImplemented\n        return _E(self.scale * other, self.offset * other)\n\n    __rmul__ = __mul__\n\n    def __truediv__(self, other):\n        if isinstance(other, _E):\n            return NotImplemented\n        return _E(self.scale / other, self.offset / other)\n\n\ndef _getscaleoffset(expr):\n    a = expr(_E(1, 0))\n    return (a.scale, a.offset) if isinstance(a, _E) else (0, a)\n\n\n# --------------------------------------------------------------------\n# Implementation wrapper\n\n\nclass SupportsGetData(Protocol):\n    def getdata(\n        self,\n    ) -> tuple[Transform, Sequence[int]]: ...\n\n\nclass Image:\n    \"\"\"\n    This class represents an image object.  To create\n    :py:class:`~PIL.Image.Image` objects, use the appropriate factory\n    functions.  There's hardly ever any reason to call the Image constructor\n    directly.\n\n    * :py:func:`~PIL.Image.open`\n    * :py:func:`~PIL.Image.new`\n    * :py:func:`~PIL.Image.frombytes`\n    \"\"\"\n\n    format: str | None = None\n    format_description: str | None = None\n    _close_exclusive_fp_after_loading = True\n\n    def __init__(self):\n        # FIXME: take \"new\" parameters / other image?\n        # FIXME: turn mode and size into delegating properties?\n        self.im = None\n        self._mode = \"\"\n        self._size = (0, 0)\n        self.palette = None\n        self.info = {}\n        self.readonly = 0\n        self.pyaccess = None\n        self._exif = None\n\n    @property\n    def width(self) -> int:\n        return self.size[0]\n\n    @property\n    def height(self) -> int:\n        return self.size[1]\n\n    @property\n    def size(self) -> tuple[int, int]:\n        return self._size\n\n    @property\n    def mode(self) -> str:\n        return self._mode\n\n    def _new(self, im: core.ImagingCore) -> Image:\n        new = Image()\n        new.im = im\n        new._mode = im.mode\n        new._size = im.size\n        if im.mode in (\"P\", \"PA\"):\n            if self.palette:\n                new.palette = self.palette.copy()\n            else:\n                from . import ImagePalette\n\n                new.palette = ImagePalette.ImagePalette()\n        new.info = self.info.copy()\n        return new\n\n    # Context manager support\n    def __enter__(self):\n        return self\n\n    def _close_fp(self):\n        if getattr(self, \"_fp\", False):\n            if self._fp != self.fp:\n                self._fp.close()\n            self._fp = DeferredError(ValueError(\"Operation on closed image\"))\n        if self.fp:\n            self.fp.close()\n\n    def __exit__(self, *args):\n        if hasattr(self, \"fp\"):\n            if getattr(self, \"_exclusive_fp\", False):\n                self._close_fp()\n            self.fp = None\n\n    def close(self) -> None:\n        \"\"\"\n        Closes the file pointer, if possible.\n\n        This operation will destroy the image core and release its memory.\n        The image data will be unusable afterward.\n\n        This function is required to close images that have multiple frames or\n        have not had their file read and closed by the\n        :py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for\n        more information.\n        \"\"\"\n        if hasattr(self, \"fp\"):\n            try:\n                self._close_fp()\n                self.fp = None\n            except Exception as msg:\n                logger.debug(\"Error closing: %s\", msg)\n\n        if getattr(self, \"map\", None):\n            self.map = None\n\n        # Instead of simply setting to None, we're setting up a\n        # deferred error that will better explain that the core image\n        # object is gone.\n        self.im = DeferredError(ValueError(\"Operation on closed image\"))\n\n    def _copy(self) -> None:\n        self.load()\n        self.im = self.im.copy()\n        self.pyaccess = None\n        self.readonly = 0\n\n    def _ensure_mutable(self) -> None:\n        if self.readonly:\n            self._copy()\n        else:\n            self.load()\n\n    def _dump(\n        self, file: str | None = None, format: str | None = None, **options: Any\n    ) -> str:\n        suffix = \"\"\n        if format:\n            suffix = f\".{format}\"\n\n        if not file:\n            f, filename = tempfile.mkstemp(suffix)\n            os.close(f)\n        else:\n            filename = file\n            if not filename.endswith(suffix):\n                filename = filename + suffix\n\n        self.load()\n\n        if not format or format == \"PPM\":\n            self.im.save_ppm(filename)\n        else:\n            self.save(filename, format, **options)\n\n        return filename\n\n    def __eq__(self, other: object) -> bool:\n        if self.__class__ is not other.__class__:\n            return False\n        assert isinstance(other, Image)\n        return (\n            self.mode == other.mode\n            and self.size == other.size\n            and self.info == other.info\n            and self.getpalette() == other.getpalette()\n            and self.tobytes() == other.tobytes()\n        )\n\n    def __repr__(self) -> str:\n        return \"<%s.%s image mode=%s size=%dx%d at 0x%X>\" % (\n            self.__class__.__module__,\n            self.__class__.__name__,\n            self.mode,\n            self.size[0],\n            self.size[1],\n            id(self),\n        )\n\n    def _repr_pretty_(self, p, cycle) -> None:\n        \"\"\"IPython plain text display support\"\"\"\n\n        # Same as __repr__ but without unpredictable id(self),\n        # to keep Jupyter notebook `text/plain` output stable.\n        p.text(\n            \"<%s.%s image mode=%s size=%dx%d>\"\n            % (\n                self.__class__.__module__,\n                self.__class__.__name__,\n                self.mode,\n                self.size[0],\n                self.size[1],\n            )\n        )\n\n    def _repr_image(self, image_format: str, **kwargs: Any) -> bytes | None:\n        \"\"\"Helper function for iPython display hook.\n\n        :param image_format: Image format.\n        :returns: image as bytes, saved into the given format.\n        \"\"\"\n        b = io.BytesIO()\n        try:\n            self.save(b, image_format, **kwargs)\n        except Exception:\n            return None\n        return b.getvalue()\n\n    def _repr_png_(self) -> bytes | None:\n        \"\"\"iPython display hook support for PNG format.\n\n        :returns: PNG version of the image as bytes\n        \"\"\"\n        return self._repr_image(\"PNG\", compress_level=1)\n\n    def _repr_jpeg_(self) -> bytes | None:\n        \"\"\"iPython display hook support for JPEG format.\n\n        :returns: JPEG version of the image as bytes\n        \"\"\"\n        return self._repr_image(\"JPEG\")\n\n    @property\n    def __array_interface__(self):\n        # numpy array interface support\n        new = {\"version\": 3}\n        try:\n            if self.mode == \"1\":\n                # Binary images need to be extended from bits to bytes\n                # See: https://github.com/python-pillow/Pillow/issues/350\n                new[\"data\"] = self.tobytes(\"raw\", \"L\")\n            else:\n                new[\"data\"] = self.tobytes()\n        except Exception as e:\n            if not isinstance(e, (MemoryError, RecursionError)):\n                try:\n                    import numpy\n                    from packaging.version import parse as parse_version\n                except ImportError:\n                    pass\n                else:\n                    if parse_version(numpy.__version__) < parse_version(\"1.23\"):\n                        warnings.warn(str(e))\n            raise\n        new[\"shape\"], new[\"typestr\"] = _conv_type_shape(self)\n        return new\n\n    def __getstate__(self):\n        im_data = self.tobytes()  # load image first\n        return [self.info, self.mode, self.size, self.getpalette(), im_data]\n\n    def __setstate__(self, state) -> None:\n        Image.__init__(self)\n        info, mode, size, palette, data = state\n        self.info = info\n        self._mode = mode\n        self._size = size\n        self.im = core.new(mode, size)\n        if mode in (\"L\", \"LA\", \"P\", \"PA\") and palette:\n            self.putpalette(palette)\n        self.frombytes(data)\n\n    def tobytes(self, encoder_name: str = \"raw\", *args: Any) -> bytes:\n        \"\"\"\n        Return image as a bytes object.\n\n        .. warning::\n\n            This method returns the raw image data from the internal\n            storage.  For compressed image data (e.g. PNG, JPEG) use\n            :meth:`~.save`, with a BytesIO parameter for in-memory\n            data.\n\n        :param encoder_name: What encoder to use.  The default is to\n                             use the standard \"raw\" encoder.\n\n                             A list of C encoders can be seen under\n                             codecs section of the function array in\n                             :file:`_imaging.c`. Python encoders are\n                             registered within the relevant plugins.\n        :param args: Extra arguments to the encoder.\n        :returns: A :py:class:`bytes` object.\n        \"\"\"\n\n        encoder_args: Any = args\n        if len(encoder_args) == 1 and isinstance(encoder_args[0], tuple):\n            # may pass tuple instead of argument list\n            encoder_args = encoder_args[0]\n\n        if encoder_name == \"raw\" and encoder_args == ():\n            encoder_args = self.mode\n\n        self.load()\n\n        if self.width == 0 or self.height == 0:\n            return b\"\"\n\n        # unpack data\n        e = _getencoder(self.mode, encoder_name, encoder_args)\n        e.setimage(self.im)\n\n        bufsize = max(65536, self.size[0] * 4)  # see RawEncode.c\n\n        output = []\n        while True:\n            bytes_consumed, errcode, data = e.encode(bufsize)\n            output.append(data)\n            if errcode:\n                break\n        if errcode < 0:\n            msg = f\"encoder error {errcode} in tobytes\"\n            raise RuntimeError(msg)\n\n        return b\"\".join(output)\n\n    def tobitmap(self, name: str = \"image\") -> bytes:\n        \"\"\"\n        Returns the image converted to an X11 bitmap.\n\n        .. note:: This method only works for mode \"1\" images.\n\n        :param name: The name prefix to use for the bitmap variables.\n        :returns: A string containing an X11 bitmap.\n        :raises ValueError: If the mode is not \"1\"\n        \"\"\"\n\n        self.load()\n        if self.mode != \"1\":\n            msg = \"not a bitmap\"\n            raise ValueError(msg)\n        data = self.tobytes(\"xbm\")\n        return b\"\".join(\n            [\n                f\"#define {name}_width {self.size[0]}\\n\".encode(\"ascii\"),\n                f\"#define {name}_height {self.size[1]}\\n\".encode(\"ascii\"),\n                f\"static char {name}_bits[] = {{\\n\".encode(\"ascii\"),\n                data,\n                b\"};\",\n            ]\n        )\n\n    def frombytes(\n        self, data: bytes | bytearray, decoder_name: str = \"raw\", *args: Any\n    ) -> None:\n        \"\"\"\n        Loads this image with pixel data from a bytes object.\n\n        This method is similar to the :py:func:`~PIL.Image.frombytes` function,\n        but loads data into this image instead of creating a new image object.\n        \"\"\"\n\n        if self.width == 0 or self.height == 0:\n            return\n\n        decoder_args: Any = args\n        if len(decoder_args) == 1 and isinstance(decoder_args[0], tuple):\n            # may pass tuple instead of argument list\n            decoder_args = decoder_args[0]\n\n        # default format\n        if decoder_name == \"raw\" and decoder_args == ():\n            decoder_args = self.mode\n\n        # unpack data\n        d = _getdecoder(self.mode, decoder_name, decoder_args)\n        d.setimage(self.im)\n        s = d.decode(data)\n\n        if s[0] >= 0:\n            msg = \"not enough image data\"\n            raise ValueError(msg)\n        if s[1] != 0:\n            msg = \"cannot decode image data\"\n            raise ValueError(msg)\n\n    def load(self) -> core.PixelAccess | PyAccess.PyAccess | None:\n        \"\"\"\n        Allocates storage for the image and loads the pixel data.  In\n        normal cases, you don't need to call this method, since the\n        Image class automatically loads an opened image when it is\n        accessed for the first time.\n\n        If the file associated with the image was opened by Pillow, then this\n        method will close it. The exception to this is if the image has\n        multiple frames, in which case the file will be left open for seek\n        operations. See :ref:`file-handling` for more information.\n\n        :returns: An image access object.\n        :rtype: :py:class:`.PixelAccess` or :py:class:`.PyAccess`\n        \"\"\"\n        if self.im is not None and self.palette and self.palette.dirty:\n            # realize palette\n            mode, arr = self.palette.getdata()\n            self.im.putpalette(self.palette.mode, mode, arr)\n            self.palette.dirty = 0\n            self.palette.rawmode = None\n            if \"transparency\" in self.info and mode in (\"LA\", \"PA\"):\n                if isinstance(self.info[\"transparency\"], int):\n                    self.im.putpalettealpha(self.info[\"transparency\"], 0)\n                else:\n                    self.im.putpalettealphas(self.info[\"transparency\"])\n                self.palette.mode = \"RGBA\"\n            else:\n                self.palette.palette = self.im.getpalette(\n                    self.palette.mode, self.palette.mode\n                )\n\n        if self.im is not None:\n            if cffi and USE_CFFI_ACCESS:\n                if self.pyaccess:\n                    return self.pyaccess\n                from . import PyAccess\n\n                self.pyaccess = PyAccess.new(self, self.readonly)\n                if self.pyaccess:\n                    return self.pyaccess\n            return self.im.pixel_access(self.readonly)\n        return None\n\n    def verify(self) -> None:\n        \"\"\"\n        Verifies the contents of a file. For data read from a file, this\n        method attempts to determine if the file is broken, without\n        actually decoding the image data.  If this method finds any\n        problems, it raises suitable exceptions.  If you need to load\n        the image after using this method, you must reopen the image\n        file.\n        \"\"\"\n        pass\n\n    def convert(\n        self,\n        mode: str | None = None,\n        matrix: tuple[float, ...] | None = None,\n        dither: Dither | None = None,\n        palette: Palette = Palette.WEB,\n        colors: int = 256,\n    ) -> Image:\n        \"\"\"\n        Returns a converted copy of this image. For the \"P\" mode, this\n        method translates pixels through the palette.  If mode is\n        omitted, a mode is chosen so that all information in the image\n        and the palette can be represented without a palette.\n\n        This supports all possible conversions between \"L\", \"RGB\" and \"CMYK\". The\n        ``matrix`` argument only supports \"L\" and \"RGB\".\n\n        When translating a color image to grayscale (mode \"L\"),\n        the library uses the ITU-R 601-2 luma transform::\n\n            L = R * 299/1000 + G * 587/1000 + B * 114/1000\n\n        The default method of converting a grayscale (\"L\") or \"RGB\"\n        image into a bilevel (mode \"1\") image uses Floyd-Steinberg\n        dither to approximate the original image luminosity levels. If\n        dither is ``None``, all values larger than 127 are set to 255 (white),\n        all other values to 0 (black). To use other thresholds, use the\n        :py:meth:`~PIL.Image.Image.point` method.\n\n        When converting from \"RGBA\" to \"P\" without a ``matrix`` argument,\n        this passes the operation to :py:meth:`~PIL.Image.Image.quantize`,\n        and ``dither`` and ``palette`` are ignored.\n\n        When converting from \"PA\", if an \"RGBA\" palette is present, the alpha\n        channel from the image will be used instead of the values from the palette.\n\n        :param mode: The requested mode. See: :ref:`concept-modes`.\n        :param matrix: An optional conversion matrix.  If given, this\n           should be 4- or 12-tuple containing floating point values.\n        :param dither: Dithering method, used when converting from\n           mode \"RGB\" to \"P\" or from \"RGB\" or \"L\" to \"1\".\n           Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG`\n           (default). Note that this is not used when ``matrix`` is supplied.\n        :param palette: Palette to use when converting from mode \"RGB\"\n           to \"P\".  Available palettes are :data:`Palette.WEB` or\n           :data:`Palette.ADAPTIVE`.\n        :param colors: Number of colors to use for the :data:`Palette.ADAPTIVE`\n           palette. Defaults to 256.\n        :rtype: :py:class:`~PIL.Image.Image`\n        :returns: An :py:class:`~PIL.Image.Image` object.\n        \"\"\"\n\n        if mode in (\"BGR;15\", \"BGR;16\", \"BGR;24\"):\n            deprecate(mode, 12)\n\n        self.load()\n\n        has_transparency = \"transparency\" in self.info\n        if not mode and self.mode == \"P\":\n            # determine default mode\n            if self.palette:\n                mode = self.palette.mode\n            else:\n                mode = \"RGB\"\n            if mode == \"RGB\" and has_transparency:\n                mode = \"RGBA\"\n        if not mode or (mode == self.mode and not matrix):\n            return self.copy()\n\n        if matrix:\n            # matrix conversion\n            if mode not in (\"L\", \"RGB\"):\n                msg = \"illegal conversion\"\n                raise ValueError(msg)\n            im = self.im.convert_matrix(mode, matrix)\n            new_im = self._new(im)\n            if has_transparency and self.im.bands == 3:\n                transparency = new_im.info[\"transparency\"]\n\n                def convert_transparency(\n                    m: tuple[float, ...], v: tuple[int, int, int]\n                ) -> int:\n                    value = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * 0.5\n                    return max(0, min(255, int(value)))\n\n                if mode == \"L\":\n                    transparency = convert_transparency(matrix, transparency)\n                elif len(mode) == 3:\n                    transparency = tuple(\n                        convert_transparency(matrix[i * 4 : i * 4 + 4], transparency)\n                        for i in range(0, len(transparency))\n                    )\n                new_im.info[\"transparency\"] = transparency\n            return new_im\n\n        if mode == \"P\" and self.mode == \"RGBA\":\n            return self.quantize(colors)\n\n        trns = None\n        delete_trns = False\n        # transparency handling\n        if has_transparency:\n            if (self.mode in (\"1\", \"L\", \"I\", \"I;16\") and mode in (\"LA\", \"RGBA\")) or (\n                self.mode == \"RGB\" and mode in (\"La\", \"LA\", \"RGBa\", \"RGBA\")\n            ):\n                # Use transparent conversion to promote from transparent\n                # color to an alpha channel.\n                new_im = self._new(\n                    self.im.convert_transparent(mode, self.info[\"transparency\"])\n                )\n                del new_im.info[\"transparency\"]\n                return new_im\n            elif self.mode in (\"L\", \"RGB\", \"P\") and mode in (\"L\", \"RGB\", \"P\"):\n                t = self.info[\"transparency\"]\n                if isinstance(t, bytes):\n                    # Dragons. This can't be represented by a single color\n                    warnings.warn(\n                        \"Palette images with Transparency expressed in bytes should be \"\n                        \"converted to RGBA images\"\n                    )\n                    delete_trns = True\n                else:\n                    # get the new transparency color.\n                    # use existing conversions\n                    trns_im = new(self.mode, (1, 1))\n                    if self.mode == \"P\":\n                        trns_im.putpalette(self.palette)\n                        if isinstance(t, tuple):\n                            err = \"Couldn't allocate a palette color for transparency\"\n                            try:\n                                t = trns_im.palette.getcolor(t, self)\n                            except ValueError as e:\n                                if str(e) == \"cannot allocate more than 256 colors\":\n                                    # If all 256 colors are in use,\n                                    # then there is no need for transparency\n                                    t = None\n                                else:\n                                    raise ValueError(err) from e\n                    if t is None:\n                        trns = None\n                    else:\n                        trns_im.putpixel((0, 0), t)\n\n                        if mode in (\"L\", \"RGB\"):\n                            trns_im = trns_im.convert(mode)\n                        else:\n                            # can't just retrieve the palette number, got to do it\n                            # after quantization.\n                            trns_im = trns_im.convert(\"RGB\")\n                        trns = trns_im.getpixel((0, 0))\n\n            elif self.mode == \"P\" and mode in (\"LA\", \"PA\", \"RGBA\"):\n                t = self.info[\"transparency\"]\n                delete_trns = True\n\n                if isinstance(t, bytes):\n                    self.im.putpalettealphas(t)\n                elif isinstance(t, int):\n                    self.im.putpalettealpha(t, 0)\n                else:\n                    msg = \"Transparency for P mode should be bytes or int\"\n                    raise ValueError(msg)\n\n        if mode == \"P\" and palette == Palette.ADAPTIVE:\n            im = self.im.quantize(colors)\n            new_im = self._new(im)\n            from . import ImagePalette\n\n            new_im.palette = ImagePalette.ImagePalette(\n                \"RGB\", new_im.im.getpalette(\"RGB\")\n            )\n            if delete_trns:\n                # This could possibly happen if we requantize to fewer colors.\n                # The transparency would be totally off in that case.\n                del new_im.info[\"transparency\"]\n            if trns is not None:\n                try:\n                    new_im.info[\"transparency\"] = new_im.palette.getcolor(\n                        cast(Tuple[int, ...], trns),  # trns was converted to RGB\n                        new_im,\n                    )\n                except Exception:\n                    # if we can't make a transparent color, don't leave the old\n                    # transparency hanging around to mess us up.\n                    del new_im.info[\"transparency\"]\n                    warnings.warn(\"Couldn't allocate palette entry for transparency\")\n            return new_im\n\n        if \"LAB\" in (self.mode, mode):\n            other_mode = mode if self.mode == \"LAB\" else self.mode\n            if other_mode in (\"RGB\", \"RGBA\", \"RGBX\"):\n                from . import ImageCms\n\n                srgb = ImageCms.createProfile(\"sRGB\")\n                lab = ImageCms.createProfile(\"LAB\")\n                profiles = [lab, srgb] if self.mode == \"LAB\" else [srgb, lab]\n                transform = ImageCms.buildTransform(\n                    profiles[0], profiles[1], self.mode, mode\n                )\n                return transform.apply(self)\n\n        # colorspace conversion\n        if dither is None:\n            dither = Dither.FLOYDSTEINBERG\n\n        try:\n            im = self.im.convert(mode, dither)\n        except ValueError:\n            try:\n                # normalize source image and try again\n                modebase = getmodebase(self.mode)\n                if modebase == self.mode:\n                    raise\n                im = self.im.convert(modebase)\n                im = im.convert(mode, dither)\n            except KeyError as e:\n                msg = \"illegal conversion\"\n                raise ValueError(msg) from e\n\n        new_im = self._new(im)\n        if mode == \"P\" and palette != Palette.ADAPTIVE:\n            from . import ImagePalette\n\n            new_im.palette = ImagePalette.ImagePalette(\"RGB\", im.getpalette(\"RGB\"))\n        if delete_trns:\n            # crash fail if we leave a bytes transparency in an rgb/l mode.\n            del new_im.info[\"transparency\"]\n        if trns is not None:\n            if new_im.mode == \"P\" and new_im.palette:\n                try:\n                    new_im.info[\"transparency\"] = new_im.palette.getcolor(trns, new_im)\n                except ValueError as e:\n                    del new_im.info[\"transparency\"]\n                    if str(e) != \"cannot allocate more than 256 colors\":\n                        # If all 256 colors are in use,\n                        # then there is no need for transparency\n                        warnings.warn(\n                            \"Couldn't allocate palette entry for transparency\"\n                        )\n            else:\n                new_im.info[\"transparency\"] = trns\n        return new_im\n\n    def quantize(\n        self,\n        colors: int = 256,\n        method: int | None = None,\n        kmeans: int = 0,\n        palette=None,\n        dither: Dither = Dither.FLOYDSTEINBERG,\n    ) -> Image:\n        \"\"\"\n        Convert the image to 'P' mode with the specified number\n        of colors.\n\n        :param colors: The desired number of colors, <= 256\n        :param method: :data:`Quantize.MEDIANCUT` (median cut),\n                       :data:`Quantize.MAXCOVERAGE` (maximum coverage),\n                       :data:`Quantize.FASTOCTREE` (fast octree),\n                       :data:`Quantize.LIBIMAGEQUANT` (libimagequant; check support\n                       using :py:func:`PIL.features.check_feature` with\n                       ``feature=\"libimagequant\"``).\n\n                       By default, :data:`Quantize.MEDIANCUT` will be used.\n\n                       The exception to this is RGBA images. :data:`Quantize.MEDIANCUT`\n                       and :data:`Quantize.MAXCOVERAGE` do not support RGBA images, so\n                       :data:`Quantize.FASTOCTREE` is used by default instead.\n        :param kmeans: Integer greater than or equal to zero.\n        :param palette: Quantize to the palette of given\n                        :py:class:`PIL.Image.Image`.\n        :param dither: Dithering method, used when converting from\n           mode \"RGB\" to \"P\" or from \"RGB\" or \"L\" to \"1\".\n           Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG`\n           (default).\n        :returns: A new image\n        \"\"\"\n\n        self.load()\n\n        if method is None:\n            # defaults:\n            method = Quantize.MEDIANCUT\n            if self.mode == \"RGBA\":\n                method = Quantize.FASTOCTREE\n\n        if self.mode == \"RGBA\" and method not in (\n            Quantize.FASTOCTREE,\n            Quantize.LIBIMAGEQUANT,\n        ):\n            # Caller specified an invalid mode.\n            msg = (\n                \"Fast Octree (method == 2) and libimagequant (method == 3) \"\n                \"are the only valid methods for quantizing RGBA images\"\n            )\n            raise ValueError(msg)\n\n        if palette:\n            # use palette from reference image\n            palette.load()\n            if palette.mode != \"P\":\n                msg = \"bad mode for palette image\"\n                raise ValueError(msg)\n            if self.mode not in {\"RGB\", \"L\"}:\n                msg = \"only RGB or L mode images can be quantized to a palette\"\n                raise ValueError(msg)\n            im = self.im.convert(\"P\", dither, palette.im)\n            new_im = self._new(im)\n            new_im.palette = palette.palette.copy()\n            return new_im\n\n        if kmeans < 0:\n            msg = \"kmeans must not be negative\"\n            raise ValueError(msg)\n\n        im = self._new(self.im.quantize(colors, method, kmeans))\n\n        from . import ImagePalette\n\n        mode = im.im.getpalettemode()\n        palette = im.im.getpalette(mode, mode)[: colors * len(mode)]\n        im.palette = ImagePalette.ImagePalette(mode, palette)\n\n        return im\n\n    def copy(self) -> Image:\n        \"\"\"\n        Copies this image. Use this method if you wish to paste things\n        into an image, but still retain the original.\n\n        :rtype: :py:class:`~PIL.Image.Image`\n        :returns: An :py:class:`~PIL.Image.Image` object.\n        \"\"\"\n        self.load()\n        return self._new(self.im.copy())\n\n    __copy__ = copy\n\n    def crop(self, box: tuple[float, float, float, float] | None = None) -> Image:\n        \"\"\"\n        Returns a rectangular region from this image. The box is a\n        4-tuple defining the left, upper, right, and lower pixel\n        coordinate. See :ref:`coordinate-system`.\n\n        Note: Prior to Pillow 3.4.0, this was a lazy operation.\n\n        :param box: The crop rectangle, as a (left, upper, right, lower)-tuple.\n        :rtype: :py:class:`~PIL.Image.Image`\n        :returns: An :py:class:`~PIL.Image.Image` object.\n        \"\"\"\n\n        if box is None:\n            return self.copy()\n\n        if box[2] < box[0]:\n            msg = \"Coordinate 'right' is less than 'left'\"\n            raise ValueError(msg)\n        elif box[3] < box[1]:\n            msg = \"Coordinate 'lower' is less than 'upper'\"\n            raise ValueError(msg)\n\n        self.load()\n        return self._new(self._crop(self.im, box))\n\n    def _crop(\n        self, im: core.ImagingCore, box: tuple[float, float, float, float]\n    ) -> core.ImagingCore:\n        \"\"\"\n        Returns a rectangular region from the core image object im.\n\n        This is equivalent to calling im.crop((x0, y0, x1, y1)), but\n        includes additional sanity checks.\n\n        :param im: a core image object\n        :param box: The crop rectangle, as a (left, upper, right, lower)-tuple.\n        :returns: A core image object.\n        \"\"\"\n\n        x0, y0, x1, y1 = map(int, map(round, box))\n\n        absolute_values = (abs(x1 - x0), abs(y1 - y0))\n\n        _decompression_bomb_check(absolute_values)\n\n        return im.crop((x0, y0, x1, y1))\n\n    def draft(\n        self, mode: str | None, size: tuple[int, int] | None\n    ) -> tuple[str, tuple[int, int, float, float]] | None:\n        \"\"\"\n        Configures the image file loader so it returns a version of the\n        image that as closely as possible matches the given mode and\n        size. For example, you can use this method to convert a color\n        JPEG to grayscale while loading it.\n\n        If any changes are made, returns a tuple with the chosen ``mode`` and\n        ``box`` with coordinates of the original image within the altered one.\n\n        Note that this method modifies the :py:class:`~PIL.Image.Image` object\n        in place. If the image has already been loaded, this method has no\n        effect.\n\n        Note: This method is not implemented for most images. It is\n        currently implemented only for JPEG and MPO images.\n\n        :param mode: The requested mode.\n        :param size: The requested size in pixels, as a 2-tuple:\n           (width, height).\n        \"\"\"\n        pass\n\n    def _expand(self, xmargin: int, ymargin: int | None = None) -> Image:\n        if ymargin is None:\n            ymargin = xmargin\n        self.load()\n        return self._new(self.im.expand(xmargin, ymargin))\n\n    if TYPE_CHECKING:\n        from . import ImageFilter\n\n    def filter(self, filter: ImageFilter.Filter | type[ImageFilter.Filter]) -> Image:\n        \"\"\"\n        Filters this image using the given filter.  For a list of\n        available filters, see the :py:mod:`~PIL.ImageFilter` module.\n\n        :param filter: Filter kernel.\n        :returns: An :py:class:`~PIL.Image.Image` object.\"\"\"\n\n        from . import ImageFilter\n\n        self.load()\n\n        if callable(filter):\n            filter = filter()\n        if not hasattr(filter, \"filter\"):\n            msg = \"filter argument should be ImageFilter.Filter instance or class\"\n            raise TypeError(msg)\n\n        multiband = isinstance(filter, ImageFilter.MultibandFilter)\n        if self.im.bands == 1 or multiband:\n            return self._new(filter.filter(self.im))\n\n        ims = [\n            self._new(filter.filter(self.im.getband(c))) for c in range(self.im.bands)\n        ]\n        return merge(self.mode, ims)\n\n    def getbands(self) -> tuple[str, ...]:\n        \"\"\"\n        Returns a tuple containing the name of each band in this image.\n        For example, ``getbands`` on an RGB image returns (\"R\", \"G\", \"B\").\n\n        :returns: A tuple containing band names.\n        :rtype: tuple\n        \"\"\"\n        return ImageMode.getmode(self.mode).bands\n\n    def getbbox(self, *, alpha_only: bool = True) -> tuple[int, int, int, int] | None:\n        \"\"\"\n        Calculates the bounding box of the non-zero regions in the\n        image.\n\n        :param alpha_only: Optional flag, defaulting to ``True``.\n           If ``True`` and the image has an alpha channel, trim transparent pixels.\n           Otherwise, trim pixels when all channels are zero.\n           Keyword-only argument.\n        :returns: The bounding box is returned as a 4-tuple defining the\n           left, upper, right, and lower pixel coordinate. See\n           :ref:`coordinate-system`. If the image is completely empty, this\n           method returns None.\n\n        \"\"\"\n\n        self.load()\n        return self.im.getbbox(alpha_only)\n\n    def getcolors(self, maxcolors: int = 256):\n        \"\"\"\n        Returns a list of colors used in this image.\n\n        The colors will be in the image's mode. For example, an RGB image will\n        return a tuple of (red, green, blue) color values, and a P image will\n        return the index of the color in the palette.\n\n        :param maxcolors: Maximum number of colors.  If this number is\n           exceeded, this method returns None.  The default limit is\n           256 colors.\n        :returns: An unsorted list of (count, pixel) values.\n        \"\"\"\n\n        self.load()\n        if self.mode in (\"1\", \"L\", \"P\"):\n            h = self.im.histogram()\n            out = [(h[i], i) for i in range(256) if h[i]]\n            if len(out) > maxcolors:\n                return None\n            return out\n        return self.im.getcolors(maxcolors)\n\n    def getdata(self, band: int | None = None):\n        \"\"\"\n        Returns the contents of this image as a sequence object\n        containing pixel values.  The sequence object is flattened, so\n        that values for line one follow directly after the values of\n        line zero, and so on.\n\n        Note that the sequence object returned by this method is an\n        internal PIL data type, which only supports certain sequence\n        operations.  To convert it to an ordinary sequence (e.g. for\n        printing), use ``list(im.getdata())``.\n\n        :param band: What band to return.  The default is to return\n           all bands.  To return a single band, pass in the index\n           value (e.g. 0 to get the \"R\" band from an \"RGB\" image).\n        :returns: A sequence-like object.\n        \"\"\"\n\n        self.load()\n        if band is not None:\n            return self.im.getband(band)\n        return self.im  # could be abused\n\n    def getextrema(self) -> tuple[float, float] | tuple[tuple[int, int], ...]:\n        \"\"\"\n        Gets the minimum and maximum pixel values for each band in\n        the image.\n\n        :returns: For a single-band image, a 2-tuple containing the\n           minimum and maximum pixel value.  For a multi-band image,\n           a tuple containing one 2-tuple for each band.\n        \"\"\"\n\n        self.load()\n        if self.im.bands > 1:\n            return tuple(self.im.getband(i).getextrema() for i in range(self.im.bands))\n        return self.im.getextrema()\n\n    def getxmp(self):\n        \"\"\"\n        Returns a dictionary containing the XMP tags.\n        Requires defusedxml to be installed.\n\n        :returns: XMP tags in a dictionary.\n        \"\"\"\n\n        def get_name(tag: str) -> str:\n            return re.sub(\"^{[^}]+}\", \"\", tag)\n\n        def get_value(element):\n            value = {get_name(k): v for k, v in element.attrib.items()}\n            children = list(element)\n            if children:\n                for child in children:\n                    name = get_name(child.tag)\n                    child_value = get_value(child)\n                    if name in value:\n                        if not isinstance(value[name], list):\n                            value[name] = [value[name]]\n                        value[name].append(child_value)\n                    else:\n                        value[name] = child_value\n            elif value:\n                if element.text:\n                    value[\"text\"] = element.text\n            else:\n                return element.text\n            return value\n\n        if ElementTree is None:\n            warnings.warn(\"XMP data cannot be read without defusedxml dependency\")\n            return {}\n        if \"xmp\" not in self.info:\n            return {}\n        root = ElementTree.fromstring(self.info[\"xmp\"].rstrip(b\"\\x00\"))\n        return {get_name(root.tag): get_value(root)}\n\n    def getexif(self) -> Exif:\n        \"\"\"\n        Gets EXIF data from the image.\n\n        :returns: an :py:class:`~PIL.Image.Exif` object.\n        \"\"\"\n        if self._exif is None:\n            self._exif = Exif()\n        elif self._exif._loaded:\n            return self._exif\n        self._exif._loaded = True\n\n        exif_info = self.info.get(\"exif\")\n        if exif_info is None:\n            if \"Raw profile type exif\" in self.info:\n                exif_info = bytes.fromhex(\n                    \"\".join(self.info[\"Raw profile type exif\"].split(\"\\n\")[3:])\n                )\n            elif hasattr(self, \"tag_v2\"):\n                self._exif.bigtiff = self.tag_v2._bigtiff\n                self._exif.endian = self.tag_v2._endian\n                self._exif.load_from_fp(self.fp, self.tag_v2._offset)\n        if exif_info is not None:\n            self._exif.load(exif_info)\n\n        # XMP tags\n        if ExifTags.Base.Orientation not in self._exif:\n            xmp_tags = self.info.get(\"XML:com.adobe.xmp\")\n            if xmp_tags:\n                match = re.search(r'tiff:Orientation(=\"|>)([0-9])', xmp_tags)\n                if match:\n                    self._exif[ExifTags.Base.Orientation] = int(match[2])\n\n        return self._exif\n\n    def _reload_exif(self) -> None:\n        if self._exif is None or not self._exif._loaded:\n            return\n        self._exif._loaded = False\n        self.getexif()\n\n    def get_child_images(self) -> list[ImageFile.ImageFile]:\n        child_images = []\n        exif = self.getexif()\n        ifds = []\n        if ExifTags.Base.SubIFDs in exif:\n            subifd_offsets = exif[ExifTags.Base.SubIFDs]\n            if subifd_offsets:\n                if not isinstance(subifd_offsets, tuple):\n                    subifd_offsets = (subifd_offsets,)\n                for subifd_offset in subifd_offsets:\n                    ifds.append((exif._get_ifd_dict(subifd_offset), subifd_offset))\n        ifd1 = exif.get_ifd(ExifTags.IFD.IFD1)\n        if ifd1 and ifd1.get(513):\n            ifds.append((ifd1, exif._info.next))\n\n        offset = None\n        for ifd, ifd_offset in ifds:\n            current_offset = self.fp.tell()\n            if offset is None:\n                offset = current_offset\n\n            fp = self.fp\n            thumbnail_offset = ifd.get(513)\n            if thumbnail_offset is not None:\n                thumbnail_offset += getattr(self, \"_exif_offset\", 0)\n                self.fp.seek(thumbnail_offset)\n                data = self.fp.read(ifd.get(514))\n                fp = io.BytesIO(data)\n\n            with open(fp) as im:\n                from . import TiffImagePlugin\n\n                if thumbnail_offset is None and isinstance(\n                    im, TiffImagePlugin.TiffImageFile\n                ):\n                    im._frame_pos = [ifd_offset]\n                    im._seek(0)\n                im.load()\n                child_images.append(im)\n\n        if offset is not None:\n            self.fp.seek(offset)\n        return child_images\n\n    def getim(self):\n        \"\"\"\n        Returns a capsule that points to the internal image memory.\n\n        :returns: A capsule object.\n        \"\"\"\n\n        self.load()\n        return self.im.ptr\n\n    def getpalette(self, rawmode: str | None = \"RGB\") -> list[int] | None:\n        \"\"\"\n        Returns the image palette as a list.\n\n        :param rawmode: The mode in which to return the palette. ``None`` will\n           return the palette in its current mode.\n\n           .. versionadded:: 9.1.0\n\n        :returns: A list of color values [r, g, b, ...], or None if the\n           image has no palette.\n        \"\"\"\n\n        self.load()\n        try:\n            mode = self.im.getpalettemode()\n        except ValueError:\n            return None  # no palette\n        if rawmode is None:\n            rawmode = mode\n        return list(self.im.getpalette(mode, rawmode))\n\n    @property\n    def has_transparency_data(self) -> bool:\n        \"\"\"\n        Determine if an image has transparency data, whether in the form of an\n        alpha channel, a palette with an alpha channel, or a \"transparency\" key\n        in the info dictionary.\n\n        Note the image might still appear solid, if all of the values shown\n        within are opaque.\n\n        :returns: A boolean.\n        \"\"\"\n        return (\n            self.mode in (\"LA\", \"La\", \"PA\", \"RGBA\", \"RGBa\")\n            or (self.mode == \"P\" and self.palette.mode.endswith(\"A\"))\n            or \"transparency\" in self.info\n        )\n\n    def apply_transparency(self) -> None:\n        \"\"\"\n        If a P mode image has a \"transparency\" key in the info dictionary,\n        remove the key and instead apply the transparency to the palette.\n        Otherwise, the image is unchanged.\n        \"\"\"\n        if self.mode != \"P\" or \"transparency\" not in self.info:\n            return\n\n        from . import ImagePalette\n\n        palette = self.getpalette(\"RGBA\")\n        assert palette is not None\n        transparency = self.info[\"transparency\"]\n        if isinstance(transparency, bytes):\n            for i, alpha in enumerate(transparency):\n                palette[i * 4 + 3] = alpha\n        else:\n            palette[transparency * 4 + 3] = 0\n        self.palette = ImagePalette.ImagePalette(\"RGBA\", bytes(palette))\n        self.palette.dirty = 1\n\n        del self.info[\"transparency\"]\n\n    def getpixel(\n        self, xy: tuple[int, int] | list[int]\n    ) -> float | tuple[int, ...] | None:\n        \"\"\"\n        Returns the pixel value at a given position.\n\n        :param xy: The coordinate, given as (x, y). See\n           :ref:`coordinate-system`.\n        :returns: The pixel value.  If the image is a multi-layer image,\n           this method returns a tuple.\n        \"\"\"\n\n        self.load()\n        if self.pyaccess:\n            return self.pyaccess.getpixel(xy)\n        return self.im.getpixel(tuple(xy))\n\n    def getprojection(self) -> tuple[list[int], list[int]]:\n        \"\"\"\n        Get projection to x and y axes\n\n        :returns: Two sequences, indicating where there are non-zero\n            pixels along the X-axis and the Y-axis, respectively.\n        \"\"\"\n\n        self.load()\n        x, y = self.im.getprojection()\n        return list(x), list(y)\n\n    def histogram(self, mask: Image | None = None, extrema=None) -> list[int]:\n        \"\"\"\n        Returns a histogram for the image. The histogram is returned as a\n        list of pixel counts, one for each pixel value in the source\n        image. Counts are grouped into 256 bins for each band, even if\n        the image has more than 8 bits per band. If the image has more\n        than one band, the histograms for all bands are concatenated (for\n        example, the histogram for an \"RGB\" image contains 768 values).\n\n        A bilevel image (mode \"1\") is treated as a grayscale (\"L\") image\n        by this method.\n\n        If a mask is provided, the method returns a histogram for those\n        parts of the image where the mask image is non-zero. The mask\n        image must have the same size as the image, and be either a\n        bi-level image (mode \"1\") or a grayscale image (\"L\").\n\n        :param mask: An optional mask.\n        :param extrema: An optional tuple of manually-specified extrema.\n        :returns: A list containing pixel counts.\n        \"\"\"\n        self.load()\n        if mask:\n            mask.load()\n            return self.im.histogram((0, 0), mask.im)\n        if self.mode in (\"I\", \"F\"):\n            if extrema is None:\n                extrema = self.getextrema()\n            return self.im.histogram(extrema)\n        return self.im.histogram()\n\n    def entropy(self, mask=None, extrema=None):\n        \"\"\"\n        Calculates and returns the entropy for the image.\n\n        A bilevel image (mode \"1\") is treated as a grayscale (\"L\")\n        image by this method.\n\n        If a mask is provided, the method employs the histogram for\n        those parts of the image where the mask image is non-zero.\n        The mask image must have the same size as the image, and be\n        either a bi-level image (mode \"1\") or a grayscale image (\"L\").\n\n        :param mask: An optional mask.\n        :param extrema: An optional tuple of manually-specified extrema.\n        :returns: A float value representing the image entropy\n        \"\"\"\n        self.load()\n        if mask:\n            mask.load()\n            return self.im.entropy((0, 0), mask.im)\n        if self.mode in (\"I\", \"F\"):\n            if extrema is None:\n                extrema = self.getextrema()\n            return self.im.entropy(extrema)\n        return self.im.entropy()\n\n    def paste(\n        self,\n        im: Image | str | float | tuple[float, ...],\n        box: Image | tuple[int, int, int, int] | tuple[int, int] | None = None,\n        mask: Image | None = None,\n    ) -> None:\n        \"\"\"\n        Pastes another image into this image. The box argument is either\n        a 2-tuple giving the upper left corner, a 4-tuple defining the\n        left, upper, right, and lower pixel coordinate, or None (same as\n        (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size\n        of the pasted image must match the size of the region.\n\n        If the modes don't match, the pasted image is converted to the mode of\n        this image (see the :py:meth:`~PIL.Image.Image.convert` method for\n        details).\n\n        Instead of an image, the source can be a integer or tuple\n        containing pixel values.  The method then fills the region\n        with the given color.  When creating RGB images, you can\n        also use color strings as supported by the ImageColor module.\n\n        If a mask is given, this method updates only the regions\n        indicated by the mask. You can use either \"1\", \"L\", \"LA\", \"RGBA\"\n        or \"RGBa\" images (if present, the alpha band is used as mask).\n        Where the mask is 255, the given image is copied as is.  Where\n        the mask is 0, the current value is preserved.  Intermediate\n        values will mix the two images together, including their alpha\n        channels if they have them.\n\n        See :py:meth:`~PIL.Image.Image.alpha_composite` if you want to\n        combine images with respect to their alpha channels.\n\n        :param im: Source image or pixel value (integer, float or tuple).\n        :param box: An optional 4-tuple giving the region to paste into.\n           If a 2-tuple is used instead, it's treated as the upper left\n           corner.  If omitted or None, the source is pasted into the\n           upper left corner.\n\n           If an image is given as the second argument and there is no\n           third, the box defaults to (0, 0), and the second argument\n           is interpreted as a mask image.\n        :param mask: An optional mask image.\n        \"\"\"\n\n        if isImageType(box):\n            if mask is not None:\n                msg = \"If using second argument as mask, third argument must be None\"\n                raise ValueError(msg)\n            # abbreviated paste(im, mask) syntax\n            mask = box\n            box = None\n        assert not isinstance(box, Image)\n\n        if box is None:\n            box = (0, 0)\n\n        if len(box) == 2:\n            # upper left corner given; get size from image or mask\n            if isImageType(im):\n                size = im.size\n            elif isImageType(mask):\n                size = mask.size\n            else:\n                # FIXME: use self.size here?\n                msg = \"cannot determine region size; use 4-item box\"\n                raise ValueError(msg)\n            box += (box[0] + size[0], box[1] + size[1])\n\n        if isinstance(im, str):\n            from . import ImageColor\n\n            im = ImageColor.getcolor(im, self.mode)\n\n        elif isImageType(im):\n            im.load()\n            if self.mode != im.mode:\n                if self.mode != \"RGB\" or im.mode not in (\"LA\", \"RGBA\", \"RGBa\"):\n                    # should use an adapter for this!\n                    im = im.convert(self.mode)\n            im = im.im\n\n        self._ensure_mutable()\n\n        if mask:\n            mask.load()\n            self.im.paste(im, box, mask.im)\n        else:\n            self.im.paste(im, box)\n\n    def alpha_composite(\n        self, im: Image, dest: Sequence[int] = (0, 0), source: Sequence[int] = (0, 0)\n    ) -> None:\n        \"\"\"'In-place' analog of Image.alpha_composite. Composites an image\n        onto this image.\n\n        :param im: image to composite over this one\n        :param dest: Optional 2 tuple (left, top) specifying the upper\n          left corner in this (destination) image.\n        :param source: Optional 2 (left, top) tuple for the upper left\n          corner in the overlay source image, or 4 tuple (left, top, right,\n          bottom) for the bounds of the source rectangle\n\n        Performance Note: Not currently implemented in-place in the core layer.\n        \"\"\"\n\n        if not isinstance(source, (list, tuple)):\n            msg = \"Source must be a list or tuple\"\n            raise ValueError(msg)\n        if not isinstance(dest, (list, tuple)):\n            msg = \"Destination must be a list or tuple\"\n            raise ValueError(msg)\n\n        if len(source) == 4:\n            overlay_crop_box = tuple(source)\n        elif len(source) == 2:\n            overlay_crop_box = tuple(source) + im.size\n        else:\n            msg = \"Source must be a sequence of length 2 or 4\"\n            raise ValueError(msg)\n\n        if not len(dest) == 2:\n            msg = \"Destination must be a sequence of length 2\"\n            raise ValueError(msg)\n        if min(source) < 0:\n            msg = \"Source must be non-negative\"\n            raise ValueError(msg)\n\n        # over image, crop if it's not the whole image.\n        if overlay_crop_box == (0, 0) + im.size:\n            overlay = im\n        else:\n            overlay = im.crop(overlay_crop_box)\n\n        # target for the paste\n        box = tuple(dest) + (dest[0] + overlay.width, dest[1] + overlay.height)\n\n        # destination image. don't copy if we're using the whole image.\n        if box == (0, 0) + self.size:\n            background = self\n        else:\n            background = self.crop(box)\n\n        result = alpha_composite(background, overlay)\n        self.paste(result, box)\n\n    def point(\n        self,\n        lut: Sequence[float] | Callable[[int], float] | ImagePointHandler,\n        mode: str | None = None,\n    ) -> Image:\n        \"\"\"\n        Maps this image through a lookup table or function.\n\n        :param lut: A lookup table, containing 256 (or 65536 if\n           self.mode==\"I\" and mode == \"L\") values per band in the\n           image.  A function can be used instead, it should take a\n           single argument. The function is called once for each\n           possible pixel value, and the resulting table is applied to\n           all bands of the image.\n\n           It may also be an :py:class:`~PIL.Image.ImagePointHandler`\n           object::\n\n               class Example(Image.ImagePointHandler):\n                 def point(self, data):\n                   # Return result\n        :param mode: Output mode (default is same as input). This can only be used if\n           the source image has mode \"L\" or \"P\", and the output has mode \"1\" or the\n           source image mode is \"I\" and the output mode is \"L\".\n        :returns: An :py:class:`~PIL.Image.Image` object.\n        \"\"\"\n\n        self.load()\n\n        if isinstance(lut, ImagePointHandler):\n            return lut.point(self)\n\n        if callable(lut):\n            # if it isn't a list, it should be a function\n            if self.mode in (\"I\", \"I;16\", \"F\"):\n                # check if the function can be used with point_transform\n                # UNDONE wiredfool -- I think this prevents us from ever doing\n                # a gamma function point transform on > 8bit images.\n                scale, offset = _getscaleoffset(lut)\n                return self._new(self.im.point_transform(scale, offset))\n            # for other modes, convert the function to a table\n            flatLut = [lut(i) for i in range(256)] * self.im.bands\n        else:\n            flatLut = lut\n\n        if self.mode == \"F\":\n            # FIXME: _imaging returns a confusing error message for this case\n            msg = \"point operation not supported for this mode\"\n            raise ValueError(msg)\n\n        if mode != \"F\":\n            flatLut = [round(i) for i in flatLut]\n        return self._new(self.im.point(flatLut, mode))\n\n    def putalpha(self, alpha: Image | int) -> None:\n        \"\"\"\n        Adds or replaces the alpha layer in this image.  If the image\n        does not have an alpha layer, it's converted to \"LA\" or \"RGBA\".\n        The new layer must be either \"L\" or \"1\".\n\n        :param alpha: The new alpha layer.  This can either be an \"L\" or \"1\"\n           image having the same size as this image, or an integer.\n        \"\"\"\n\n        self._ensure_mutable()\n\n        if self.mode not in (\"LA\", \"PA\", \"RGBA\"):\n            # attempt to promote self to a matching alpha mode\n            try:\n                mode = getmodebase(self.mode) + \"A\"\n                try:\n                    self.im.setmode(mode)\n                except (AttributeError, ValueError) as e:\n                    # do things the hard way\n                    im = self.im.convert(mode)\n                    if im.mode not in (\"LA\", \"PA\", \"RGBA\"):\n                        msg = \"alpha channel could not be added\"\n                        raise ValueError(msg) from e  # sanity check\n                    self.im = im\n                self.pyaccess = None\n                self._mode = self.im.mode\n            except KeyError as e:\n                msg = \"illegal image mode\"\n                raise ValueError(msg) from e\n\n        if self.mode in (\"LA\", \"PA\"):\n            band = 1\n        else:\n            band = 3\n\n        if isImageType(alpha):\n            # alpha layer\n            if alpha.mode not in (\"1\", \"L\"):\n                msg = \"illegal image mode\"\n                raise ValueError(msg)\n            alpha.load()\n            if alpha.mode == \"1\":\n                alpha = alpha.convert(\"L\")\n        else:\n            # constant alpha\n            alpha = cast(int, alpha)  # see python/typing#1013\n            try:\n                self.im.fillband(band, alpha)\n            except (AttributeError, ValueError):\n                # do things the hard way\n                alpha = new(\"L\", self.size, alpha)\n            else:\n                return\n\n        self.im.putband(alpha.im, band)\n\n    def putdata(\n        self,\n        data: Sequence[float] | Sequence[Sequence[int]],\n        scale: float = 1.0,\n        offset: float = 0.0,\n    ) -> None:\n        \"\"\"\n        Copies pixel data from a flattened sequence object into the image. The\n        values should start at the upper left corner (0, 0), continue to the\n        end of the line, followed directly by the first value of the second\n        line, and so on. Data will be read until either the image or the\n        sequence ends. The scale and offset values are used to adjust the\n        sequence values: **pixel = value*scale + offset**.\n\n        :param data: A flattened sequence object.\n        :param scale: An optional scale value.  The default is 1.0.\n        :param offset: An optional offset value.  The default is 0.0.\n        \"\"\"\n\n        self._ensure_mutable()\n\n        self.im.putdata(data, scale, offset)\n\n    def putpalette(self, data, rawmode=\"RGB\") -> None:\n        \"\"\"\n        Attaches a palette to this image.  The image must be a \"P\", \"PA\", \"L\"\n        or \"LA\" image.\n\n        The palette sequence must contain at most 256 colors, made up of one\n        integer value for each channel in the raw mode.\n        For example, if the raw mode is \"RGB\", then it can contain at most 768\n        values, made up of red, green and blue values for the corresponding pixel\n        index in the 256 colors.\n        If the raw mode is \"RGBA\", then it can contain at most 1024 values,\n        containing red, green, blue and alpha values.\n\n        Alternatively, an 8-bit string may be used instead of an integer sequence.\n\n        :param data: A palette sequence (either a list or a string).\n        :param rawmode: The raw mode of the palette. Either \"RGB\", \"RGBA\", or a mode\n           that can be transformed to \"RGB\" or \"RGBA\" (e.g. \"R\", \"BGR;15\", \"RGBA;L\").\n        \"\"\"\n        from . import ImagePalette\n\n        if self.mode not in (\"L\", \"LA\", \"P\", \"PA\"):\n            msg = \"illegal image mode\"\n            raise ValueError(msg)\n        if isinstance(data, ImagePalette.ImagePalette):\n            palette = ImagePalette.raw(data.rawmode, data.palette)\n        else:\n            if not isinstance(data, bytes):\n                data = bytes(data)\n            palette = ImagePalette.raw(rawmode, data)\n        self._mode = \"PA\" if \"A\" in self.mode else \"P\"\n        self.palette = palette\n        self.palette.mode = \"RGBA\" if \"A\" in rawmode else \"RGB\"\n        self.load()  # install new palette\n\n    def putpixel(\n        self, xy: tuple[int, int], value: float | tuple[int, ...] | list[int]\n    ) -> None:\n        \"\"\"\n        Modifies the pixel at the given position. The color is given as\n        a single numerical value for single-band images, and a tuple for\n        multi-band images. In addition to this, RGB and RGBA tuples are\n        accepted for P and PA images.\n\n        Note that this method is relatively slow.  For more extensive changes,\n        use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw`\n        module instead.\n\n        See:\n\n        * :py:meth:`~PIL.Image.Image.paste`\n        * :py:meth:`~PIL.Image.Image.putdata`\n        * :py:mod:`~PIL.ImageDraw`\n\n        :param xy: The pixel coordinate, given as (x, y). See\n           :ref:`coordinate-system`.\n        :param value: The pixel value.\n        \"\"\"\n\n        if self.readonly:\n            self._copy()\n        self.load()\n\n        if self.pyaccess:\n            return self.pyaccess.putpixel(xy, value)\n\n        if (\n            self.mode in (\"P\", \"PA\")\n            and isinstance(value, (list, tuple))\n            and len(value) in [3, 4]\n        ):\n            # RGB or RGBA value for a P or PA image\n            if self.mode == \"PA\":\n                alpha = value[3] if len(value) == 4 else 255\n                value = value[:3]\n            palette_index = self.palette.getcolor(value, self)\n            value = (palette_index, alpha) if self.mode == \"PA\" else palette_index\n        return self.im.putpixel(xy, value)\n\n    def remap_palette(self, dest_map, source_palette=None):\n        \"\"\"\n        Rewrites the image to reorder the palette.\n\n        :param dest_map: A list of indexes into the original palette.\n           e.g. ``[1,0]`` would swap a two item palette, and ``list(range(256))``\n           is the identity transform.\n        :param source_palette: Bytes or None.\n        :returns:  An :py:class:`~PIL.Image.Image` object.\n\n        \"\"\"\n        from . import ImagePalette\n\n        if self.mode not in (\"L\", \"P\"):\n            msg = \"illegal image mode\"\n            raise ValueError(msg)\n\n        bands = 3\n        palette_mode = \"RGB\"\n        if source_palette is None:\n            if self.mode == \"P\":\n                self.load()\n                palette_mode = self.im.getpalettemode()\n                if palette_mode == \"RGBA\":\n                    bands = 4\n                source_palette = self.im.getpalette(palette_mode, palette_mode)\n            else:  # L-mode\n                source_palette = bytearray(i // 3 for i in range(768))\n\n        palette_bytes = b\"\"\n        new_positions = [0] * 256\n\n        # pick only the used colors from the palette\n        for i, oldPosition in enumerate(dest_map):\n            palette_bytes += source_palette[\n                oldPosition * bands : oldPosition * bands + bands\n            ]\n            new_positions[oldPosition] = i\n\n        # replace the palette color id of all pixel with the new id\n\n        # Palette images are [0..255], mapped through a 1 or 3\n        # byte/color map.  We need to remap the whole image\n        # from palette 1 to palette 2. New_positions is\n        # an array of indexes into palette 1.  Palette 2 is\n        # palette 1 with any holes removed.\n\n        # We're going to leverage the convert mechanism to use the\n        # C code to remap the image from palette 1 to palette 2,\n        # by forcing the source image into 'L' mode and adding a\n        # mapping 'L' mode palette, then converting back to 'L'\n        # sans palette thus converting the image bytes, then\n        # assigning the optimized RGB palette.\n\n        # perf reference, 9500x4000 gif, w/~135 colors\n        # 14 sec prepatch, 1 sec postpatch with optimization forced.\n\n        mapping_palette = bytearray(new_positions)\n\n        m_im = self.copy()\n        m_im._mode = \"P\"\n\n        m_im.palette = ImagePalette.ImagePalette(\n            palette_mode, palette=mapping_palette * bands\n        )\n        # possibly set palette dirty, then\n        # m_im.putpalette(mapping_palette, 'L')  # converts to 'P'\n        # or just force it.\n        # UNDONE -- this is part of the general issue with palettes\n        m_im.im.putpalette(palette_mode, palette_mode + \";L\", m_im.palette.tobytes())\n\n        m_im = m_im.convert(\"L\")\n\n        m_im.putpalette(palette_bytes, palette_mode)\n        m_im.palette = ImagePalette.ImagePalette(palette_mode, palette=palette_bytes)\n\n        if \"transparency\" in self.info:\n            try:\n                m_im.info[\"transparency\"] = dest_map.index(self.info[\"transparency\"])\n            except ValueError:\n                if \"transparency\" in m_im.info:\n                    del m_im.info[\"transparency\"]\n\n        return m_im\n\n    def _get_safe_box(self, size, resample, box):\n        \"\"\"Expands the box so it includes adjacent pixels\n        that may be used by resampling with the given resampling filter.\n        \"\"\"\n        filter_support = _filters_support[resample] - 0.5\n        scale_x = (box[2] - box[0]) / size[0]\n        scale_y = (box[3] - box[1]) / size[1]\n        support_x = filter_support * scale_x\n        support_y = filter_support * scale_y\n\n        return (\n            max(0, int(box[0] - support_x)),\n            max(0, int(box[1] - support_y)),\n            min(self.size[0], math.ceil(box[2] + support_x)),\n            min(self.size[1], math.ceil(box[3] + support_y)),\n        )\n\n    def resize(\n        self,\n        size: tuple[int, int],\n        resample: int | None = None,\n        box: tuple[float, float, float, float] | None = None,\n        reducing_gap: float | None = None,\n    ) -> Image:\n        \"\"\"\n        Returns a resized copy of this image.\n\n        :param size: The requested size in pixels, as a 2-tuple:\n           (width, height).\n        :param resample: An optional resampling filter.  This can be\n           one of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`,\n           :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`,\n           :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`.\n           If the image has mode \"1\" or \"P\", it is always set to\n           :py:data:`Resampling.NEAREST`. If the image mode specifies a number\n           of bits, such as \"I;16\", then the default filter is\n           :py:data:`Resampling.NEAREST`. Otherwise, the default filter is\n           :py:data:`Resampling.BICUBIC`. See: :ref:`concept-filters`.\n        :param box: An optional 4-tuple of floats providing\n           the source image region to be scaled.\n           The values must be within (0, 0, width, height) rectangle.\n           If omitted or None, the entire source is used.\n        :param reducing_gap: Apply optimization by resizing the image\n           in two steps. First, reducing the image by integer times\n           using :py:meth:`~PIL.Image.Image.reduce`.\n           Second, resizing using regular resampling. The last step\n           changes size no less than by ``reducing_gap`` times.\n           ``reducing_gap`` may be None (no first step is performed)\n           or should be greater than 1.0. The bigger ``reducing_gap``,\n           the closer the result to the fair resampling.\n           The smaller ``reducing_gap``, the faster resizing.\n           With ``reducing_gap`` greater or equal to 3.0, the result is\n           indistinguishable from fair resampling in most cases.\n           The default value is None (no optimization).\n        :returns: An :py:class:`~PIL.Image.Image` object.\n        \"\"\"\n\n        if resample is None:\n            type_special = \";\" in self.mode\n            resample = Resampling.NEAREST if type_special else Resampling.BICUBIC\n        elif resample not in (\n            Resampling.NEAREST,\n            Resampling.BILINEAR,\n            Resampling.BICUBIC,\n            Resampling.LANCZOS,\n            Resampling.BOX,\n            Resampling.HAMMING,\n        ):\n            msg = f\"Unknown resampling filter ({resample}).\"\n\n            filters = [\n                f\"{filter[1]} ({filter[0]})\"\n                for filter in (\n                    (Resampling.NEAREST, \"Image.Resampling.NEAREST\"),\n                    (Resampling.LANCZOS, \"Image.Resampling.LANCZOS\"),\n                    (Resampling.BILINEAR, \"Image.Resampling.BILINEAR\"),\n                    (Resampling.BICUBIC, \"Image.Resampling.BICUBIC\"),\n                    (Resampling.BOX, \"Image.Resampling.BOX\"),\n                    (Resampling.HAMMING, \"Image.Resampling.HAMMING\"),\n                )\n            ]\n            msg += f\" Use {', '.join(filters[:-1])} or {filters[-1]}\"\n            raise ValueError(msg)\n\n        if reducing_gap is not None and reducing_gap < 1.0:\n            msg = \"reducing_gap must be 1.0 or greater\"\n            raise ValueError(msg)\n\n        self.load()\n        if box is None:\n            box = (0, 0) + self.size\n\n        if self.size == size and box == (0, 0) + self.size:\n            return self.copy()\n\n        if self.mode in (\"1\", \"P\"):\n            resample = Resampling.NEAREST\n\n        if self.mode in [\"LA\", \"RGBA\"] and resample != Resampling.NEAREST:\n            im = self.convert({\"LA\": \"La\", \"RGBA\": \"RGBa\"}[self.mode])\n            im = im.resize(size, resample, box)\n            return im.convert(self.mode)\n\n        self.load()\n\n        if reducing_gap is not None and resample != Resampling.NEAREST:\n            factor_x = int((box[2] - box[0]) / size[0] / reducing_gap) or 1\n            factor_y = int((box[3] - box[1]) / size[1] / reducing_gap) or 1\n            if factor_x > 1 or factor_y > 1:\n                reduce_box = self._get_safe_box(size, resample, box)\n                factor = (factor_x, factor_y)\n                self = (\n                    self.reduce(factor, box=reduce_box)\n                    if callable(self.reduce)\n                    else Image.reduce(self, factor, box=reduce_box)\n                )\n                box = (\n                    (box[0] - reduce_box[0]) / factor_x,\n                    (box[1] - reduce_box[1]) / factor_y,\n                    (box[2] - reduce_box[0]) / factor_x,\n                    (box[3] - reduce_box[1]) / factor_y,\n                )\n\n        return self._new(self.im.resize(size, resample, box))\n\n    def reduce(\n        self,\n        factor: int | tuple[int, int],\n        box: tuple[int, int, int, int] | None = None,\n    ) -> Image:\n        \"\"\"\n        Returns a copy of the image reduced ``factor`` times.\n        If the size of the image is not dividable by ``factor``,\n        the resulting size will be rounded up.\n\n        :param factor: A greater than 0 integer or tuple of two integers\n           for width and height separately.\n        :param box: An optional 4-tuple of ints providing\n           the source image region to be reduced.\n           The values must be within ``(0, 0, width, height)`` rectangle.\n           If omitted or ``None``, the entire source is used.\n        \"\"\"\n        if not isinstance(factor, (list, tuple)):\n            factor = (factor, factor)\n\n        if box is None:\n            box = (0, 0) + self.size\n\n        if factor == (1, 1) and box == (0, 0) + self.size:\n            return self.copy()\n\n        if self.mode in [\"LA\", \"RGBA\"]:\n            im = self.convert({\"LA\": \"La\", \"RGBA\": \"RGBa\"}[self.mode])\n            im = im.reduce(factor, box)\n            return im.convert(self.mode)\n\n        self.load()\n\n        return self._new(self.im.reduce(factor, box))\n\n    def rotate(\n        self,\n        angle: float,\n        resample: Resampling = Resampling.NEAREST,\n        expand: int | bool = False,\n        center: tuple[float, float] | None = None,\n        translate: tuple[int, int] | None = None,\n        fillcolor: float | tuple[float, ...] | str | None = None,\n    ) -> Image:\n        \"\"\"\n        Returns a rotated copy of this image.  This method returns a\n        copy of this image, rotated the given number of degrees counter\n        clockwise around its centre.\n\n        :param angle: In degrees counter clockwise.\n        :param resample: An optional resampling filter.  This can be\n           one of :py:data:`Resampling.NEAREST` (use nearest neighbour),\n           :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2\n           environment), or :py:data:`Resampling.BICUBIC` (cubic spline\n           interpolation in a 4x4 environment). If omitted, or if the image has\n           mode \"1\" or \"P\", it is set to :py:data:`Resampling.NEAREST`.\n           See :ref:`concept-filters`.\n        :param expand: Optional expansion flag.  If true, expands the output\n           image to make it large enough to hold the entire rotated image.\n           If false or omitted, make the output image the same size as the\n           input image.  Note that the expand flag assumes rotation around\n           the center and no translation.\n        :param center: Optional center of rotation (a 2-tuple).  Origin is\n           the upper left corner.  Default is the center of the image.\n        :param translate: An optional post-rotate translation (a 2-tuple).\n        :param fillcolor: An optional color for area outside the rotated image.\n        :returns: An :py:class:`~PIL.Image.Image` object.\n        \"\"\"\n\n        angle = angle % 360.0\n\n        # Fast paths regardless of filter, as long as we're not\n        # translating or changing the center.\n        if not (center or translate):\n            if angle == 0:\n                return self.copy()\n            if angle == 180:\n                return self.transpose(Transpose.ROTATE_180)\n            if angle in (90, 270) and (expand or self.width == self.height):\n                return self.transpose(\n                    Transpose.ROTATE_90 if angle == 90 else Transpose.ROTATE_270\n                )\n\n        # Calculate the affine matrix.  Note that this is the reverse\n        # transformation (from destination image to source) because we\n        # want to interpolate the (discrete) destination pixel from\n        # the local area around the (floating) source pixel.\n\n        # The matrix we actually want (note that it operates from the right):\n        # (1, 0, tx)   (1, 0, cx)   ( cos a, sin a, 0)   (1, 0, -cx)\n        # (0, 1, ty) * (0, 1, cy) * (-sin a, cos a, 0) * (0, 1, -cy)\n        # (0, 0,  1)   (0, 0,  1)   (     0,     0, 1)   (0, 0,   1)\n\n        # The reverse matrix is thus:\n        # (1, 0, cx)   ( cos -a, sin -a, 0)   (1, 0, -cx)   (1, 0, -tx)\n        # (0, 1, cy) * (-sin -a, cos -a, 0) * (0, 1, -cy) * (0, 1, -ty)\n        # (0, 0,  1)   (      0,      0, 1)   (0, 0,   1)   (0, 0,   1)\n\n        # In any case, the final translation may be updated at the end to\n        # compensate for the expand flag.\n\n        w, h = self.size\n\n        if translate is None:\n            post_trans = (0, 0)\n        else:\n            post_trans = translate\n        if center is None:\n            center = (w / 2, h / 2)\n\n        angle = -math.radians(angle)\n        matrix = [\n            round(math.cos(angle), 15),\n            round(math.sin(angle), 15),\n            0.0,\n            round(-math.sin(angle), 15),\n            round(math.cos(angle), 15),\n            0.0,\n        ]\n\n        def transform(x, y, matrix):\n            (a, b, c, d, e, f) = matrix\n            return a * x + b * y + c, d * x + e * y + f\n\n        matrix[2], matrix[5] = transform(\n            -center[0] - post_trans[0], -center[1] - post_trans[1], matrix\n        )\n        matrix[2] += center[0]\n        matrix[5] += center[1]\n\n        if expand:\n            # calculate output size\n            xx = []\n            yy = []\n            for x, y in ((0, 0), (w, 0), (w, h), (0, h)):\n                x, y = transform(x, y, matrix)\n                xx.append(x)\n                yy.append(y)\n            nw = math.ceil(max(xx)) - math.floor(min(xx))\n            nh = math.ceil(max(yy)) - math.floor(min(yy))\n\n            # We multiply a translation matrix from the right.  Because of its\n            # special form, this is the same as taking the image of the\n            # translation vector as new translation vector.\n            matrix[2], matrix[5] = transform(-(nw - w) / 2.0, -(nh - h) / 2.0, matrix)\n            w, h = nw, nh\n\n        return self.transform(\n            (w, h), Transform.AFFINE, matrix, resample, fillcolor=fillcolor\n        )\n\n    def save(\n        self, fp: StrOrBytesPath | IO[bytes], format: str | None = None, **params: Any\n    ) -> None:\n        \"\"\"\n        Saves this image under the given filename.  If no format is\n        specified, the format to use is determined from the filename\n        extension, if possible.\n\n        Keyword options can be used to provide additional instructions\n        to the writer. If a writer doesn't recognise an option, it is\n        silently ignored. The available options are described in the\n        :doc:`image format documentation\n        <../handbook/image-file-formats>` for each writer.\n\n        You can use a file object instead of a filename. In this case,\n        you must always specify the format. The file object must\n        implement the ``seek``, ``tell``, and ``write``\n        methods, and be opened in binary mode.\n\n        :param fp: A filename (string), os.PathLike object or file object.\n        :param format: Optional format override.  If omitted, the\n           format to use is determined from the filename extension.\n           If a file object was used instead of a filename, this\n           parameter should always be used.\n        :param params: Extra parameters to the image writer.\n        :returns: None\n        :exception ValueError: If the output format could not be determined\n           from the file name.  Use the format option to solve this.\n        :exception OSError: If the file could not be written.  The file\n           may have been created, and may contain partial data.\n        \"\"\"\n\n        filename: str | bytes = \"\"\n        open_fp = False\n        if is_path(fp):\n            filename = os.path.realpath(os.fspath(fp))\n            open_fp = True\n        elif fp == sys.stdout:\n            try:\n                fp = sys.stdout.buffer\n            except AttributeError:\n                pass\n        if not filename and hasattr(fp, \"name\") and is_path(fp.name):\n            # only set the name for metadata purposes\n            filename = os.path.realpath(os.fspath(fp.name))\n\n        # may mutate self!\n        self._ensure_mutable()\n\n        save_all = params.pop(\"save_all\", False)\n        self.encoderinfo = params\n        self.encoderconfig: tuple[Any, ...] = ()\n\n        preinit()\n\n        filename_ext = os.path.splitext(filename)[1].lower()\n        ext = filename_ext.decode() if isinstance(filename_ext, bytes) else filename_ext\n\n        if not format:\n            if ext not in EXTENSION:\n                init()\n            try:\n                format = EXTENSION[ext]\n            except KeyError as e:\n                msg = f\"unknown file extension: {ext}\"\n                raise ValueError(msg) from e\n\n        if format.upper() not in SAVE:\n            init()\n        if save_all:\n            save_handler = SAVE_ALL[format.upper()]\n        else:\n            save_handler = SAVE[format.upper()]\n\n        created = False\n        if open_fp:\n            created = not os.path.exists(filename)\n            if params.get(\"append\", False):\n                # Open also for reading (\"+\"), because TIFF save_all\n                # writer needs to go back and edit the written data.\n                fp = builtins.open(filename, \"r+b\")\n            else:\n                fp = builtins.open(filename, \"w+b\")\n        else:\n            fp = cast(IO[bytes], fp)\n\n        try:\n            save_handler(self, fp, filename)\n        except Exception:\n            if open_fp:\n                fp.close()\n            if created:\n                try:\n                    os.remove(filename)\n                except PermissionError:\n                    pass\n            raise\n        if open_fp:\n            fp.close()\n\n    def seek(self, frame: int) -> None:\n        \"\"\"\n        Seeks to the given frame in this sequence file. If you seek\n        beyond the end of the sequence, the method raises an\n        ``EOFError`` exception. When a sequence file is opened, the\n        library automatically seeks to frame 0.\n\n        See :py:meth:`~PIL.Image.Image.tell`.\n\n        If defined, :attr:`~PIL.Image.Image.n_frames` refers to the\n        number of available frames.\n\n        :param frame: Frame number, starting at 0.\n        :exception EOFError: If the call attempts to seek beyond the end\n            of the sequence.\n        \"\"\"\n\n        # overridden by file handlers\n        if frame != 0:\n            msg = \"no more images in file\"\n            raise EOFError(msg)\n\n    def show(self, title: str | None = None) -> None:\n        \"\"\"\n        Displays this image. This method is mainly intended for debugging purposes.\n\n        This method calls :py:func:`PIL.ImageShow.show` internally. You can use\n        :py:func:`PIL.ImageShow.register` to override its default behaviour.\n\n        The image is first saved to a temporary file. By default, it will be in\n        PNG format.\n\n        On Unix, the image is then opened using the **xdg-open**, **display**,\n        **gm**, **eog** or **xv** utility, depending on which one can be found.\n\n        On macOS, the image is opened with the native Preview application.\n\n        On Windows, the image is opened with the standard PNG display utility.\n\n        :param title: Optional title to use for the image window, where possible.\n        \"\"\"\n\n        _show(self, title=title)\n\n    def split(self) -> tuple[Image, ...]:\n        \"\"\"\n        Split this image into individual bands. This method returns a\n        tuple of individual image bands from an image. For example,\n        splitting an \"RGB\" image creates three new images each\n        containing a copy of one of the original bands (red, green,\n        blue).\n\n        If you need only one band, :py:meth:`~PIL.Image.Image.getchannel`\n        method can be more convenient and faster.\n\n        :returns: A tuple containing bands.\n        \"\"\"\n\n        self.load()\n        if self.im.bands == 1:\n            return (self.copy(),)\n        return tuple(map(self._new, self.im.split()))\n\n    def getchannel(self, channel: int | str) -> Image:\n        \"\"\"\n        Returns an image containing a single channel of the source image.\n\n        :param channel: What channel to return. Could be index\n          (0 for \"R\" channel of \"RGB\") or channel name\n          (\"A\" for alpha channel of \"RGBA\").\n        :returns: An image in \"L\" mode.\n\n        .. versionadded:: 4.3.0\n        \"\"\"\n        self.load()\n\n        if isinstance(channel, str):\n            try:\n                channel = self.getbands().index(channel)\n            except ValueError as e:\n                msg = f'The image has no channel \"{channel}\"'\n                raise ValueError(msg) from e\n\n        return self._new(self.im.getband(channel))\n\n    def tell(self) -> int:\n        \"\"\"\n        Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`.\n\n        If defined, :attr:`~PIL.Image.Image.n_frames` refers to the\n        number of available frames.\n\n        :returns: Frame number, starting with 0.\n        \"\"\"\n        return 0\n\n    def thumbnail(\n        self,\n        size: tuple[float, float],\n        resample: Resampling = Resampling.BICUBIC,\n        reducing_gap: float | None = 2.0,\n    ) -> None:\n        \"\"\"\n        Make this image into a thumbnail.  This method modifies the\n        image to contain a thumbnail version of itself, no larger than\n        the given size.  This method calculates an appropriate thumbnail\n        size to preserve the aspect of the image, calls the\n        :py:meth:`~PIL.Image.Image.draft` method to configure the file reader\n        (where applicable), and finally resizes the image.\n\n        Note that this function modifies the :py:class:`~PIL.Image.Image`\n        object in place.  If you need to use the full resolution image as well,\n        apply this method to a :py:meth:`~PIL.Image.Image.copy` of the original\n        image.\n\n        :param size: The requested size in pixels, as a 2-tuple:\n           (width, height).\n        :param resample: Optional resampling filter.  This can be one\n           of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`,\n           :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`,\n           :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`.\n           If omitted, it defaults to :py:data:`Resampling.BICUBIC`.\n           (was :py:data:`Resampling.NEAREST` prior to version 2.5.0).\n           See: :ref:`concept-filters`.\n        :param reducing_gap: Apply optimization by resizing the image\n           in two steps. First, reducing the image by integer times\n           using :py:meth:`~PIL.Image.Image.reduce` or\n           :py:meth:`~PIL.Image.Image.draft` for JPEG images.\n           Second, resizing using regular resampling. The last step\n           changes size no less than by ``reducing_gap`` times.\n           ``reducing_gap`` may be None (no first step is performed)\n           or should be greater than 1.0. The bigger ``reducing_gap``,\n           the closer the result to the fair resampling.\n           The smaller ``reducing_gap``, the faster resizing.\n           With ``reducing_gap`` greater or equal to 3.0, the result is\n           indistinguishable from fair resampling in most cases.\n           The default value is 2.0 (very close to fair resampling\n           while still being faster in many cases).\n        :returns: None\n        \"\"\"\n\n        provided_size = tuple(map(math.floor, size))\n\n        def preserve_aspect_ratio() -> tuple[int, int] | None:\n            def round_aspect(number, key):\n                return max(min(math.floor(number), math.ceil(number), key=key), 1)\n\n            x, y = provided_size\n            if x >= self.width and y >= self.height:\n                return None\n\n            aspect = self.width / self.height\n            if x / y >= aspect:\n                x = round_aspect(y * aspect, key=lambda n: abs(aspect - n / y))\n            else:\n                y = round_aspect(\n                    x / aspect, key=lambda n: 0 if n == 0 else abs(aspect - x / n)\n                )\n            return x, y\n\n        box = None\n        final_size: tuple[int, int]\n        if reducing_gap is not None:\n            preserved_size = preserve_aspect_ratio()\n            if preserved_size is None:\n                return\n            final_size = preserved_size\n\n            res = self.draft(\n                None, (int(size[0] * reducing_gap), int(size[1] * reducing_gap))\n            )\n            if res is not None:\n                box = res[1]\n        if box is None:\n            self.load()\n\n            # load() may have changed the size of the image\n            preserved_size = preserve_aspect_ratio()\n            if preserved_size is None:\n                return\n            final_size = preserved_size\n\n        if self.size != final_size:\n            im = self.resize(final_size, resample, box=box, reducing_gap=reducing_gap)\n\n            self.im = im.im\n            self._size = final_size\n            self._mode = self.im.mode\n\n        self.readonly = 0\n        self.pyaccess = None\n\n    # FIXME: the different transform methods need further explanation\n    # instead of bloating the method docs, add a separate chapter.\n    def transform(\n        self,\n        size: tuple[int, int],\n        method: Transform | ImageTransformHandler | SupportsGetData,\n        data: Sequence[Any] | None = None,\n        resample: int = Resampling.NEAREST,\n        fill: int = 1,\n        fillcolor: float | tuple[float, ...] | str | None = None,\n    ) -> Image:\n        \"\"\"\n        Transforms this image.  This method creates a new image with the\n        given size, and the same mode as the original, and copies data\n        to the new image using the given transform.\n\n        :param size: The output size in pixels, as a 2-tuple:\n           (width, height).\n        :param method: The transformation method.  This is one of\n          :py:data:`Transform.EXTENT` (cut out a rectangular subregion),\n          :py:data:`Transform.AFFINE` (affine transform),\n          :py:data:`Transform.PERSPECTIVE` (perspective transform),\n          :py:data:`Transform.QUAD` (map a quadrilateral to a rectangle), or\n          :py:data:`Transform.MESH` (map a number of source quadrilaterals\n          in one operation).\n\n          It may also be an :py:class:`~PIL.Image.ImageTransformHandler`\n          object::\n\n            class Example(Image.ImageTransformHandler):\n                def transform(self, size, data, resample, fill=1):\n                    # Return result\n\n          Implementations of :py:class:`~PIL.Image.ImageTransformHandler`\n          for some of the :py:class:`Transform` methods are provided\n          in :py:mod:`~PIL.ImageTransform`.\n\n          It may also be an object with a ``method.getdata`` method\n          that returns a tuple supplying new ``method`` and ``data`` values::\n\n            class Example:\n                def getdata(self):\n                    method = Image.Transform.EXTENT\n                    data = (0, 0, 100, 100)\n                    return method, data\n        :param data: Extra data to the transformation method.\n        :param resample: Optional resampling filter.  It can be one of\n           :py:data:`Resampling.NEAREST` (use nearest neighbour),\n           :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2\n           environment), or :py:data:`Resampling.BICUBIC` (cubic spline\n           interpolation in a 4x4 environment). If omitted, or if the image\n           has mode \"1\" or \"P\", it is set to :py:data:`Resampling.NEAREST`.\n           See: :ref:`concept-filters`.\n        :param fill: If ``method`` is an\n          :py:class:`~PIL.Image.ImageTransformHandler` object, this is one of\n          the arguments passed to it. Otherwise, it is unused.\n        :param fillcolor: Optional fill color for the area outside the\n           transform in the output image.\n        :returns: An :py:class:`~PIL.Image.Image` object.\n        \"\"\"\n\n        if self.mode in (\"LA\", \"RGBA\") and resample != Resampling.NEAREST:\n            return (\n                self.convert({\"LA\": \"La\", \"RGBA\": \"RGBa\"}[self.mode])\n                .transform(size, method, data, resample, fill, fillcolor)\n                .convert(self.mode)\n            )\n\n        if isinstance(method, ImageTransformHandler):\n            return method.transform(size, self, resample=resample, fill=fill)\n\n        if hasattr(method, \"getdata\"):\n            # compatibility w. old-style transform objects\n            method, data = method.getdata()\n\n        if data is None:\n            msg = \"missing method data\"\n            raise ValueError(msg)\n\n        im = new(self.mode, size, fillcolor)\n        if self.mode == \"P\" and self.palette:\n            im.palette = self.palette.copy()\n        im.info = self.info.copy()\n        if method == Transform.MESH:\n            # list of quads\n            for box, quad in data:\n                im.__transformer(\n                    box, self, Transform.QUAD, quad, resample, fillcolor is None\n                )\n        else:\n            im.__transformer(\n                (0, 0) + size, self, method, data, resample, fillcolor is None\n            )\n\n        return im\n\n    def __transformer(\n        self, box, image, method, data, resample=Resampling.NEAREST, fill=1\n    ):\n        w = box[2] - box[0]\n        h = box[3] - box[1]\n\n        if method == Transform.AFFINE:\n            data = data[:6]\n\n        elif method == Transform.EXTENT:\n            # convert extent to an affine transform\n            x0, y0, x1, y1 = data\n            xs = (x1 - x0) / w\n            ys = (y1 - y0) / h\n            method = Transform.AFFINE\n            data = (xs, 0, x0, 0, ys, y0)\n\n        elif method == Transform.PERSPECTIVE:\n            data = data[:8]\n\n        elif method == Transform.QUAD:\n            # quadrilateral warp.  data specifies the four corners\n            # given as NW, SW, SE, and NE.\n            nw = data[:2]\n            sw = data[2:4]\n            se = data[4:6]\n            ne = data[6:8]\n            x0, y0 = nw\n            As = 1.0 / w\n            At = 1.0 / h\n            data = (\n                x0,\n                (ne[0] - x0) * As,\n                (sw[0] - x0) * At,\n                (se[0] - sw[0] - ne[0] + x0) * As * At,\n                y0,\n                (ne[1] - y0) * As,\n                (sw[1] - y0) * At,\n                (se[1] - sw[1] - ne[1] + y0) * As * At,\n            )\n\n        else:\n            msg = \"unknown transformation method\"\n            raise ValueError(msg)\n\n        if resample not in (\n            Resampling.NEAREST,\n            Resampling.BILINEAR,\n            Resampling.BICUBIC,\n        ):\n            if resample in (Resampling.BOX, Resampling.HAMMING, Resampling.LANCZOS):\n                msg = {\n                    Resampling.BOX: \"Image.Resampling.BOX\",\n                    Resampling.HAMMING: \"Image.Resampling.HAMMING\",\n                    Resampling.LANCZOS: \"Image.Resampling.LANCZOS\",\n                }[resample] + f\" ({resample}) cannot be used.\"\n            else:\n                msg = f\"Unknown resampling filter ({resample}).\"\n\n            filters = [\n                f\"{filter[1]} ({filter[0]})\"\n                for filter in (\n                    (Resampling.NEAREST, \"Image.Resampling.NEAREST\"),\n                    (Resampling.BILINEAR, \"Image.Resampling.BILINEAR\"),\n                    (Resampling.BICUBIC, \"Image.Resampling.BICUBIC\"),\n                )\n            ]\n            msg += f\" Use {', '.join(filters[:-1])} or {filters[-1]}\"\n            raise ValueError(msg)\n\n        image.load()\n\n        self.load()\n\n        if image.mode in (\"1\", \"P\"):\n            resample = Resampling.NEAREST\n\n        self.im.transform(box, image.im, method, data, resample, fill)\n\n    def transpose(self, method: Transpose) -> Image:\n        \"\"\"\n        Transpose image (flip or rotate in 90 degree steps)\n\n        :param method: One of :py:data:`Transpose.FLIP_LEFT_RIGHT`,\n          :py:data:`Transpose.FLIP_TOP_BOTTOM`, :py:data:`Transpose.ROTATE_90`,\n          :py:data:`Transpose.ROTATE_180`, :py:data:`Transpose.ROTATE_270`,\n          :py:data:`Transpose.TRANSPOSE` or :py:data:`Transpose.TRANSVERSE`.\n        :returns: Returns a flipped or rotated copy of this image.\n        \"\"\"\n\n        self.load()\n        return self._new(self.im.transpose(method))\n\n    def effect_spread(self, distance: int) -> Image:\n        \"\"\"\n        Randomly spread pixels in an image.\n\n        :param distance: Distance to spread pixels.\n        \"\"\"\n        self.load()\n        return self._new(self.im.effect_spread(distance))\n\n    def toqimage(self):\n        \"\"\"Returns a QImage copy of this image\"\"\"\n        from . import ImageQt\n\n        if not ImageQt.qt_is_installed:\n            msg = \"Qt bindings are not installed\"\n            raise ImportError(msg)\n        return ImageQt.toqimage(self)\n\n    def toqpixmap(self):\n        \"\"\"Returns a QPixmap copy of this image\"\"\"\n        from . import ImageQt\n\n        if not ImageQt.qt_is_installed:\n            msg = \"Qt bindings are not installed\"\n            raise ImportError(msg)\n        return ImageQt.toqpixmap(self)\n\n\n# --------------------------------------------------------------------\n# Abstract handlers.\n\n\nclass ImagePointHandler:\n    \"\"\"\n    Used as a mixin by point transforms\n    (for use with :py:meth:`~PIL.Image.Image.point`)\n    \"\"\"\n\n    @abc.abstractmethod\n    def point(self, im: Image) -> Image:\n        pass\n\n\nclass ImageTransformHandler:\n    \"\"\"\n    Used as a mixin by geometry transforms\n    (for use with :py:meth:`~PIL.Image.Image.transform`)\n    \"\"\"\n\n    @abc.abstractmethod\n    def transform(\n        self,\n        size: tuple[int, int],\n        image: Image,\n        **options: Any,\n    ) -> Image:\n        pass\n\n\n# --------------------------------------------------------------------\n# Factories\n\n#\n# Debugging\n\n\ndef _wedge() -> Image:\n    \"\"\"Create grayscale wedge (for debugging only)\"\"\"\n\n    return Image()._new(core.wedge(\"L\"))\n\n\ndef _check_size(size: Any) -> None:\n    \"\"\"\n    Common check to enforce type and sanity check on size tuples\n\n    :param size: Should be a 2 tuple of (width, height)\n    :returns: None, or raises a ValueError\n    \"\"\"\n\n    if not isinstance(size, (list, tuple)):\n        msg = \"Size must be a list or tuple\"\n        raise ValueError(msg)\n    if len(size) != 2:\n        msg = \"Size must be a sequence of length 2\"\n        raise ValueError(msg)\n    if size[0] < 0 or size[1] < 0:\n        msg = \"Width and height must be >= 0\"\n        raise ValueError(msg)\n\n\ndef new(\n    mode: str,\n    size: tuple[int, int] | list[int],\n    color: float | tuple[float, ...] | str | None = 0,\n) -> Image:\n    \"\"\"\n    Creates a new image with the given mode and size.\n\n    :param mode: The mode to use for the new image. See:\n       :ref:`concept-modes`.\n    :param size: A 2-tuple, containing (width, height) in pixels.\n    :param color: What color to use for the image.  Default is black.\n       If given, this should be a single integer or floating point value\n       for single-band modes, and a tuple for multi-band modes (one value\n       per band).  When creating RGB or HSV images, you can also use color\n       strings as supported by the ImageColor module.  If the color is\n       None, the image is not initialised.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    \"\"\"\n\n    if mode in (\"BGR;15\", \"BGR;16\", \"BGR;24\"):\n        deprecate(mode, 12)\n\n    _check_size(size)\n\n    if color is None:\n        # don't initialize\n        return Image()._new(core.new(mode, size))\n\n    if isinstance(color, str):\n        # css3-style specifier\n\n        from . import ImageColor\n\n        color = ImageColor.getcolor(color, mode)\n\n    im = Image()\n    if (\n        mode == \"P\"\n        and isinstance(color, (list, tuple))\n        and all(isinstance(i, int) for i in color)\n    ):\n        color_ints: tuple[int, ...] = cast(Tuple[int, ...], tuple(color))\n        if len(color_ints) == 3 or len(color_ints) == 4:\n            # RGB or RGBA value for a P image\n            from . import ImagePalette\n\n            im.palette = ImagePalette.ImagePalette()\n            color = im.palette.getcolor(color_ints)\n    return im._new(core.fill(mode, size, color))\n\n\ndef frombytes(\n    mode: str,\n    size: tuple[int, int],\n    data: bytes | bytearray,\n    decoder_name: str = \"raw\",\n    *args: Any,\n) -> Image:\n    \"\"\"\n    Creates a copy of an image memory from pixel data in a buffer.\n\n    In its simplest form, this function takes three arguments\n    (mode, size, and unpacked pixel data).\n\n    You can also use any pixel decoder supported by PIL. For more\n    information on available decoders, see the section\n    :ref:`Writing Your Own File Codec <file-codecs>`.\n\n    Note that this function decodes pixel data only, not entire images.\n    If you have an entire image in a string, wrap it in a\n    :py:class:`~io.BytesIO` object, and use :py:func:`~PIL.Image.open` to load\n    it.\n\n    :param mode: The image mode. See: :ref:`concept-modes`.\n    :param size: The image size.\n    :param data: A byte buffer containing raw data for the given mode.\n    :param decoder_name: What decoder to use.\n    :param args: Additional parameters for the given decoder.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    \"\"\"\n\n    _check_size(size)\n\n    im = new(mode, size)\n    if im.width != 0 and im.height != 0:\n        decoder_args: Any = args\n        if len(decoder_args) == 1 and isinstance(decoder_args[0], tuple):\n            # may pass tuple instead of argument list\n            decoder_args = decoder_args[0]\n\n        if decoder_name == \"raw\" and decoder_args == ():\n            decoder_args = mode\n\n        im.frombytes(data, decoder_name, decoder_args)\n    return im\n\n\ndef frombuffer(\n    mode: str, size: tuple[int, int], data, decoder_name: str = \"raw\", *args: Any\n) -> Image:\n    \"\"\"\n    Creates an image memory referencing pixel data in a byte buffer.\n\n    This function is similar to :py:func:`~PIL.Image.frombytes`, but uses data\n    in the byte buffer, where possible.  This means that changes to the\n    original buffer object are reflected in this image).  Not all modes can\n    share memory; supported modes include \"L\", \"RGBX\", \"RGBA\", and \"CMYK\".\n\n    Note that this function decodes pixel data only, not entire images.\n    If you have an entire image file in a string, wrap it in a\n    :py:class:`~io.BytesIO` object, and use :py:func:`~PIL.Image.open` to load it.\n\n    The default parameters used for the \"raw\" decoder differs from that used for\n    :py:func:`~PIL.Image.frombytes`. This is a bug, and will probably be fixed in a\n    future release. The current release issues a warning if you do this; to disable\n    the warning, you should provide the full set of parameters. See below for details.\n\n    :param mode: The image mode. See: :ref:`concept-modes`.\n    :param size: The image size.\n    :param data: A bytes or other buffer object containing raw\n        data for the given mode.\n    :param decoder_name: What decoder to use.\n    :param args: Additional parameters for the given decoder.  For the\n        default encoder (\"raw\"), it's recommended that you provide the\n        full set of parameters::\n\n            frombuffer(mode, size, data, \"raw\", mode, 0, 1)\n\n    :returns: An :py:class:`~PIL.Image.Image` object.\n\n    .. versionadded:: 1.1.4\n    \"\"\"\n\n    _check_size(size)\n\n    # may pass tuple instead of argument list\n    if len(args) == 1 and isinstance(args[0], tuple):\n        args = args[0]\n\n    if decoder_name == \"raw\":\n        if args == ():\n            args = mode, 0, 1\n        if args[0] in _MAPMODES:\n            im = new(mode, (0, 0))\n            im = im._new(core.map_buffer(data, size, decoder_name, 0, args))\n            if mode == \"P\":\n                from . import ImagePalette\n\n                im.palette = ImagePalette.ImagePalette(\"RGB\", im.im.getpalette(\"RGB\"))\n            im.readonly = 1\n            return im\n\n    return frombytes(mode, size, data, decoder_name, args)\n\n\nclass SupportsArrayInterface(Protocol):\n    \"\"\"\n    An object that has an ``__array_interface__`` dictionary.\n    \"\"\"\n\n    @property\n    def __array_interface__(self) -> dict[str, Any]:\n        raise NotImplementedError()\n\n\ndef fromarray(obj: SupportsArrayInterface, mode: str | None = None) -> Image:\n    \"\"\"\n    Creates an image memory from an object exporting the array interface\n    (using the buffer protocol)::\n\n      from PIL import Image\n      import numpy as np\n      a = np.zeros((5, 5))\n      im = Image.fromarray(a)\n\n    If ``obj`` is not contiguous, then the ``tobytes`` method is called\n    and :py:func:`~PIL.Image.frombuffer` is used.\n\n    In the case of NumPy, be aware that Pillow modes do not always correspond\n    to NumPy dtypes. Pillow modes only offer 1-bit pixels, 8-bit pixels,\n    32-bit signed integer pixels, and 32-bit floating point pixels.\n\n    Pillow images can also be converted to arrays::\n\n      from PIL import Image\n      import numpy as np\n      im = Image.open(\"hopper.jpg\")\n      a = np.asarray(im)\n\n    When converting Pillow images to arrays however, only pixel values are\n    transferred. This means that P and PA mode images will lose their palette.\n\n    :param obj: Object with array interface\n    :param mode: Optional mode to use when reading ``obj``. Will be determined from\n      type if ``None``.\n\n      This will not be used to convert the data after reading, but will be used to\n      change how the data is read::\n\n        from PIL import Image\n        import numpy as np\n        a = np.full((1, 1), 300)\n        im = Image.fromarray(a, mode=\"L\")\n        im.getpixel((0, 0))  # 44\n        im = Image.fromarray(a, mode=\"RGB\")\n        im.getpixel((0, 0))  # (44, 1, 0)\n\n      See: :ref:`concept-modes` for general information about modes.\n    :returns: An image object.\n\n    .. versionadded:: 1.1.6\n    \"\"\"\n    arr = obj.__array_interface__\n    shape = arr[\"shape\"]\n    ndim = len(shape)\n    strides = arr.get(\"strides\", None)\n    if mode is None:\n        try:\n            typekey = (1, 1) + shape[2:], arr[\"typestr\"]\n        except KeyError as e:\n            msg = \"Cannot handle this data type\"\n            raise TypeError(msg) from e\n        try:\n            mode, rawmode = _fromarray_typemap[typekey]\n        except KeyError as e:\n            typekey_shape, typestr = typekey\n            msg = f\"Cannot handle this data type: {typekey_shape}, {typestr}\"\n            raise TypeError(msg) from e\n    else:\n        rawmode = mode\n    if mode in [\"1\", \"L\", \"I\", \"P\", \"F\"]:\n        ndmax = 2\n    elif mode == \"RGB\":\n        ndmax = 3\n    else:\n        ndmax = 4\n    if ndim > ndmax:\n        msg = f\"Too many dimensions: {ndim} > {ndmax}.\"\n        raise ValueError(msg)\n\n    size = 1 if ndim == 1 else shape[1], shape[0]\n    if strides is not None:\n        if hasattr(obj, \"tobytes\"):\n            obj = obj.tobytes()\n        elif hasattr(obj, \"tostring\"):\n            obj = obj.tostring()\n        else:\n            msg = \"'strides' requires either tobytes() or tostring()\"\n            raise ValueError(msg)\n\n    return frombuffer(mode, size, obj, \"raw\", rawmode, 0, 1)\n\n\ndef fromqimage(im):\n    \"\"\"Creates an image instance from a QImage image\"\"\"\n    from . import ImageQt\n\n    if not ImageQt.qt_is_installed:\n        msg = \"Qt bindings are not installed\"\n        raise ImportError(msg)\n    return ImageQt.fromqimage(im)\n\n\ndef fromqpixmap(im):\n    \"\"\"Creates an image instance from a QPixmap image\"\"\"\n    from . import ImageQt\n\n    if not ImageQt.qt_is_installed:\n        msg = \"Qt bindings are not installed\"\n        raise ImportError(msg)\n    return ImageQt.fromqpixmap(im)\n\n\n_fromarray_typemap = {\n    # (shape, typestr) => mode, rawmode\n    # first two members of shape are set to one\n    ((1, 1), \"|b1\"): (\"1\", \"1;8\"),\n    ((1, 1), \"|u1\"): (\"L\", \"L\"),\n    ((1, 1), \"|i1\"): (\"I\", \"I;8\"),\n    ((1, 1), \"<u2\"): (\"I\", \"I;16\"),\n    ((1, 1), \">u2\"): (\"I\", \"I;16B\"),\n    ((1, 1), \"<i2\"): (\"I\", \"I;16S\"),\n    ((1, 1), \">i2\"): (\"I\", \"I;16BS\"),\n    ((1, 1), \"<u4\"): (\"I\", \"I;32\"),\n    ((1, 1), \">u4\"): (\"I\", \"I;32B\"),\n    ((1, 1), \"<i4\"): (\"I\", \"I;32S\"),\n    ((1, 1), \">i4\"): (\"I\", \"I;32BS\"),\n    ((1, 1), \"<f4\"): (\"F\", \"F;32F\"),\n    ((1, 1), \">f4\"): (\"F\", \"F;32BF\"),\n    ((1, 1), \"<f8\"): (\"F\", \"F;64F\"),\n    ((1, 1), \">f8\"): (\"F\", \"F;64BF\"),\n    ((1, 1, 2), \"|u1\"): (\"LA\", \"LA\"),\n    ((1, 1, 3), \"|u1\"): (\"RGB\", \"RGB\"),\n    ((1, 1, 4), \"|u1\"): (\"RGBA\", \"RGBA\"),\n    # shortcuts:\n    ((1, 1), f\"{_ENDIAN}i4\"): (\"I\", \"I\"),\n    ((1, 1), f\"{_ENDIAN}f4\"): (\"F\", \"F\"),\n}\n\n\ndef _decompression_bomb_check(size: tuple[int, int]) -> None:\n    if MAX_IMAGE_PIXELS is None:\n        return\n\n    pixels = max(1, size[0]) * max(1, size[1])\n\n    if pixels > 2 * MAX_IMAGE_PIXELS:\n        msg = (\n            f\"Image size ({pixels} pixels) exceeds limit of {2 * MAX_IMAGE_PIXELS} \"\n            \"pixels, could be decompression bomb DOS attack.\"\n        )\n        raise DecompressionBombError(msg)\n\n    if pixels > MAX_IMAGE_PIXELS:\n        warnings.warn(\n            f\"Image size ({pixels} pixels) exceeds limit of {MAX_IMAGE_PIXELS} pixels, \"\n            \"could be decompression bomb DOS attack.\",\n            DecompressionBombWarning,\n        )\n\n\ndef open(\n    fp: StrOrBytesPath | IO[bytes],\n    mode: Literal[\"r\"] = \"r\",\n    formats: list[str] | tuple[str, ...] | None = None,\n) -> ImageFile.ImageFile:\n    \"\"\"\n    Opens and identifies the given image file.\n\n    This is a lazy operation; this function identifies the file, but\n    the file remains open and the actual image data is not read from\n    the file until you try to process the data (or call the\n    :py:meth:`~PIL.Image.Image.load` method).  See\n    :py:func:`~PIL.Image.new`. See :ref:`file-handling`.\n\n    :param fp: A filename (string), os.PathLike object or a file object.\n       The file object must implement ``file.read``,\n       ``file.seek``, and ``file.tell`` methods,\n       and be opened in binary mode. The file object will also seek to zero\n       before reading.\n    :param mode: The mode.  If given, this argument must be \"r\".\n    :param formats: A list or tuple of formats to attempt to load the file in.\n       This can be used to restrict the set of formats checked.\n       Pass ``None`` to try all supported formats. You can print the set of\n       available formats by running ``python3 -m PIL`` or using\n       the :py:func:`PIL.features.pilinfo` function.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    :exception FileNotFoundError: If the file cannot be found.\n    :exception PIL.UnidentifiedImageError: If the image cannot be opened and\n       identified.\n    :exception ValueError: If the ``mode`` is not \"r\", or if a ``StringIO``\n       instance is used for ``fp``.\n    :exception TypeError: If ``formats`` is not ``None``, a list or a tuple.\n    \"\"\"\n\n    if mode != \"r\":\n        msg = f\"bad mode {repr(mode)}\"  # type: ignore[unreachable]\n        raise ValueError(msg)\n    elif isinstance(fp, io.StringIO):\n        msg = (  # type: ignore[unreachable]\n            \"StringIO cannot be used to open an image. \"\n            \"Binary data must be used instead.\"\n        )\n        raise ValueError(msg)\n\n    if formats is None:\n        formats = ID\n    elif not isinstance(formats, (list, tuple)):\n        msg = \"formats must be a list or tuple\"  # type: ignore[unreachable]\n        raise TypeError(msg)\n\n    exclusive_fp = False\n    filename: str | bytes = \"\"\n    if is_path(fp):\n        filename = os.path.realpath(os.fspath(fp))\n\n    if filename:\n        fp = builtins.open(filename, \"rb\")\n        exclusive_fp = True\n    else:\n        fp = cast(IO[bytes], fp)\n\n    try:\n        fp.seek(0)\n    except (AttributeError, io.UnsupportedOperation):\n        fp = io.BytesIO(fp.read())\n        exclusive_fp = True\n\n    prefix = fp.read(16)\n\n    preinit()\n\n    accept_warnings: list[str] = []\n\n    def _open_core(\n        fp: IO[bytes],\n        filename: str | bytes,\n        prefix: bytes,\n        formats: list[str] | tuple[str, ...],\n    ) -> ImageFile.ImageFile | None:\n        for i in formats:\n            i = i.upper()\n            if i not in OPEN:\n                init()\n            try:\n                factory, accept = OPEN[i]\n                result = not accept or accept(prefix)\n                if isinstance(result, str):\n                    accept_warnings.append(result)\n                elif result:\n                    fp.seek(0)\n                    im = factory(fp, filename)\n                    _decompression_bomb_check(im.size)\n                    return im\n            except (SyntaxError, IndexError, TypeError, struct.error):\n                # Leave disabled by default, spams the logs with image\n                # opening failures that are entirely expected.\n                # logger.debug(\"\", exc_info=True)\n                continue\n            except BaseException:\n                if exclusive_fp:\n                    fp.close()\n                raise\n        return None\n\n    im = _open_core(fp, filename, prefix, formats)\n\n    if im is None and formats is ID:\n        checked_formats = ID.copy()\n        if init():\n            im = _open_core(\n                fp,\n                filename,\n                prefix,\n                tuple(format for format in formats if format not in checked_formats),\n            )\n\n    if im:\n        im._exclusive_fp = exclusive_fp\n        return im\n\n    if exclusive_fp:\n        fp.close()\n    for message in accept_warnings:\n        warnings.warn(message)\n    msg = \"cannot identify image file %r\" % (filename if filename else fp)\n    raise UnidentifiedImageError(msg)\n\n\n#\n# Image processing.\n\n\ndef alpha_composite(im1: Image, im2: Image) -> Image:\n    \"\"\"\n    Alpha composite im2 over im1.\n\n    :param im1: The first image. Must have mode RGBA.\n    :param im2: The second image.  Must have mode RGBA, and the same size as\n       the first image.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    \"\"\"\n\n    im1.load()\n    im2.load()\n    return im1._new(core.alpha_composite(im1.im, im2.im))\n\n\ndef blend(im1: Image, im2: Image, alpha: float) -> Image:\n    \"\"\"\n    Creates a new image by interpolating between two input images, using\n    a constant alpha::\n\n        out = image1 * (1.0 - alpha) + image2 * alpha\n\n    :param im1: The first image.\n    :param im2: The second image.  Must have the same mode and size as\n       the first image.\n    :param alpha: The interpolation alpha factor.  If alpha is 0.0, a\n       copy of the first image is returned. If alpha is 1.0, a copy of\n       the second image is returned. There are no restrictions on the\n       alpha value. If necessary, the result is clipped to fit into\n       the allowed output range.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    \"\"\"\n\n    im1.load()\n    im2.load()\n    return im1._new(core.blend(im1.im, im2.im, alpha))\n\n\ndef composite(image1: Image, image2: Image, mask: Image) -> Image:\n    \"\"\"\n    Create composite image by blending images using a transparency mask.\n\n    :param image1: The first image.\n    :param image2: The second image.  Must have the same mode and\n       size as the first image.\n    :param mask: A mask image.  This image can have mode\n       \"1\", \"L\", or \"RGBA\", and must have the same size as the\n       other two images.\n    \"\"\"\n\n    image = image2.copy()\n    image.paste(image1, None, mask)\n    return image\n\n\ndef eval(image, *args):\n    \"\"\"\n    Applies the function (which should take one argument) to each pixel\n    in the given image. If the image has more than one band, the same\n    function is applied to each band. Note that the function is\n    evaluated once for each possible pixel value, so you cannot use\n    random components or other generators.\n\n    :param image: The input image.\n    :param function: A function object, taking one integer argument.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    \"\"\"\n\n    return image.point(args[0])\n\n\ndef merge(mode: str, bands: Sequence[Image]) -> Image:\n    \"\"\"\n    Merge a set of single band images into a new multiband image.\n\n    :param mode: The mode to use for the output image. See:\n        :ref:`concept-modes`.\n    :param bands: A sequence containing one single-band image for\n        each band in the output image.  All bands must have the\n        same size.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    \"\"\"\n\n    if getmodebands(mode) != len(bands) or \"*\" in mode:\n        msg = \"wrong number of bands\"\n        raise ValueError(msg)\n    for band in bands[1:]:\n        if band.mode != getmodetype(mode):\n            msg = \"mode mismatch\"\n            raise ValueError(msg)\n        if band.size != bands[0].size:\n            msg = \"size mismatch\"\n            raise ValueError(msg)\n    for band in bands:\n        band.load()\n    return bands[0]._new(core.merge(mode, *[b.im for b in bands]))\n\n\n# --------------------------------------------------------------------\n# Plugin registry\n\n\ndef register_open(\n    id: str,\n    factory: Callable[[IO[bytes], str | bytes], ImageFile.ImageFile],\n    accept: Callable[[bytes], bool | str] | None = None,\n) -> None:\n    \"\"\"\n    Register an image file plugin.  This function should not be used\n    in application code.\n\n    :param id: An image format identifier.\n    :param factory: An image file factory method.\n    :param accept: An optional function that can be used to quickly\n       reject images having another format.\n    \"\"\"\n    id = id.upper()\n    if id not in ID:\n        ID.append(id)\n    OPEN[id] = factory, accept\n\n\ndef register_mime(id: str, mimetype: str) -> None:\n    \"\"\"\n    Registers an image MIME type by populating ``Image.MIME``. This function\n    should not be used in application code.\n\n    ``Image.MIME`` provides a mapping from image format identifiers to mime\n    formats, but :py:meth:`~PIL.ImageFile.ImageFile.get_format_mimetype` can\n    provide a different result for specific images.\n\n    :param id: An image format identifier.\n    :param mimetype: The image MIME type for this format.\n    \"\"\"\n    MIME[id.upper()] = mimetype\n\n\ndef register_save(\n    id: str, driver: Callable[[Image, IO[bytes], str | bytes], None]\n) -> None:\n    \"\"\"\n    Registers an image save function.  This function should not be\n    used in application code.\n\n    :param id: An image format identifier.\n    :param driver: A function to save images in this format.\n    \"\"\"\n    SAVE[id.upper()] = driver\n\n\ndef register_save_all(\n    id: str, driver: Callable[[Image, IO[bytes], str | bytes], None]\n) -> None:\n    \"\"\"\n    Registers an image function to save all the frames\n    of a multiframe format.  This function should not be\n    used in application code.\n\n    :param id: An image format identifier.\n    :param driver: A function to save images in this format.\n    \"\"\"\n    SAVE_ALL[id.upper()] = driver\n\n\ndef register_extension(id: str, extension: str) -> None:\n    \"\"\"\n    Registers an image extension.  This function should not be\n    used in application code.\n\n    :param id: An image format identifier.\n    :param extension: An extension used for this format.\n    \"\"\"\n    EXTENSION[extension.lower()] = id.upper()\n\n\ndef register_extensions(id: str, extensions: list[str]) -> None:\n    \"\"\"\n    Registers image extensions.  This function should not be\n    used in application code.\n\n    :param id: An image format identifier.\n    :param extensions: A list of extensions used for this format.\n    \"\"\"\n    for extension in extensions:\n        register_extension(id, extension)\n\n\ndef registered_extensions() -> dict[str, str]:\n    \"\"\"\n    Returns a dictionary containing all file extensions belonging\n    to registered plugins\n    \"\"\"\n    init()\n    return EXTENSION\n\n\ndef register_decoder(name: str, decoder: type[ImageFile.PyDecoder]) -> None:\n    \"\"\"\n    Registers an image decoder.  This function should not be\n    used in application code.\n\n    :param name: The name of the decoder\n    :param decoder: An ImageFile.PyDecoder object\n\n    .. versionadded:: 4.1.0\n    \"\"\"\n    DECODERS[name] = decoder\n\n\ndef register_encoder(name: str, encoder: type[ImageFile.PyEncoder]) -> None:\n    \"\"\"\n    Registers an image encoder.  This function should not be\n    used in application code.\n\n    :param name: The name of the encoder\n    :param encoder: An ImageFile.PyEncoder object\n\n    .. versionadded:: 4.1.0\n    \"\"\"\n    ENCODERS[name] = encoder\n\n\n# --------------------------------------------------------------------\n# Simple display support.\n\n\ndef _show(image: Image, **options: Any) -> None:\n    from . import ImageShow\n\n    ImageShow.show(image, **options)\n\n\n# --------------------------------------------------------------------\n# Effects\n\n\ndef effect_mandelbrot(\n    size: tuple[int, int], extent: tuple[float, float, float, float], quality: int\n) -> Image:\n    \"\"\"\n    Generate a Mandelbrot set covering the given extent.\n\n    :param size: The requested size in pixels, as a 2-tuple:\n       (width, height).\n    :param extent: The extent to cover, as a 4-tuple:\n       (x0, y0, x1, y1).\n    :param quality: Quality.\n    \"\"\"\n    return Image()._new(core.effect_mandelbrot(size, extent, quality))\n\n\ndef effect_noise(size: tuple[int, int], sigma: float) -> Image:\n    \"\"\"\n    Generate Gaussian noise centered around 128.\n\n    :param size: The requested size in pixels, as a 2-tuple:\n       (width, height).\n    :param sigma: Standard deviation of noise.\n    \"\"\"\n    return Image()._new(core.effect_noise(size, sigma))\n\n\ndef linear_gradient(mode: str) -> Image:\n    \"\"\"\n    Generate 256x256 linear gradient from black to white, top to bottom.\n\n    :param mode: Input mode.\n    \"\"\"\n    return Image()._new(core.linear_gradient(mode))\n\n\ndef radial_gradient(mode: str) -> Image:\n    \"\"\"\n    Generate 256x256 radial gradient from black to white, centre to edge.\n\n    :param mode: Input mode.\n    \"\"\"\n    return Image()._new(core.radial_gradient(mode))\n\n\n# --------------------------------------------------------------------\n# Resources\n\n\ndef _apply_env_variables(env: dict[str, str] | None = None) -> None:\n    env_dict = env if env is not None else os.environ\n\n    for var_name, setter in [\n        (\"PILLOW_ALIGNMENT\", core.set_alignment),\n        (\"PILLOW_BLOCK_SIZE\", core.set_block_size),\n        (\"PILLOW_BLOCKS_MAX\", core.set_blocks_max),\n    ]:\n        if var_name not in env_dict:\n            continue\n\n        var = env_dict[var_name].lower()\n\n        units = 1\n        for postfix, mul in [(\"k\", 1024), (\"m\", 1024 * 1024)]:\n            if var.endswith(postfix):\n                units = mul\n                var = var[: -len(postfix)]\n\n        try:\n            var_int = int(var) * units\n        except ValueError:\n            warnings.warn(f\"{var_name} is not int\")\n            continue\n\n        try:\n            setter(var_int)\n        except ValueError as e:\n            warnings.warn(f\"{var_name}: {e}\")\n\n\n_apply_env_variables()\natexit.register(core.clear_cache)\n\n\nif TYPE_CHECKING:\n    _ExifBase = MutableMapping[int, Any]\nelse:\n    _ExifBase = MutableMapping\n\n\nclass Exif(_ExifBase):\n    \"\"\"\n    This class provides read and write access to EXIF image data::\n\n      from PIL import Image\n      im = Image.open(\"exif.png\")\n      exif = im.getexif()  # Returns an instance of this class\n\n    Information can be read and written, iterated over or deleted::\n\n      print(exif[274])  # 1\n      exif[274] = 2\n      for k, v in exif.items():\n        print(\"Tag\", k, \"Value\", v)  # Tag 274 Value 2\n      del exif[274]\n\n    To access information beyond IFD0, :py:meth:`~PIL.Image.Exif.get_ifd`\n    returns a dictionary::\n\n      from PIL import ExifTags\n      im = Image.open(\"exif_gps.jpg\")\n      exif = im.getexif()\n      gps_ifd = exif.get_ifd(ExifTags.IFD.GPSInfo)\n      print(gps_ifd)\n\n    Other IFDs include ``ExifTags.IFD.Exif``, ``ExifTags.IFD.Makernote``,\n    ``ExifTags.IFD.Interop`` and ``ExifTags.IFD.IFD1``.\n\n    :py:mod:`~PIL.ExifTags` also has enum classes to provide names for data::\n\n      print(exif[ExifTags.Base.Software])  # PIL\n      print(gps_ifd[ExifTags.GPS.GPSDateStamp])  # 1999:99:99 99:99:99\n    \"\"\"\n\n    endian = None\n    bigtiff = False\n    _loaded = False\n\n    def __init__(self):\n        self._data = {}\n        self._hidden_data = {}\n        self._ifds = {}\n        self._info = None\n        self._loaded_exif = None\n\n    def _fixup(self, value):\n        try:\n            if len(value) == 1 and isinstance(value, tuple):\n                return value[0]\n        except Exception:\n            pass\n        return value\n\n    def _fixup_dict(self, src_dict):\n        # Helper function\n        # returns a dict with any single item tuples/lists as individual values\n        return {k: self._fixup(v) for k, v in src_dict.items()}\n\n    def _get_ifd_dict(self, offset, group=None):\n        try:\n            # an offset pointer to the location of the nested embedded IFD.\n            # It should be a long, but may be corrupted.\n            self.fp.seek(offset)\n        except (KeyError, TypeError):\n            pass\n        else:\n            from . import TiffImagePlugin\n\n            info = TiffImagePlugin.ImageFileDirectory_v2(self.head, group=group)\n            info.load(self.fp)\n            return self._fixup_dict(info)\n\n    def _get_head(self):\n        version = b\"\\x2B\" if self.bigtiff else b\"\\x2A\"\n        if self.endian == \"<\":\n            head = b\"II\" + version + b\"\\x00\" + o32le(8)\n        else:\n            head = b\"MM\\x00\" + version + o32be(8)\n        if self.bigtiff:\n            head += o32le(8) if self.endian == \"<\" else o32be(8)\n            head += b\"\\x00\\x00\\x00\\x00\"\n        return head\n\n    def load(self, data):\n        # Extract EXIF information.  This is highly experimental,\n        # and is likely to be replaced with something better in a future\n        # version.\n\n        # The EXIF record consists of a TIFF file embedded in a JPEG\n        # application marker (!).\n        if data == self._loaded_exif:\n            return\n        self._loaded_exif = data\n        self._data.clear()\n        self._hidden_data.clear()\n        self._ifds.clear()\n        if data and data.startswith(b\"Exif\\x00\\x00\"):\n            data = data[6:]\n        if not data:\n            self._info = None\n            return\n\n        self.fp = io.BytesIO(data)\n        self.head = self.fp.read(8)\n        # process dictionary\n        from . import TiffImagePlugin\n\n        self._info = TiffImagePlugin.ImageFileDirectory_v2(self.head)\n        self.endian = self._info._endian\n        self.fp.seek(self._info.next)\n        self._info.load(self.fp)\n\n    def load_from_fp(self, fp, offset=None):\n        self._loaded_exif = None\n        self._data.clear()\n        self._hidden_data.clear()\n        self._ifds.clear()\n\n        # process dictionary\n        from . import TiffImagePlugin\n\n        self.fp = fp\n        if offset is not None:\n            self.head = self._get_head()\n        else:\n            self.head = self.fp.read(8)\n        self._info = TiffImagePlugin.ImageFileDirectory_v2(self.head)\n        if self.endian is None:\n            self.endian = self._info._endian\n        if offset is None:\n            offset = self._info.next\n        self.fp.tell()\n        self.fp.seek(offset)\n        self._info.load(self.fp)\n\n    def _get_merged_dict(self):\n        merged_dict = dict(self)\n\n        # get EXIF extension\n        if ExifTags.IFD.Exif in self:\n            ifd = self._get_ifd_dict(self[ExifTags.IFD.Exif], ExifTags.IFD.Exif)\n            if ifd:\n                merged_dict.update(ifd)\n\n        # GPS\n        if ExifTags.IFD.GPSInfo in self:\n            merged_dict[ExifTags.IFD.GPSInfo] = self._get_ifd_dict(\n                self[ExifTags.IFD.GPSInfo], ExifTags.IFD.GPSInfo\n            )\n\n        return merged_dict\n\n    def tobytes(self, offset: int = 8) -> bytes:\n        from . import TiffImagePlugin\n\n        head = self._get_head()\n        ifd = TiffImagePlugin.ImageFileDirectory_v2(ifh=head)\n        for tag, value in self.items():\n            if tag in [\n                ExifTags.IFD.Exif,\n                ExifTags.IFD.GPSInfo,\n            ] and not isinstance(value, dict):\n                value = self.get_ifd(tag)\n                if (\n                    tag == ExifTags.IFD.Exif\n                    and ExifTags.IFD.Interop in value\n                    and not isinstance(value[ExifTags.IFD.Interop], dict)\n                ):\n                    value = value.copy()\n                    value[ExifTags.IFD.Interop] = self.get_ifd(ExifTags.IFD.Interop)\n            ifd[tag] = value\n        return b\"Exif\\x00\\x00\" + head + ifd.tobytes(offset)\n\n    def get_ifd(self, tag):\n        if tag not in self._ifds:\n            if tag == ExifTags.IFD.IFD1:\n                if self._info is not None and self._info.next != 0:\n                    self._ifds[tag] = self._get_ifd_dict(self._info.next)\n            elif tag in [ExifTags.IFD.Exif, ExifTags.IFD.GPSInfo]:\n                offset = self._hidden_data.get(tag, self.get(tag))\n                if offset is not None:\n                    self._ifds[tag] = self._get_ifd_dict(offset, tag)\n            elif tag in [ExifTags.IFD.Interop, ExifTags.IFD.Makernote]:\n                if ExifTags.IFD.Exif not in self._ifds:\n                    self.get_ifd(ExifTags.IFD.Exif)\n                tag_data = self._ifds[ExifTags.IFD.Exif][tag]\n                if tag == ExifTags.IFD.Makernote:\n                    from .TiffImagePlugin import ImageFileDirectory_v2\n\n                    if tag_data[:8] == b\"FUJIFILM\":\n                        ifd_offset = i32le(tag_data, 8)\n                        ifd_data = tag_data[ifd_offset:]\n\n                        makernote = {}\n                        for i in range(0, struct.unpack(\"<H\", ifd_data[:2])[0]):\n                            ifd_tag, typ, count, data = struct.unpack(\n                                \"<HHL4s\", ifd_data[i * 12 + 2 : (i + 1) * 12 + 2]\n                            )\n                            try:\n                                (\n                                    unit_size,\n                                    handler,\n                                ) = ImageFileDirectory_v2._load_dispatch[typ]\n                            except KeyError:\n                                continue\n                            size = count * unit_size\n                            if size > 4:\n                                (offset,) = struct.unpack(\"<L\", data)\n                                data = ifd_data[offset - 12 : offset + size - 12]\n                            else:\n                                data = data[:size]\n\n                            if len(data) != size:\n                                warnings.warn(\n                                    \"Possibly corrupt EXIF MakerNote data.  \"\n                                    f\"Expecting to read {size} bytes but only got \"\n                                    f\"{len(data)}. Skipping tag {ifd_tag}\"\n                                )\n                                continue\n\n                            if not data:\n                                continue\n\n                            makernote[ifd_tag] = handler(\n                                ImageFileDirectory_v2(), data, False\n                            )\n                        self._ifds[tag] = dict(self._fixup_dict(makernote))\n                    elif self.get(0x010F) == \"Nintendo\":\n                        makernote = {}\n                        for i in range(0, struct.unpack(\">H\", tag_data[:2])[0]):\n                            ifd_tag, typ, count, data = struct.unpack(\n                                \">HHL4s\", tag_data[i * 12 + 2 : (i + 1) * 12 + 2]\n                            )\n                            if ifd_tag == 0x1101:\n                                # CameraInfo\n                                (offset,) = struct.unpack(\">L\", data)\n                                self.fp.seek(offset)\n\n                                camerainfo = {\"ModelID\": self.fp.read(4)}\n\n                                self.fp.read(4)\n                                # Seconds since 2000\n                                camerainfo[\"TimeStamp\"] = i32le(self.fp.read(12))\n\n                                self.fp.read(4)\n                                camerainfo[\"InternalSerialNumber\"] = self.fp.read(4)\n\n                                self.fp.read(12)\n                                parallax = self.fp.read(4)\n                                handler = ImageFileDirectory_v2._load_dispatch[\n                                    TiffTags.FLOAT\n                                ][1]\n                                camerainfo[\"Parallax\"] = handler(\n                                    ImageFileDirectory_v2(), parallax, False\n                                )\n\n                                self.fp.read(4)\n                                camerainfo[\"Category\"] = self.fp.read(2)\n\n                                makernote = {0x1101: dict(self._fixup_dict(camerainfo))}\n                        self._ifds[tag] = makernote\n                else:\n                    # Interop\n                    self._ifds[tag] = self._get_ifd_dict(tag_data, tag)\n        ifd = self._ifds.get(tag, {})\n        if tag == ExifTags.IFD.Exif and self._hidden_data:\n            ifd = {\n                k: v\n                for (k, v) in ifd.items()\n                if k not in (ExifTags.IFD.Interop, ExifTags.IFD.Makernote)\n            }\n        return ifd\n\n    def hide_offsets(self) -> None:\n        for tag in (ExifTags.IFD.Exif, ExifTags.IFD.GPSInfo):\n            if tag in self:\n                self._hidden_data[tag] = self[tag]\n                del self[tag]\n\n    def __str__(self) -> str:\n        if self._info is not None:\n            # Load all keys into self._data\n            for tag in self._info:\n                self[tag]\n\n        return str(self._data)\n\n    def __len__(self) -> int:\n        keys = set(self._data)\n        if self._info is not None:\n            keys.update(self._info)\n        return len(keys)\n\n    def __getitem__(self, tag):\n        if self._info is not None and tag not in self._data and tag in self._info:\n            self._data[tag] = self._fixup(self._info[tag])\n            del self._info[tag]\n        return self._data[tag]\n\n    def __contains__(self, tag) -> bool:\n        return tag in self._data or (self._info is not None and tag in self._info)\n\n    def __setitem__(self, tag, value) -> None:\n        if self._info is not None and tag in self._info:\n            del self._info[tag]\n        self._data[tag] = value\n\n    def __delitem__(self, tag: int) -> None:\n        if self._info is not None and tag in self._info:\n            del self._info[tag]\n        else:\n            del self._data[tag]\n\n    def __iter__(self):\n        keys = set(self._data)\n        if self._info is not None:\n            keys.update(self._info)\n        return iter(keys)\n",
            "new_file_content": "#\n# The Python Imaging Library.\n# $Id$\n#\n# the Image class wrapper\n#\n# partial release history:\n# 1995-09-09 fl   Created\n# 1996-03-11 fl   PIL release 0.0 (proof of concept)\n# 1996-04-30 fl   PIL release 0.1b1\n# 1999-07-28 fl   PIL release 1.0 final\n# 2000-06-07 fl   PIL release 1.1\n# 2000-10-20 fl   PIL release 1.1.1\n# 2001-05-07 fl   PIL release 1.1.2\n# 2002-03-15 fl   PIL release 1.1.3\n# 2003-05-10 fl   PIL release 1.1.4\n# 2005-03-28 fl   PIL release 1.1.5\n# 2006-12-02 fl   PIL release 1.1.6\n# 2009-11-15 fl   PIL release 1.1.7\n#\n# Copyright (c) 1997-2009 by Secret Labs AB.  All rights reserved.\n# Copyright (c) 1995-2009 by Fredrik Lundh.\n#\n# See the README file for information on usage and redistribution.\n#\n\nfrom __future__ import annotations\n\nimport abc\nimport atexit\nimport builtins\nimport io\nimport logging\nimport math\nimport os\nimport re\nimport struct\nimport sys\nimport tempfile\nimport warnings\nfrom collections.abc import Callable, MutableMapping\nfrom enum import IntEnum\nfrom types import ModuleType\nfrom typing import (\n    IO,\n    TYPE_CHECKING,\n    Any,\n    Literal,\n    Protocol,\n    Sequence,\n    Tuple,\n    cast,\n)\n\n# VERSION was removed in Pillow 6.0.0.\n# PILLOW_VERSION was removed in Pillow 9.0.0.\n# Use __version__ instead.\nfrom . import (\n    ExifTags,\n    ImageMode,\n    TiffTags,\n    UnidentifiedImageError,\n    __version__,\n    _plugins,\n)\nfrom ._binary import i32le, o32be, o32le\nfrom ._deprecate import deprecate\nfrom ._typing import StrOrBytesPath, TypeGuard\nfrom ._util import DeferredError, is_path\n\nElementTree: ModuleType | None\ntry:\n    from defusedxml import ElementTree\nexcept ImportError:\n    ElementTree = None\n\nlogger = logging.getLogger(__name__)\n\n\nclass DecompressionBombWarning(RuntimeWarning):\n    pass\n\n\nclass DecompressionBombError(Exception):\n    pass\n\n\nWARN_POSSIBLE_FORMATS: bool = False\n\n# Limit to around a quarter gigabyte for a 24-bit (3 bpp) image\nMAX_IMAGE_PIXELS: int | None = int(1024 * 1024 * 1024 // 4 // 3)\n\n\ntry:\n    # If the _imaging C module is not present, Pillow will not load.\n    # Note that other modules should not refer to _imaging directly;\n    # import Image and use the Image.core variable instead.\n    # Also note that Image.core is not a publicly documented interface,\n    # and should be considered private and subject to change.\n    from . import _imaging as core\n\n    if __version__ != getattr(core, \"PILLOW_VERSION\", None):\n        msg = (\n            \"The _imaging extension was built for another version of Pillow or PIL:\\n\"\n            f\"Core version: {getattr(core, 'PILLOW_VERSION', None)}\\n\"\n            f\"Pillow version: {__version__}\"\n        )\n        raise ImportError(msg)\n\nexcept ImportError as v:\n    core = DeferredError.new(ImportError(\"The _imaging C module is not installed.\"))\n    # Explanations for ways that we know we might have an import error\n    if str(v).startswith(\"Module use of python\"):\n        # The _imaging C module is present, but not compiled for\n        # the right version (windows only).  Print a warning, if\n        # possible.\n        warnings.warn(\n            \"The _imaging extension was built for another version of Python.\",\n            RuntimeWarning,\n        )\n    elif str(v).startswith(\"The _imaging extension\"):\n        warnings.warn(str(v), RuntimeWarning)\n    # Fail here anyway. Don't let people run with a mostly broken Pillow.\n    # see docs/porting.rst\n    raise\n\n\nUSE_CFFI_ACCESS = False\ncffi: ModuleType | None\ntry:\n    import cffi\nexcept ImportError:\n    cffi = None\n\n\ndef isImageType(t: Any) -> TypeGuard[Image]:\n    \"\"\"\n    Checks if an object is an image object.\n\n    .. warning::\n\n       This function is for internal use only.\n\n    :param t: object to check if it's an image\n    :returns: True if the object is an image\n    \"\"\"\n    return hasattr(t, \"im\")\n\n\n#\n# Constants\n\n\n# transpose\nclass Transpose(IntEnum):\n    FLIP_LEFT_RIGHT = 0\n    FLIP_TOP_BOTTOM = 1\n    ROTATE_90 = 2\n    ROTATE_180 = 3\n    ROTATE_270 = 4\n    TRANSPOSE = 5\n    TRANSVERSE = 6\n\n\n# transforms (also defined in Imaging.h)\nclass Transform(IntEnum):\n    AFFINE = 0\n    EXTENT = 1\n    PERSPECTIVE = 2\n    QUAD = 3\n    MESH = 4\n\n\n# resampling filters (also defined in Imaging.h)\nclass Resampling(IntEnum):\n    NEAREST = 0\n    BOX = 4\n    BILINEAR = 2\n    HAMMING = 5\n    BICUBIC = 3\n    LANCZOS = 1\n\n\n_filters_support = {\n    Resampling.BOX: 0.5,\n    Resampling.BILINEAR: 1.0,\n    Resampling.HAMMING: 1.0,\n    Resampling.BICUBIC: 2.0,\n    Resampling.LANCZOS: 3.0,\n}\n\n\n# dithers\nclass Dither(IntEnum):\n    NONE = 0\n    ORDERED = 1  # Not yet implemented\n    RASTERIZE = 2  # Not yet implemented\n    FLOYDSTEINBERG = 3  # default\n\n\n# palettes/quantizers\nclass Palette(IntEnum):\n    WEB = 0\n    ADAPTIVE = 1\n\n\nclass Quantize(IntEnum):\n    MEDIANCUT = 0\n    MAXCOVERAGE = 1\n    FASTOCTREE = 2\n    LIBIMAGEQUANT = 3\n\n\nmodule = sys.modules[__name__]\nfor enum in (Transpose, Transform, Resampling, Dither, Palette, Quantize):\n    for item in enum:\n        setattr(module, item.name, item.value)\n\n\nif hasattr(core, \"DEFAULT_STRATEGY\"):\n    DEFAULT_STRATEGY = core.DEFAULT_STRATEGY\n    FILTERED = core.FILTERED\n    HUFFMAN_ONLY = core.HUFFMAN_ONLY\n    RLE = core.RLE\n    FIXED = core.FIXED\n\n\n# --------------------------------------------------------------------\n# Registries\n\nif TYPE_CHECKING:\n    from . import ImageFile, PyAccess\nID: list[str] = []\nOPEN: dict[\n    str,\n    tuple[\n        Callable[[IO[bytes], str | bytes], ImageFile.ImageFile],\n        Callable[[bytes], bool | str] | None,\n    ],\n] = {}\nMIME: dict[str, str] = {}\nSAVE: dict[str, Callable[[Image, IO[bytes], str | bytes], None]] = {}\nSAVE_ALL: dict[str, Callable[[Image, IO[bytes], str | bytes], None]] = {}\nEXTENSION: dict[str, str] = {}\nDECODERS: dict[str, type[ImageFile.PyDecoder]] = {}\nENCODERS: dict[str, type[ImageFile.PyEncoder]] = {}\n\n# --------------------------------------------------------------------\n# Modes\n\n_ENDIAN = \"<\" if sys.byteorder == \"little\" else \">\"\n\n\ndef _conv_type_shape(im):\n    m = ImageMode.getmode(im.mode)\n    shape = (im.height, im.width)\n    extra = len(m.bands)\n    if extra != 1:\n        shape += (extra,)\n    return shape, m.typestr\n\n\nMODES = [\n    \"1\",\n    \"CMYK\",\n    \"F\",\n    \"HSV\",\n    \"I\",\n    \"I;16\",\n    \"I;16B\",\n    \"I;16L\",\n    \"I;16N\",\n    \"L\",\n    \"LA\",\n    \"La\",\n    \"LAB\",\n    \"P\",\n    \"PA\",\n    \"RGB\",\n    \"RGBA\",\n    \"RGBa\",\n    \"RGBX\",\n    \"YCbCr\",\n]\n\n# raw modes that may be memory mapped.  NOTE: if you change this, you\n# may have to modify the stride calculation in map.c too!\n_MAPMODES = (\"L\", \"P\", \"RGBX\", \"RGBA\", \"CMYK\", \"I;16\", \"I;16L\", \"I;16B\")\n\n\ndef getmodebase(mode: str) -> str:\n    \"\"\"\n    Gets the \"base\" mode for given mode.  This function returns \"L\" for\n    images that contain grayscale data, and \"RGB\" for images that\n    contain color data.\n\n    :param mode: Input mode.\n    :returns: \"L\" or \"RGB\".\n    :exception KeyError: If the input mode was not a standard mode.\n    \"\"\"\n    return ImageMode.getmode(mode).basemode\n\n\ndef getmodetype(mode: str) -> str:\n    \"\"\"\n    Gets the storage type mode.  Given a mode, this function returns a\n    single-layer mode suitable for storing individual bands.\n\n    :param mode: Input mode.\n    :returns: \"L\", \"I\", or \"F\".\n    :exception KeyError: If the input mode was not a standard mode.\n    \"\"\"\n    return ImageMode.getmode(mode).basetype\n\n\ndef getmodebandnames(mode: str) -> tuple[str, ...]:\n    \"\"\"\n    Gets a list of individual band names.  Given a mode, this function returns\n    a tuple containing the names of individual bands (use\n    :py:method:`~PIL.Image.getmodetype` to get the mode used to store each\n    individual band.\n\n    :param mode: Input mode.\n    :returns: A tuple containing band names.  The length of the tuple\n        gives the number of bands in an image of the given mode.\n    :exception KeyError: If the input mode was not a standard mode.\n    \"\"\"\n    return ImageMode.getmode(mode).bands\n\n\ndef getmodebands(mode: str) -> int:\n    \"\"\"\n    Gets the number of individual bands for this mode.\n\n    :param mode: Input mode.\n    :returns: The number of bands in this mode.\n    :exception KeyError: If the input mode was not a standard mode.\n    \"\"\"\n    return len(ImageMode.getmode(mode).bands)\n\n\n# --------------------------------------------------------------------\n# Helpers\n\n_initialized = 0\n\n\ndef preinit() -> None:\n    \"\"\"\n    Explicitly loads BMP, GIF, JPEG, PPM and PPM file format drivers.\n\n    It is called when opening or saving images.\n    \"\"\"\n\n    global _initialized\n    if _initialized >= 1:\n        return\n\n    try:\n        from . import BmpImagePlugin\n\n        assert BmpImagePlugin\n    except ImportError:\n        pass\n    try:\n        from . import GifImagePlugin\n\n        assert GifImagePlugin\n    except ImportError:\n        pass\n    try:\n        from . import JpegImagePlugin\n\n        assert JpegImagePlugin\n    except ImportError:\n        pass\n    try:\n        from . import PpmImagePlugin\n\n        assert PpmImagePlugin\n    except ImportError:\n        pass\n    try:\n        from . import PngImagePlugin\n\n        assert PngImagePlugin\n    except ImportError:\n        pass\n\n    _initialized = 1\n\n\ndef init() -> bool:\n    \"\"\"\n    Explicitly initializes the Python Imaging Library. This function\n    loads all available file format drivers.\n\n    It is called when opening or saving images if :py:meth:`~preinit()` is\n    insufficient, and by :py:meth:`~PIL.features.pilinfo`.\n    \"\"\"\n\n    global _initialized\n    if _initialized >= 2:\n        return False\n\n    parent_name = __name__.rpartition(\".\")[0]\n    for plugin in _plugins:\n        try:\n            logger.debug(\"Importing %s\", plugin)\n            __import__(f\"{parent_name}.{plugin}\", globals(), locals(), [])\n        except ImportError as e:\n            logger.debug(\"Image: failed to import %s: %s\", plugin, e)\n\n    if OPEN or SAVE:\n        _initialized = 2\n        return True\n    return False\n\n\n# --------------------------------------------------------------------\n# Codec factories (used by tobytes/frombytes and ImageFile.load)\n\n\ndef _getdecoder(\n    mode: str, decoder_name: str, args: Any, extra: tuple[Any, ...] = ()\n) -> core.ImagingDecoder | ImageFile.PyDecoder:\n    # tweak arguments\n    if args is None:\n        args = ()\n    elif not isinstance(args, tuple):\n        args = (args,)\n\n    try:\n        decoder = DECODERS[decoder_name]\n    except KeyError:\n        pass\n    else:\n        return decoder(mode, *args + extra)\n\n    try:\n        # get decoder\n        decoder = getattr(core, f\"{decoder_name}_decoder\")\n    except AttributeError as e:\n        msg = f\"decoder {decoder_name} not available\"\n        raise OSError(msg) from e\n    return decoder(mode, *args + extra)\n\n\ndef _getencoder(\n    mode: str, encoder_name: str, args: Any, extra: tuple[Any, ...] = ()\n) -> core.ImagingEncoder | ImageFile.PyEncoder:\n    # tweak arguments\n    if args is None:\n        args = ()\n    elif not isinstance(args, tuple):\n        args = (args,)\n\n    try:\n        encoder = ENCODERS[encoder_name]\n    except KeyError:\n        pass\n    else:\n        return encoder(mode, *args + extra)\n\n    try:\n        # get encoder\n        encoder = getattr(core, f\"{encoder_name}_encoder\")\n    except AttributeError as e:\n        msg = f\"encoder {encoder_name} not available\"\n        raise OSError(msg) from e\n    return encoder(mode, *args + extra)\n\n\n# --------------------------------------------------------------------\n# Simple expression analyzer\n\n\nclass _E:\n    def __init__(self, scale, offset) -> None:\n        self.scale = scale\n        self.offset = offset\n\n    def __neg__(self):\n        return _E(-self.scale, -self.offset)\n\n    def __add__(self, other):\n        if isinstance(other, _E):\n            return _E(self.scale + other.scale, self.offset + other.offset)\n        return _E(self.scale, self.offset + other)\n\n    __radd__ = __add__\n\n    def __sub__(self, other):\n        return self + -other\n\n    def __rsub__(self, other):\n        return other + -self\n\n    def __mul__(self, other):\n        if isinstance(other, _E):\n            return NotImplemented\n        return _E(self.scale * other, self.offset * other)\n\n    __rmul__ = __mul__\n\n    def __truediv__(self, other):\n        if isinstance(other, _E):\n            return NotImplemented\n        return _E(self.scale / other, self.offset / other)\n\n\ndef _getscaleoffset(expr):\n    a = expr(_E(1, 0))\n    return (a.scale, a.offset) if isinstance(a, _E) else (0, a)\n\n\n# --------------------------------------------------------------------\n# Implementation wrapper\n\n\nclass SupportsGetData(Protocol):\n    def getdata(\n        self,\n    ) -> tuple[Transform, Sequence[int]]: ...\n\n\nclass Image:\n    \"\"\"\n    This class represents an image object.  To create\n    :py:class:`~PIL.Image.Image` objects, use the appropriate factory\n    functions.  There's hardly ever any reason to call the Image constructor\n    directly.\n\n    * :py:func:`~PIL.Image.open`\n    * :py:func:`~PIL.Image.new`\n    * :py:func:`~PIL.Image.frombytes`\n    \"\"\"\n\n    format: str | None = None\n    format_description: str | None = None\n    _close_exclusive_fp_after_loading = True\n\n    def __init__(self):\n        # FIXME: take \"new\" parameters / other image?\n        # FIXME: turn mode and size into delegating properties?\n        self.im = None\n        self._mode = \"\"\n        self._size = (0, 0)\n        self.palette = None\n        self.info = {}\n        self.readonly = 0\n        self.pyaccess = None\n        self._exif = None\n\n    @property\n    def width(self) -> int:\n        return self.size[0]\n\n    @property\n    def height(self) -> int:\n        return self.size[1]\n\n    @property\n    def size(self) -> tuple[int, int]:\n        return self._size\n\n    @property\n    def mode(self) -> str:\n        return self._mode\n\n    def _new(self, im: core.ImagingCore) -> Image:\n        new = Image()\n        new.im = im\n        new._mode = im.mode\n        new._size = im.size\n        if im.mode in (\"P\", \"PA\"):\n            if self.palette:\n                new.palette = self.palette.copy()\n            else:\n                from . import ImagePalette\n\n                new.palette = ImagePalette.ImagePalette()\n        new.info = self.info.copy()\n        return new\n\n    # Context manager support\n    def __enter__(self):\n        return self\n\n    def _close_fp(self):\n        if getattr(self, \"_fp\", False):\n            if self._fp != self.fp:\n                self._fp.close()\n            self._fp = DeferredError(ValueError(\"Operation on closed image\"))\n        if self.fp:\n            self.fp.close()\n\n    def __exit__(self, *args):\n        if hasattr(self, \"fp\"):\n            if getattr(self, \"_exclusive_fp\", False):\n                self._close_fp()\n            self.fp = None\n\n    def close(self) -> None:\n        \"\"\"\n        Closes the file pointer, if possible.\n\n        This operation will destroy the image core and release its memory.\n        The image data will be unusable afterward.\n\n        This function is required to close images that have multiple frames or\n        have not had their file read and closed by the\n        :py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for\n        more information.\n        \"\"\"\n        if hasattr(self, \"fp\"):\n            try:\n                self._close_fp()\n                self.fp = None\n            except Exception as msg:\n                logger.debug(\"Error closing: %s\", msg)\n\n        if getattr(self, \"map\", None):\n            self.map = None\n\n        # Instead of simply setting to None, we're setting up a\n        # deferred error that will better explain that the core image\n        # object is gone.\n        self.im = DeferredError(ValueError(\"Operation on closed image\"))\n\n    def _copy(self) -> None:\n        self.load()\n        self.im = self.im.copy()\n        self.pyaccess = None\n        self.readonly = 0\n\n    def _ensure_mutable(self) -> None:\n        if self.readonly:\n            self._copy()\n        else:\n            self.load()\n\n    def _dump(\n        self, file: str | None = None, format: str | None = None, **options: Any\n    ) -> str:\n        suffix = \"\"\n        if format:\n            suffix = f\".{format}\"\n\n        if not file:\n            f, filename = tempfile.mkstemp(suffix)\n            os.close(f)\n        else:\n            filename = file\n            if not filename.endswith(suffix):\n                filename = filename + suffix\n\n        self.load()\n\n        if not format or format == \"PPM\":\n            self.im.save_ppm(filename)\n        else:\n            self.save(filename, format, **options)\n\n        return filename\n\n    def __eq__(self, other: object) -> bool:\n        if self.__class__ is not other.__class__:\n            return False\n        assert isinstance(other, Image)\n        return (\n            self.mode == other.mode\n            and self.size == other.size\n            and self.info == other.info\n            and self.getpalette() == other.getpalette()\n            and self.tobytes() == other.tobytes()\n        )\n\n    def __repr__(self) -> str:\n        return \"<%s.%s image mode=%s size=%dx%d at 0x%X>\" % (\n            self.__class__.__module__,\n            self.__class__.__name__,\n            self.mode,\n            self.size[0],\n            self.size[1],\n            id(self),\n        )\n\n    def _repr_pretty_(self, p, cycle) -> None:\n        \"\"\"IPython plain text display support\"\"\"\n\n        # Same as __repr__ but without unpredictable id(self),\n        # to keep Jupyter notebook `text/plain` output stable.\n        p.text(\n            \"<%s.%s image mode=%s size=%dx%d>\"\n            % (\n                self.__class__.__module__,\n                self.__class__.__name__,\n                self.mode,\n                self.size[0],\n                self.size[1],\n            )\n        )\n\n    def _repr_image(self, image_format: str, **kwargs: Any) -> bytes | None:\n        \"\"\"Helper function for iPython display hook.\n\n        :param image_format: Image format.\n        :returns: image as bytes, saved into the given format.\n        \"\"\"\n        b = io.BytesIO()\n        try:\n            self.save(b, image_format, **kwargs)\n        except Exception:\n            return None\n        return b.getvalue()\n\n    def _repr_png_(self) -> bytes | None:\n        \"\"\"iPython display hook support for PNG format.\n\n        :returns: PNG version of the image as bytes\n        \"\"\"\n        return self._repr_image(\"PNG\", compress_level=1)\n\n    def _repr_jpeg_(self) -> bytes | None:\n        \"\"\"iPython display hook support for JPEG format.\n\n        :returns: JPEG version of the image as bytes\n        \"\"\"\n        return self._repr_image(\"JPEG\")\n\n    @property\n    def __array_interface__(self):\n        # numpy array interface support\n        new = {\"version\": 3}\n        try:\n            if self.mode == \"1\":\n                # Binary images need to be extended from bits to bytes\n                # See: https://github.com/python-pillow/Pillow/issues/350\n                new[\"data\"] = self.tobytes(\"raw\", \"L\")\n            else:\n                new[\"data\"] = self.tobytes()\n        except Exception as e:\n            if not isinstance(e, (MemoryError, RecursionError)):\n                try:\n                    import numpy\n                    from packaging.version import parse as parse_version\n                except ImportError:\n                    pass\n                else:\n                    if parse_version(numpy.__version__) < parse_version(\"1.23\"):\n                        warnings.warn(str(e))\n            raise\n        new[\"shape\"], new[\"typestr\"] = _conv_type_shape(self)\n        return new\n\n    def __getstate__(self):\n        im_data = self.tobytes()  # load image first\n        return [self.info, self.mode, self.size, self.getpalette(), im_data]\n\n    def __setstate__(self, state) -> None:\n        Image.__init__(self)\n        info, mode, size, palette, data = state\n        self.info = info\n        self._mode = mode\n        self._size = size\n        self.im = core.new(mode, size)\n        if mode in (\"L\", \"LA\", \"P\", \"PA\") and palette:\n            self.putpalette(palette)\n        self.frombytes(data)\n\n    def tobytes(self, encoder_name: str = \"raw\", *args: Any) -> bytes:\n        \"\"\"\n        Return image as a bytes object.\n\n        .. warning::\n\n            This method returns the raw image data from the internal\n            storage.  For compressed image data (e.g. PNG, JPEG) use\n            :meth:`~.save`, with a BytesIO parameter for in-memory\n            data.\n\n        :param encoder_name: What encoder to use.  The default is to\n                             use the standard \"raw\" encoder.\n\n                             A list of C encoders can be seen under\n                             codecs section of the function array in\n                             :file:`_imaging.c`. Python encoders are\n                             registered within the relevant plugins.\n        :param args: Extra arguments to the encoder.\n        :returns: A :py:class:`bytes` object.\n        \"\"\"\n\n        encoder_args: Any = args\n        if len(encoder_args) == 1 and isinstance(encoder_args[0], tuple):\n            # may pass tuple instead of argument list\n            encoder_args = encoder_args[0]\n\n        if encoder_name == \"raw\" and encoder_args == ():\n            encoder_args = self.mode\n\n        self.load()\n\n        if self.width == 0 or self.height == 0:\n            return b\"\"\n\n        # unpack data\n        e = _getencoder(self.mode, encoder_name, encoder_args)\n        e.setimage(self.im)\n\n        bufsize = max(65536, self.size[0] * 4)  # see RawEncode.c\n\n        output = []\n        while True:\n            bytes_consumed, errcode, data = e.encode(bufsize)\n            output.append(data)\n            if errcode:\n                break\n        if errcode < 0:\n            msg = f\"encoder error {errcode} in tobytes\"\n            raise RuntimeError(msg)\n\n        return b\"\".join(output)\n\n    def tobitmap(self, name: str = \"image\") -> bytes:\n        \"\"\"\n        Returns the image converted to an X11 bitmap.\n\n        .. note:: This method only works for mode \"1\" images.\n\n        :param name: The name prefix to use for the bitmap variables.\n        :returns: A string containing an X11 bitmap.\n        :raises ValueError: If the mode is not \"1\"\n        \"\"\"\n\n        self.load()\n        if self.mode != \"1\":\n            msg = \"not a bitmap\"\n            raise ValueError(msg)\n        data = self.tobytes(\"xbm\")\n        return b\"\".join(\n            [\n                f\"#define {name}_width {self.size[0]}\\n\".encode(\"ascii\"),\n                f\"#define {name}_height {self.size[1]}\\n\".encode(\"ascii\"),\n                f\"static char {name}_bits[] = {{\\n\".encode(\"ascii\"),\n                data,\n                b\"};\",\n            ]\n        )\n\n    def frombytes(\n        self, data: bytes | bytearray, decoder_name: str = \"raw\", *args: Any\n    ) -> None:\n        \"\"\"\n        Loads this image with pixel data from a bytes object.\n\n        This method is similar to the :py:func:`~PIL.Image.frombytes` function,\n        but loads data into this image instead of creating a new image object.\n        \"\"\"\n\n        if self.width == 0 or self.height == 0:\n            return\n\n        decoder_args: Any = args\n        if len(decoder_args) == 1 and isinstance(decoder_args[0], tuple):\n            # may pass tuple instead of argument list\n            decoder_args = decoder_args[0]\n\n        # default format\n        if decoder_name == \"raw\" and decoder_args == ():\n            decoder_args = self.mode\n\n        # unpack data\n        d = _getdecoder(self.mode, decoder_name, decoder_args)\n        d.setimage(self.im)\n        s = d.decode(data)\n\n        if s[0] >= 0:\n            msg = \"not enough image data\"\n            raise ValueError(msg)\n        if s[1] != 0:\n            msg = \"cannot decode image data\"\n            raise ValueError(msg)\n\n    def load(self) -> core.PixelAccess | PyAccess.PyAccess | None:\n        \"\"\"\n        Allocates storage for the image and loads the pixel data.  In\n        normal cases, you don't need to call this method, since the\n        Image class automatically loads an opened image when it is\n        accessed for the first time.\n\n        If the file associated with the image was opened by Pillow, then this\n        method will close it. The exception to this is if the image has\n        multiple frames, in which case the file will be left open for seek\n        operations. See :ref:`file-handling` for more information.\n\n        :returns: An image access object.\n        :rtype: :py:class:`.PixelAccess` or :py:class:`.PyAccess`\n        \"\"\"\n        if self.im is not None and self.palette and self.palette.dirty:\n            # realize palette\n            mode, arr = self.palette.getdata()\n            self.im.putpalette(self.palette.mode, mode, arr)\n            self.palette.dirty = 0\n            self.palette.rawmode = None\n            if \"transparency\" in self.info and mode in (\"LA\", \"PA\"):\n                if isinstance(self.info[\"transparency\"], int):\n                    self.im.putpalettealpha(self.info[\"transparency\"], 0)\n                else:\n                    self.im.putpalettealphas(self.info[\"transparency\"])\n                self.palette.mode = \"RGBA\"\n            else:\n                self.palette.palette = self.im.getpalette(\n                    self.palette.mode, self.palette.mode\n                )\n\n        if self.im is not None:\n            if cffi and USE_CFFI_ACCESS:\n                if self.pyaccess:\n                    return self.pyaccess\n                from . import PyAccess\n\n                self.pyaccess = PyAccess.new(self, self.readonly)\n                if self.pyaccess:\n                    return self.pyaccess\n            return self.im.pixel_access(self.readonly)\n        return None\n\n    def verify(self) -> None:\n        \"\"\"\n        Verifies the contents of a file. For data read from a file, this\n        method attempts to determine if the file is broken, without\n        actually decoding the image data.  If this method finds any\n        problems, it raises suitable exceptions.  If you need to load\n        the image after using this method, you must reopen the image\n        file.\n        \"\"\"\n        pass\n\n    def convert(\n        self,\n        mode: str | None = None,\n        matrix: tuple[float, ...] | None = None,\n        dither: Dither | None = None,\n        palette: Palette = Palette.WEB,\n        colors: int = 256,\n    ) -> Image:\n        \"\"\"\n        Returns a converted copy of this image. For the \"P\" mode, this\n        method translates pixels through the palette.  If mode is\n        omitted, a mode is chosen so that all information in the image\n        and the palette can be represented without a palette.\n\n        This supports all possible conversions between \"L\", \"RGB\" and \"CMYK\". The\n        ``matrix`` argument only supports \"L\" and \"RGB\".\n\n        When translating a color image to grayscale (mode \"L\"),\n        the library uses the ITU-R 601-2 luma transform::\n\n            L = R * 299/1000 + G * 587/1000 + B * 114/1000\n\n        The default method of converting a grayscale (\"L\") or \"RGB\"\n        image into a bilevel (mode \"1\") image uses Floyd-Steinberg\n        dither to approximate the original image luminosity levels. If\n        dither is ``None``, all values larger than 127 are set to 255 (white),\n        all other values to 0 (black). To use other thresholds, use the\n        :py:meth:`~PIL.Image.Image.point` method.\n\n        When converting from \"RGBA\" to \"P\" without a ``matrix`` argument,\n        this passes the operation to :py:meth:`~PIL.Image.Image.quantize`,\n        and ``dither`` and ``palette`` are ignored.\n\n        When converting from \"PA\", if an \"RGBA\" palette is present, the alpha\n        channel from the image will be used instead of the values from the palette.\n\n        :param mode: The requested mode. See: :ref:`concept-modes`.\n        :param matrix: An optional conversion matrix.  If given, this\n           should be 4- or 12-tuple containing floating point values.\n        :param dither: Dithering method, used when converting from\n           mode \"RGB\" to \"P\" or from \"RGB\" or \"L\" to \"1\".\n           Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG`\n           (default). Note that this is not used when ``matrix`` is supplied.\n        :param palette: Palette to use when converting from mode \"RGB\"\n           to \"P\".  Available palettes are :data:`Palette.WEB` or\n           :data:`Palette.ADAPTIVE`.\n        :param colors: Number of colors to use for the :data:`Palette.ADAPTIVE`\n           palette. Defaults to 256.\n        :rtype: :py:class:`~PIL.Image.Image`\n        :returns: An :py:class:`~PIL.Image.Image` object.\n        \"\"\"\n\n        if mode in (\"BGR;15\", \"BGR;16\", \"BGR;24\"):\n            deprecate(mode, 12)\n\n        self.load()\n\n        has_transparency = \"transparency\" in self.info\n        if not mode and self.mode == \"P\":\n            # determine default mode\n            if self.palette:\n                mode = self.palette.mode\n            else:\n                mode = \"RGB\"\n            if mode == \"RGB\" and has_transparency:\n                mode = \"RGBA\"\n        if not mode or (mode == self.mode and not matrix):\n            return self.copy()\n\n        if matrix:\n            # matrix conversion\n            if mode not in (\"L\", \"RGB\"):\n                msg = \"illegal conversion\"\n                raise ValueError(msg)\n            im = self.im.convert_matrix(mode, matrix)\n            new_im = self._new(im)\n            if has_transparency and self.im.bands == 3:\n                transparency = new_im.info[\"transparency\"]\n\n                def convert_transparency(\n                    m: tuple[float, ...], v: tuple[int, int, int]\n                ) -> int:\n                    value = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * 0.5\n                    return max(0, min(255, int(value)))\n\n                if mode == \"L\":\n                    transparency = convert_transparency(matrix, transparency)\n                elif len(mode) == 3:\n                    transparency = tuple(\n                        convert_transparency(matrix[i * 4 : i * 4 + 4], transparency)\n                        for i in range(0, len(transparency))\n                    )\n                new_im.info[\"transparency\"] = transparency\n            return new_im\n\n        if mode == \"P\" and self.mode == \"RGBA\":\n            return self.quantize(colors)\n\n        trns = None\n        delete_trns = False\n        # transparency handling\n        if has_transparency:\n            if (self.mode in (\"1\", \"L\", \"I\", \"I;16\") and mode in (\"LA\", \"RGBA\")) or (\n                self.mode == \"RGB\" and mode in (\"La\", \"LA\", \"RGBa\", \"RGBA\")\n            ):\n                # Use transparent conversion to promote from transparent\n                # color to an alpha channel.\n                new_im = self._new(\n                    self.im.convert_transparent(mode, self.info[\"transparency\"])\n                )\n                del new_im.info[\"transparency\"]\n                return new_im\n            elif self.mode in (\"L\", \"RGB\", \"P\") and mode in (\"L\", \"RGB\", \"P\"):\n                t = self.info[\"transparency\"]\n                if isinstance(t, bytes):\n                    # Dragons. This can't be represented by a single color\n                    warnings.warn(\n                        \"Palette images with Transparency expressed in bytes should be \"\n                        \"converted to RGBA images\"\n                    )\n                    delete_trns = True\n                else:\n                    # get the new transparency color.\n                    # use existing conversions\n                    trns_im = new(self.mode, (1, 1))\n                    if self.mode == \"P\":\n                        trns_im.putpalette(self.palette)\n                        if isinstance(t, tuple):\n                            err = \"Couldn't allocate a palette color for transparency\"\n                            try:\n                                t = trns_im.palette.getcolor(t, self)\n                            except ValueError as e:\n                                if str(e) == \"cannot allocate more than 256 colors\":\n                                    # If all 256 colors are in use,\n                                    # then there is no need for transparency\n                                    t = None\n                                else:\n                                    raise ValueError(err) from e\n                    if t is None:\n                        trns = None\n                    else:\n                        trns_im.putpixel((0, 0), t)\n\n                        if mode in (\"L\", \"RGB\"):\n                            trns_im = trns_im.convert(mode)\n                        else:\n                            # can't just retrieve the palette number, got to do it\n                            # after quantization.\n                            trns_im = trns_im.convert(\"RGB\")\n                        trns = trns_im.getpixel((0, 0))\n\n            elif self.mode == \"P\" and mode in (\"LA\", \"PA\", \"RGBA\"):\n                t = self.info[\"transparency\"]\n                delete_trns = True\n\n                if isinstance(t, bytes):\n                    self.im.putpalettealphas(t)\n                elif isinstance(t, int):\n                    self.im.putpalettealpha(t, 0)\n                else:\n                    msg = \"Transparency for P mode should be bytes or int\"\n                    raise ValueError(msg)\n\n        if mode == \"P\" and palette == Palette.ADAPTIVE:\n            im = self.im.quantize(colors)\n            new_im = self._new(im)\n            from . import ImagePalette\n\n            new_im.palette = ImagePalette.ImagePalette(\n                \"RGB\", new_im.im.getpalette(\"RGB\")\n            )\n            if delete_trns:\n                # This could possibly happen if we requantize to fewer colors.\n                # The transparency would be totally off in that case.\n                del new_im.info[\"transparency\"]\n            if trns is not None:\n                try:\n                    new_im.info[\"transparency\"] = new_im.palette.getcolor(\n                        cast(Tuple[int, ...], trns),  # trns was converted to RGB\n                        new_im,\n                    )\n                except Exception:\n                    # if we can't make a transparent color, don't leave the old\n                    # transparency hanging around to mess us up.\n                    del new_im.info[\"transparency\"]\n                    warnings.warn(\"Couldn't allocate palette entry for transparency\")\n            return new_im\n\n        if \"LAB\" in (self.mode, mode):\n            other_mode = mode if self.mode == \"LAB\" else self.mode\n            if other_mode in (\"RGB\", \"RGBA\", \"RGBX\"):\n                from . import ImageCms\n\n                srgb = ImageCms.createProfile(\"sRGB\")\n                lab = ImageCms.createProfile(\"LAB\")\n                profiles = [lab, srgb] if self.mode == \"LAB\" else [srgb, lab]\n                transform = ImageCms.buildTransform(\n                    profiles[0], profiles[1], self.mode, mode\n                )\n                return transform.apply(self)\n\n        # colorspace conversion\n        if dither is None:\n            dither = Dither.FLOYDSTEINBERG\n\n        try:\n            im = self.im.convert(mode, dither)\n        except ValueError:\n            try:\n                # normalize source image and try again\n                modebase = getmodebase(self.mode)\n                if modebase == self.mode:\n                    raise\n                im = self.im.convert(modebase)\n                im = im.convert(mode, dither)\n            except KeyError as e:\n                msg = \"illegal conversion\"\n                raise ValueError(msg) from e\n\n        new_im = self._new(im)\n        if mode == \"P\" and palette != Palette.ADAPTIVE:\n            from . import ImagePalette\n\n            new_im.palette = ImagePalette.ImagePalette(\"RGB\", im.getpalette(\"RGB\"))\n        if delete_trns:\n            # crash fail if we leave a bytes transparency in an rgb/l mode.\n            del new_im.info[\"transparency\"]\n        if trns is not None:\n            if new_im.mode == \"P\" and new_im.palette:\n                try:\n                    new_im.info[\"transparency\"] = new_im.palette.getcolor(trns, new_im)\n                except ValueError as e:\n                    del new_im.info[\"transparency\"]\n                    if str(e) != \"cannot allocate more than 256 colors\":\n                        # If all 256 colors are in use,\n                        # then there is no need for transparency\n                        warnings.warn(\n                            \"Couldn't allocate palette entry for transparency\"\n                        )\n            else:\n                new_im.info[\"transparency\"] = trns\n        return new_im\n\n    def quantize(\n        self,\n        colors: int = 256,\n        method: int | None = None,\n        kmeans: int = 0,\n        palette=None,\n        dither: Dither = Dither.FLOYDSTEINBERG,\n    ) -> Image:\n        \"\"\"\n        Convert the image to 'P' mode with the specified number\n        of colors.\n\n        :param colors: The desired number of colors, <= 256\n        :param method: :data:`Quantize.MEDIANCUT` (median cut),\n                       :data:`Quantize.MAXCOVERAGE` (maximum coverage),\n                       :data:`Quantize.FASTOCTREE` (fast octree),\n                       :data:`Quantize.LIBIMAGEQUANT` (libimagequant; check support\n                       using :py:func:`PIL.features.check_feature` with\n                       ``feature=\"libimagequant\"``).\n\n                       By default, :data:`Quantize.MEDIANCUT` will be used.\n\n                       The exception to this is RGBA images. :data:`Quantize.MEDIANCUT`\n                       and :data:`Quantize.MAXCOVERAGE` do not support RGBA images, so\n                       :data:`Quantize.FASTOCTREE` is used by default instead.\n        :param kmeans: Integer greater than or equal to zero.\n        :param palette: Quantize to the palette of given\n                        :py:class:`PIL.Image.Image`.\n        :param dither: Dithering method, used when converting from\n           mode \"RGB\" to \"P\" or from \"RGB\" or \"L\" to \"1\".\n           Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG`\n           (default).\n        :returns: A new image\n        \"\"\"\n\n        self.load()\n\n        if method is None:\n            # defaults:\n            method = Quantize.MEDIANCUT\n            if self.mode == \"RGBA\":\n                method = Quantize.FASTOCTREE\n\n        if self.mode == \"RGBA\" and method not in (\n            Quantize.FASTOCTREE,\n            Quantize.LIBIMAGEQUANT,\n        ):\n            # Caller specified an invalid mode.\n            msg = (\n                \"Fast Octree (method == 2) and libimagequant (method == 3) \"\n                \"are the only valid methods for quantizing RGBA images\"\n            )\n            raise ValueError(msg)\n\n        if palette:\n            # use palette from reference image\n            palette.load()\n            if palette.mode != \"P\":\n                msg = \"bad mode for palette image\"\n                raise ValueError(msg)\n            if self.mode not in {\"RGB\", \"L\"}:\n                msg = \"only RGB or L mode images can be quantized to a palette\"\n                raise ValueError(msg)\n            im = self.im.convert(\"P\", dither, palette.im)\n            new_im = self._new(im)\n            new_im.palette = palette.palette.copy()\n            return new_im\n\n        if kmeans < 0:\n            msg = \"kmeans must not be negative\"\n            raise ValueError(msg)\n\n        im = self._new(self.im.quantize(colors, method, kmeans))\n\n        from . import ImagePalette\n\n        mode = im.im.getpalettemode()\n        palette = im.im.getpalette(mode, mode)[: colors * len(mode)]\n        im.palette = ImagePalette.ImagePalette(mode, palette)\n\n        return im\n\n    def copy(self) -> Image:\n        \"\"\"\n        Copies this image. Use this method if you wish to paste things\n        into an image, but still retain the original.\n\n        :rtype: :py:class:`~PIL.Image.Image`\n        :returns: An :py:class:`~PIL.Image.Image` object.\n        \"\"\"\n        self.load()\n        return self._new(self.im.copy())\n\n    __copy__ = copy\n\n    def crop(self, box: tuple[float, float, float, float] | None = None) -> Image:\n        \"\"\"\n        Returns a rectangular region from this image. The box is a\n        4-tuple defining the left, upper, right, and lower pixel\n        coordinate. See :ref:`coordinate-system`.\n\n        Note: Prior to Pillow 3.4.0, this was a lazy operation.\n\n        :param box: The crop rectangle, as a (left, upper, right, lower)-tuple.\n        :rtype: :py:class:`~PIL.Image.Image`\n        :returns: An :py:class:`~PIL.Image.Image` object.\n        \"\"\"\n\n        if box is None:\n            return self.copy()\n\n        if box[2] < box[0]:\n            msg = \"Coordinate 'right' is less than 'left'\"\n            raise ValueError(msg)\n        elif box[3] < box[1]:\n            msg = \"Coordinate 'lower' is less than 'upper'\"\n            raise ValueError(msg)\n\n        self.load()\n        return self._new(self._crop(self.im, box))\n\n    def _crop(\n        self, im: core.ImagingCore, box: tuple[float, float, float, float]\n    ) -> core.ImagingCore:\n        \"\"\"\n        Returns a rectangular region from the core image object im.\n\n        This is equivalent to calling im.crop((x0, y0, x1, y1)), but\n        includes additional sanity checks.\n\n        :param im: a core image object\n        :param box: The crop rectangle, as a (left, upper, right, lower)-tuple.\n        :returns: A core image object.\n        \"\"\"\n\n        x0, y0, x1, y1 = map(int, map(round, box))\n\n        absolute_values = (abs(x1 - x0), abs(y1 - y0))\n\n        _decompression_bomb_check(absolute_values)\n\n        return im.crop((x0, y0, x1, y1))\n\n    def draft(\n        self, mode: str | None, size: tuple[int, int] | None\n    ) -> tuple[str, tuple[int, int, float, float]] | None:\n        \"\"\"\n        Configures the image file loader so it returns a version of the\n        image that as closely as possible matches the given mode and\n        size. For example, you can use this method to convert a color\n        JPEG to grayscale while loading it.\n\n        If any changes are made, returns a tuple with the chosen ``mode`` and\n        ``box`` with coordinates of the original image within the altered one.\n\n        Note that this method modifies the :py:class:`~PIL.Image.Image` object\n        in place. If the image has already been loaded, this method has no\n        effect.\n\n        Note: This method is not implemented for most images. It is\n        currently implemented only for JPEG and MPO images.\n\n        :param mode: The requested mode.\n        :param size: The requested size in pixels, as a 2-tuple:\n           (width, height).\n        \"\"\"\n        pass\n\n    def _expand(self, xmargin: int, ymargin: int | None = None) -> Image:\n        if ymargin is None:\n            ymargin = xmargin\n        self.load()\n        return self._new(self.im.expand(xmargin, ymargin))\n\n    if TYPE_CHECKING:\n        from . import ImageFilter\n\n    def filter(self, filter: ImageFilter.Filter | type[ImageFilter.Filter]) -> Image:\n        \"\"\"\n        Filters this image using the given filter.  For a list of\n        available filters, see the :py:mod:`~PIL.ImageFilter` module.\n\n        :param filter: Filter kernel.\n        :returns: An :py:class:`~PIL.Image.Image` object.\"\"\"\n\n        from . import ImageFilter\n\n        self.load()\n\n        if callable(filter):\n            filter = filter()\n        if not hasattr(filter, \"filter\"):\n            msg = \"filter argument should be ImageFilter.Filter instance or class\"\n            raise TypeError(msg)\n\n        multiband = isinstance(filter, ImageFilter.MultibandFilter)\n        if self.im.bands == 1 or multiband:\n            return self._new(filter.filter(self.im))\n\n        ims = [\n            self._new(filter.filter(self.im.getband(c))) for c in range(self.im.bands)\n        ]\n        return merge(self.mode, ims)\n\n    def getbands(self) -> tuple[str, ...]:\n        \"\"\"\n        Returns a tuple containing the name of each band in this image.\n        For example, ``getbands`` on an RGB image returns (\"R\", \"G\", \"B\").\n\n        :returns: A tuple containing band names.\n        :rtype: tuple\n        \"\"\"\n        return ImageMode.getmode(self.mode).bands\n\n    def getbbox(self, *, alpha_only: bool = True) -> tuple[int, int, int, int] | None:\n        \"\"\"\n        Calculates the bounding box of the non-zero regions in the\n        image.\n\n        :param alpha_only: Optional flag, defaulting to ``True``.\n           If ``True`` and the image has an alpha channel, trim transparent pixels.\n           Otherwise, trim pixels when all channels are zero.\n           Keyword-only argument.\n        :returns: The bounding box is returned as a 4-tuple defining the\n           left, upper, right, and lower pixel coordinate. See\n           :ref:`coordinate-system`. If the image is completely empty, this\n           method returns None.\n\n        \"\"\"\n\n        self.load()\n        return self.im.getbbox(alpha_only)\n\n    def getcolors(self, maxcolors: int = 256):\n        \"\"\"\n        Returns a list of colors used in this image.\n\n        The colors will be in the image's mode. For example, an RGB image will\n        return a tuple of (red, green, blue) color values, and a P image will\n        return the index of the color in the palette.\n\n        :param maxcolors: Maximum number of colors.  If this number is\n           exceeded, this method returns None.  The default limit is\n           256 colors.\n        :returns: An unsorted list of (count, pixel) values.\n        \"\"\"\n\n        self.load()\n        if self.mode in (\"1\", \"L\", \"P\"):\n            h = self.im.histogram()\n            out = [(h[i], i) for i in range(256) if h[i]]\n            if len(out) > maxcolors:\n                return None\n            return out\n        return self.im.getcolors(maxcolors)\n\n    def getdata(self, band: int | None = None):\n        \"\"\"\n        Returns the contents of this image as a sequence object\n        containing pixel values.  The sequence object is flattened, so\n        that values for line one follow directly after the values of\n        line zero, and so on.\n\n        Note that the sequence object returned by this method is an\n        internal PIL data type, which only supports certain sequence\n        operations.  To convert it to an ordinary sequence (e.g. for\n        printing), use ``list(im.getdata())``.\n\n        :param band: What band to return.  The default is to return\n           all bands.  To return a single band, pass in the index\n           value (e.g. 0 to get the \"R\" band from an \"RGB\" image).\n        :returns: A sequence-like object.\n        \"\"\"\n\n        self.load()\n        if band is not None:\n            return self.im.getband(band)\n        return self.im  # could be abused\n\n    def getextrema(self) -> tuple[float, float] | tuple[tuple[int, int], ...]:\n        \"\"\"\n        Gets the minimum and maximum pixel values for each band in\n        the image.\n\n        :returns: For a single-band image, a 2-tuple containing the\n           minimum and maximum pixel value.  For a multi-band image,\n           a tuple containing one 2-tuple for each band.\n        \"\"\"\n\n        self.load()\n        if self.im.bands > 1:\n            return tuple(self.im.getband(i).getextrema() for i in range(self.im.bands))\n        return self.im.getextrema()\n\n    def getxmp(self):\n        \"\"\"\n        Returns a dictionary containing the XMP tags.\n        Requires defusedxml to be installed.\n\n        :returns: XMP tags in a dictionary.\n        \"\"\"\n\n        def get_name(tag: str) -> str:\n            return re.sub(\"^{[^}]+}\", \"\", tag)\n\n        def get_value(element):\n            value = {get_name(k): v for k, v in element.attrib.items()}\n            children = list(element)\n            if children:\n                for child in children:\n                    name = get_name(child.tag)\n                    child_value = get_value(child)\n                    if name in value:\n                        if not isinstance(value[name], list):\n                            value[name] = [value[name]]\n                        value[name].append(child_value)\n                    else:\n                        value[name] = child_value\n            elif value:\n                if element.text:\n                    value[\"text\"] = element.text\n            else:\n                return element.text\n            return value\n\n        if ElementTree is None:\n            warnings.warn(\"XMP data cannot be read without defusedxml dependency\")\n            return {}\n        if \"xmp\" not in self.info:\n            return {}\n        root = ElementTree.fromstring(self.info[\"xmp\"].rstrip(b\"\\x00\"))\n        return {get_name(root.tag): get_value(root)}\n\n    def getexif(self) -> Exif:\n        \"\"\"\n        Gets EXIF data from the image.\n\n        :returns: an :py:class:`~PIL.Image.Exif` object.\n        \"\"\"\n        if self._exif is None:\n            self._exif = Exif()\n        elif self._exif._loaded:\n            return self._exif\n        self._exif._loaded = True\n\n        exif_info = self.info.get(\"exif\")\n        if exif_info is None:\n            if \"Raw profile type exif\" in self.info:\n                exif_info = bytes.fromhex(\n                    \"\".join(self.info[\"Raw profile type exif\"].split(\"\\n\")[3:])\n                )\n            elif hasattr(self, \"tag_v2\"):\n                self._exif.bigtiff = self.tag_v2._bigtiff\n                self._exif.endian = self.tag_v2._endian\n                self._exif.load_from_fp(self.fp, self.tag_v2._offset)\n        if exif_info is not None:\n            self._exif.load(exif_info)\n\n        # XMP tags\n        if ExifTags.Base.Orientation not in self._exif:\n            xmp_tags = self.info.get(\"XML:com.adobe.xmp\")\n            if xmp_tags:\n                match = re.search(r'tiff:Orientation(=\"|>)([0-9])', xmp_tags)\n                if match:\n                    self._exif[ExifTags.Base.Orientation] = int(match[2])\n\n        return self._exif\n\n    def _reload_exif(self) -> None:\n        if self._exif is None or not self._exif._loaded:\n            return\n        self._exif._loaded = False\n        self.getexif()\n\n    def get_child_images(self) -> list[ImageFile.ImageFile]:\n        child_images = []\n        exif = self.getexif()\n        ifds = []\n        if ExifTags.Base.SubIFDs in exif:\n            subifd_offsets = exif[ExifTags.Base.SubIFDs]\n            if subifd_offsets:\n                if not isinstance(subifd_offsets, tuple):\n                    subifd_offsets = (subifd_offsets,)\n                for subifd_offset in subifd_offsets:\n                    ifds.append((exif._get_ifd_dict(subifd_offset), subifd_offset))\n        ifd1 = exif.get_ifd(ExifTags.IFD.IFD1)\n        if ifd1 and ifd1.get(513):\n            ifds.append((ifd1, exif._info.next))\n\n        offset = None\n        for ifd, ifd_offset in ifds:\n            current_offset = self.fp.tell()\n            if offset is None:\n                offset = current_offset\n\n            fp = self.fp\n            thumbnail_offset = ifd.get(513)\n            if thumbnail_offset is not None:\n                thumbnail_offset += getattr(self, \"_exif_offset\", 0)\n                self.fp.seek(thumbnail_offset)\n                data = self.fp.read(ifd.get(514))\n                fp = io.BytesIO(data)\n\n            with open(fp) as im:\n                from . import TiffImagePlugin\n\n                if thumbnail_offset is None and isinstance(\n                    im, TiffImagePlugin.TiffImageFile\n                ):\n                    im._frame_pos = [ifd_offset]\n                    im._seek(0)\n                im.load()\n                child_images.append(im)\n\n        if offset is not None:\n            self.fp.seek(offset)\n        return child_images\n\n    def getim(self):\n        \"\"\"\n        Returns a capsule that points to the internal image memory.\n\n        :returns: A capsule object.\n        \"\"\"\n\n        self.load()\n        return self.im.ptr\n\n    def getpalette(self, rawmode: str | None = \"RGB\") -> list[int] | None:\n        \"\"\"\n        Returns the image palette as a list.\n\n        :param rawmode: The mode in which to return the palette. ``None`` will\n           return the palette in its current mode.\n\n           .. versionadded:: 9.1.0\n\n        :returns: A list of color values [r, g, b, ...], or None if the\n           image has no palette.\n        \"\"\"\n\n        self.load()\n        try:\n            mode = self.im.getpalettemode()\n        except ValueError:\n            return None  # no palette\n        if rawmode is None:\n            rawmode = mode\n        return list(self.im.getpalette(mode, rawmode))\n\n    @property\n    def has_transparency_data(self) -> bool:\n        \"\"\"\n        Determine if an image has transparency data, whether in the form of an\n        alpha channel, a palette with an alpha channel, or a \"transparency\" key\n        in the info dictionary.\n\n        Note the image might still appear solid, if all of the values shown\n        within are opaque.\n\n        :returns: A boolean.\n        \"\"\"\n        return (\n            self.mode in (\"LA\", \"La\", \"PA\", \"RGBA\", \"RGBa\")\n            or (self.mode == \"P\" and self.palette.mode.endswith(\"A\"))\n            or \"transparency\" in self.info\n        )\n\n    def apply_transparency(self) -> None:\n        \"\"\"\n        If a P mode image has a \"transparency\" key in the info dictionary,\n        remove the key and instead apply the transparency to the palette.\n        Otherwise, the image is unchanged.\n        \"\"\"\n        if self.mode != \"P\" or \"transparency\" not in self.info:\n            return\n\n        from . import ImagePalette\n\n        palette = self.getpalette(\"RGBA\")\n        assert palette is not None\n        transparency = self.info[\"transparency\"]\n        if isinstance(transparency, bytes):\n            for i, alpha in enumerate(transparency):\n                palette[i * 4 + 3] = alpha\n        else:\n            palette[transparency * 4 + 3] = 0\n        self.palette = ImagePalette.ImagePalette(\"RGBA\", bytes(palette))\n        self.palette.dirty = 1\n\n        del self.info[\"transparency\"]\n\n    def getpixel(\n        self, xy: tuple[int, int] | list[int]\n    ) -> float | tuple[int, ...] | None:\n        \"\"\"\n        Returns the pixel value at a given position.\n\n        :param xy: The coordinate, given as (x, y). See\n           :ref:`coordinate-system`.\n        :returns: The pixel value.  If the image is a multi-layer image,\n           this method returns a tuple.\n        \"\"\"\n\n        self.load()\n        if self.pyaccess:\n            return self.pyaccess.getpixel(xy)\n        return self.im.getpixel(tuple(xy))\n\n    def getprojection(self) -> tuple[list[int], list[int]]:\n        \"\"\"\n        Get projection to x and y axes\n\n        :returns: Two sequences, indicating where there are non-zero\n            pixels along the X-axis and the Y-axis, respectively.\n        \"\"\"\n\n        self.load()\n        x, y = self.im.getprojection()\n        return list(x), list(y)\n\n    def histogram(self, mask: Image | None = None, extrema=None) -> list[int]:\n        \"\"\"\n        Returns a histogram for the image. The histogram is returned as a\n        list of pixel counts, one for each pixel value in the source\n        image. Counts are grouped into 256 bins for each band, even if\n        the image has more than 8 bits per band. If the image has more\n        than one band, the histograms for all bands are concatenated (for\n        example, the histogram for an \"RGB\" image contains 768 values).\n\n        A bilevel image (mode \"1\") is treated as a grayscale (\"L\") image\n        by this method.\n\n        If a mask is provided, the method returns a histogram for those\n        parts of the image where the mask image is non-zero. The mask\n        image must have the same size as the image, and be either a\n        bi-level image (mode \"1\") or a grayscale image (\"L\").\n\n        :param mask: An optional mask.\n        :param extrema: An optional tuple of manually-specified extrema.\n        :returns: A list containing pixel counts.\n        \"\"\"\n        self.load()\n        if mask:\n            mask.load()\n            return self.im.histogram((0, 0), mask.im)\n        if self.mode in (\"I\", \"F\"):\n            if extrema is None:\n                extrema = self.getextrema()\n            return self.im.histogram(extrema)\n        return self.im.histogram()\n\n    def entropy(self, mask=None, extrema=None):\n        \"\"\"\n        Calculates and returns the entropy for the image.\n\n        A bilevel image (mode \"1\") is treated as a grayscale (\"L\")\n        image by this method.\n\n        If a mask is provided, the method employs the histogram for\n        those parts of the image where the mask image is non-zero.\n        The mask image must have the same size as the image, and be\n        either a bi-level image (mode \"1\") or a grayscale image (\"L\").\n\n        :param mask: An optional mask.\n        :param extrema: An optional tuple of manually-specified extrema.\n        :returns: A float value representing the image entropy\n        \"\"\"\n        self.load()\n        if mask:\n            mask.load()\n            return self.im.entropy((0, 0), mask.im)\n        if self.mode in (\"I\", \"F\"):\n            if extrema is None:\n                extrema = self.getextrema()\n            return self.im.entropy(extrema)\n        return self.im.entropy()\n\n    def paste(\n        self,\n        im: Image | str | float | tuple[float, ...],\n        box: Image | tuple[int, int, int, int] | tuple[int, int] | None = None,\n        mask: Image | None = None,\n    ) -> None:\n        \"\"\"\n        Pastes another image into this image. The box argument is either\n        a 2-tuple giving the upper left corner, a 4-tuple defining the\n        left, upper, right, and lower pixel coordinate, or None (same as\n        (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size\n        of the pasted image must match the size of the region.\n\n        If the modes don't match, the pasted image is converted to the mode of\n        this image (see the :py:meth:`~PIL.Image.Image.convert` method for\n        details).\n\n        Instead of an image, the source can be a integer or tuple\n        containing pixel values.  The method then fills the region\n        with the given color.  When creating RGB images, you can\n        also use color strings as supported by the ImageColor module.\n\n        If a mask is given, this method updates only the regions\n        indicated by the mask. You can use either \"1\", \"L\", \"LA\", \"RGBA\"\n        or \"RGBa\" images (if present, the alpha band is used as mask).\n        Where the mask is 255, the given image is copied as is.  Where\n        the mask is 0, the current value is preserved.  Intermediate\n        values will mix the two images together, including their alpha\n        channels if they have them.\n\n        See :py:meth:`~PIL.Image.Image.alpha_composite` if you want to\n        combine images with respect to their alpha channels.\n\n        :param im: Source image or pixel value (integer, float or tuple).\n        :param box: An optional 4-tuple giving the region to paste into.\n           If a 2-tuple is used instead, it's treated as the upper left\n           corner.  If omitted or None, the source is pasted into the\n           upper left corner.\n\n           If an image is given as the second argument and there is no\n           third, the box defaults to (0, 0), and the second argument\n           is interpreted as a mask image.\n        :param mask: An optional mask image.\n        \"\"\"\n\n        if isImageType(box):\n            if mask is not None:\n                msg = \"If using second argument as mask, third argument must be None\"\n                raise ValueError(msg)\n            # abbreviated paste(im, mask) syntax\n            mask = box\n            box = None\n        assert not isinstance(box, Image)\n\n        if box is None:\n            box = (0, 0)\n\n        if len(box) == 2:\n            # upper left corner given; get size from image or mask\n            if isImageType(im):\n                size = im.size\n            elif isImageType(mask):\n                size = mask.size\n            else:\n                # FIXME: use self.size here?\n                msg = \"cannot determine region size; use 4-item box\"\n                raise ValueError(msg)\n            box += (box[0] + size[0], box[1] + size[1])\n\n        if isinstance(im, str):\n            from . import ImageColor\n\n            im = ImageColor.getcolor(im, self.mode)\n\n        elif isImageType(im):\n            im.load()\n            if self.mode != im.mode:\n                if self.mode != \"RGB\" or im.mode not in (\"LA\", \"RGBA\", \"RGBa\"):\n                    # should use an adapter for this!\n                    im = im.convert(self.mode)\n            im = im.im\n\n        self._ensure_mutable()\n\n        if mask:\n            mask.load()\n            self.im.paste(im, box, mask.im)\n        else:\n            self.im.paste(im, box)\n\n    def alpha_composite(\n        self, im: Image, dest: Sequence[int] = (0, 0), source: Sequence[int] = (0, 0)\n    ) -> None:\n        \"\"\"'In-place' analog of Image.alpha_composite. Composites an image\n        onto this image.\n\n        :param im: image to composite over this one\n        :param dest: Optional 2 tuple (left, top) specifying the upper\n          left corner in this (destination) image.\n        :param source: Optional 2 (left, top) tuple for the upper left\n          corner in the overlay source image, or 4 tuple (left, top, right,\n          bottom) for the bounds of the source rectangle\n\n        Performance Note: Not currently implemented in-place in the core layer.\n        \"\"\"\n\n        if not isinstance(source, (list, tuple)):\n            msg = \"Source must be a list or tuple\"\n            raise ValueError(msg)\n        if not isinstance(dest, (list, tuple)):\n            msg = \"Destination must be a list or tuple\"\n            raise ValueError(msg)\n\n        if len(source) == 4:\n            overlay_crop_box = tuple(source)\n        elif len(source) == 2:\n            overlay_crop_box = tuple(source) + im.size\n        else:\n            msg = \"Source must be a sequence of length 2 or 4\"\n            raise ValueError(msg)\n\n        if not len(dest) == 2:\n            msg = \"Destination must be a sequence of length 2\"\n            raise ValueError(msg)\n        if min(source) < 0:\n            msg = \"Source must be non-negative\"\n            raise ValueError(msg)\n\n        # over image, crop if it's not the whole image.\n        if overlay_crop_box == (0, 0) + im.size:\n            overlay = im\n        else:\n            overlay = im.crop(overlay_crop_box)\n\n        # target for the paste\n        box = tuple(dest) + (dest[0] + overlay.width, dest[1] + overlay.height)\n\n        # destination image. don't copy if we're using the whole image.\n        if box == (0, 0) + self.size:\n            background = self\n        else:\n            background = self.crop(box)\n\n        result = alpha_composite(background, overlay)\n        self.paste(result, box)\n\n    def point(\n        self,\n        lut: Sequence[float] | Callable[[int], float] | ImagePointHandler,\n        mode: str | None = None,\n    ) -> Image:\n        \"\"\"\n        Maps this image through a lookup table or function.\n\n        :param lut: A lookup table, containing 256 (or 65536 if\n           self.mode==\"I\" and mode == \"L\") values per band in the\n           image.  A function can be used instead, it should take a\n           single argument. The function is called once for each\n           possible pixel value, and the resulting table is applied to\n           all bands of the image.\n\n           It may also be an :py:class:`~PIL.Image.ImagePointHandler`\n           object::\n\n               class Example(Image.ImagePointHandler):\n                 def point(self, data):\n                   # Return result\n        :param mode: Output mode (default is same as input). This can only be used if\n           the source image has mode \"L\" or \"P\", and the output has mode \"1\" or the\n           source image mode is \"I\" and the output mode is \"L\".\n        :returns: An :py:class:`~PIL.Image.Image` object.\n        \"\"\"\n\n        self.load()\n\n        if isinstance(lut, ImagePointHandler):\n            return lut.point(self)\n\n        if callable(lut):\n            # if it isn't a list, it should be a function\n            if self.mode in (\"I\", \"I;16\", \"F\"):\n                # check if the function can be used with point_transform\n                # UNDONE wiredfool -- I think this prevents us from ever doing\n                # a gamma function point transform on > 8bit images.\n                scale, offset = _getscaleoffset(lut)\n                return self._new(self.im.point_transform(scale, offset))\n            # for other modes, convert the function to a table\n            flatLut = [lut(i) for i in range(256)] * self.im.bands\n        else:\n            flatLut = lut\n\n        if self.mode == \"F\":\n            # FIXME: _imaging returns a confusing error message for this case\n            msg = \"point operation not supported for this mode\"\n            raise ValueError(msg)\n\n        if mode != \"F\":\n            flatLut = [round(i) for i in flatLut]\n        return self._new(self.im.point(flatLut, mode))\n\n    def putalpha(self, alpha: Image | int) -> None:\n        \"\"\"\n        Adds or replaces the alpha layer in this image.  If the image\n        does not have an alpha layer, it's converted to \"LA\" or \"RGBA\".\n        The new layer must be either \"L\" or \"1\".\n\n        :param alpha: The new alpha layer.  This can either be an \"L\" or \"1\"\n           image having the same size as this image, or an integer.\n        \"\"\"\n\n        self._ensure_mutable()\n\n        if self.mode not in (\"LA\", \"PA\", \"RGBA\"):\n            # attempt to promote self to a matching alpha mode\n            try:\n                mode = getmodebase(self.mode) + \"A\"\n                try:\n                    self.im.setmode(mode)\n                except (AttributeError, ValueError) as e:\n                    # do things the hard way\n                    im = self.im.convert(mode)\n                    if im.mode not in (\"LA\", \"PA\", \"RGBA\"):\n                        msg = \"alpha channel could not be added\"\n                        raise ValueError(msg) from e  # sanity check\n                    self.im = im\n                self.pyaccess = None\n                self._mode = self.im.mode\n            except KeyError as e:\n                msg = \"illegal image mode\"\n                raise ValueError(msg) from e\n\n        if self.mode in (\"LA\", \"PA\"):\n            band = 1\n        else:\n            band = 3\n\n        if isImageType(alpha):\n            # alpha layer\n            if alpha.mode not in (\"1\", \"L\"):\n                msg = \"illegal image mode\"\n                raise ValueError(msg)\n            alpha.load()\n            if alpha.mode == \"1\":\n                alpha = alpha.convert(\"L\")\n        else:\n            # constant alpha\n            alpha = cast(int, alpha)  # see python/typing#1013\n            try:\n                self.im.fillband(band, alpha)\n            except (AttributeError, ValueError):\n                # do things the hard way\n                alpha = new(\"L\", self.size, alpha)\n            else:\n                return\n\n        self.im.putband(alpha.im, band)\n\n    def putdata(\n        self,\n        data: Sequence[float] | Sequence[Sequence[int]],\n        scale: float = 1.0,\n        offset: float = 0.0,\n    ) -> None:\n        \"\"\"\n        Copies pixel data from a flattened sequence object into the image. The\n        values should start at the upper left corner (0, 0), continue to the\n        end of the line, followed directly by the first value of the second\n        line, and so on. Data will be read until either the image or the\n        sequence ends. The scale and offset values are used to adjust the\n        sequence values: **pixel = value*scale + offset**.\n\n        :param data: A flattened sequence object.\n        :param scale: An optional scale value.  The default is 1.0.\n        :param offset: An optional offset value.  The default is 0.0.\n        \"\"\"\n\n        self._ensure_mutable()\n\n        self.im.putdata(data, scale, offset)\n\n    def putpalette(self, data, rawmode=\"RGB\") -> None:\n        \"\"\"\n        Attaches a palette to this image.  The image must be a \"P\", \"PA\", \"L\"\n        or \"LA\" image.\n\n        The palette sequence must contain at most 256 colors, made up of one\n        integer value for each channel in the raw mode.\n        For example, if the raw mode is \"RGB\", then it can contain at most 768\n        values, made up of red, green and blue values for the corresponding pixel\n        index in the 256 colors.\n        If the raw mode is \"RGBA\", then it can contain at most 1024 values,\n        containing red, green, blue and alpha values.\n\n        Alternatively, an 8-bit string may be used instead of an integer sequence.\n\n        :param data: A palette sequence (either a list or a string).\n        :param rawmode: The raw mode of the palette. Either \"RGB\", \"RGBA\", or a mode\n           that can be transformed to \"RGB\" or \"RGBA\" (e.g. \"R\", \"BGR;15\", \"RGBA;L\").\n        \"\"\"\n        from . import ImagePalette\n\n        if self.mode not in (\"L\", \"LA\", \"P\", \"PA\"):\n            msg = \"illegal image mode\"\n            raise ValueError(msg)\n        if isinstance(data, ImagePalette.ImagePalette):\n            palette = ImagePalette.raw(data.rawmode, data.palette)\n        else:\n            if not isinstance(data, bytes):\n                data = bytes(data)\n            palette = ImagePalette.raw(rawmode, data)\n        self._mode = \"PA\" if \"A\" in self.mode else \"P\"\n        self.palette = palette\n        self.palette.mode = \"RGBA\" if \"A\" in rawmode else \"RGB\"\n        self.load()  # install new palette\n\n    def putpixel(\n        self, xy: tuple[int, int], value: float | tuple[int, ...] | list[int]\n    ) -> None:\n        \"\"\"\n        Modifies the pixel at the given position. The color is given as\n        a single numerical value for single-band images, and a tuple for\n        multi-band images. In addition to this, RGB and RGBA tuples are\n        accepted for P and PA images.\n\n        Note that this method is relatively slow.  For more extensive changes,\n        use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw`\n        module instead.\n\n        See:\n\n        * :py:meth:`~PIL.Image.Image.paste`\n        * :py:meth:`~PIL.Image.Image.putdata`\n        * :py:mod:`~PIL.ImageDraw`\n\n        :param xy: The pixel coordinate, given as (x, y). See\n           :ref:`coordinate-system`.\n        :param value: The pixel value.\n        \"\"\"\n\n        if self.readonly:\n            self._copy()\n        self.load()\n\n        if self.pyaccess:\n            return self.pyaccess.putpixel(xy, value)\n\n        if (\n            self.mode in (\"P\", \"PA\")\n            and isinstance(value, (list, tuple))\n            and len(value) in [3, 4]\n        ):\n            # RGB or RGBA value for a P or PA image\n            if self.mode == \"PA\":\n                alpha = value[3] if len(value) == 4 else 255\n                value = value[:3]\n            palette_index = self.palette.getcolor(value, self)\n            value = (palette_index, alpha) if self.mode == \"PA\" else palette_index\n        return self.im.putpixel(xy, value)\n\n    def remap_palette(self, dest_map, source_palette=None):\n        \"\"\"\n        Rewrites the image to reorder the palette.\n\n        :param dest_map: A list of indexes into the original palette.\n           e.g. ``[1,0]`` would swap a two item palette, and ``list(range(256))``\n           is the identity transform.\n        :param source_palette: Bytes or None.\n        :returns:  An :py:class:`~PIL.Image.Image` object.\n\n        \"\"\"\n        from . import ImagePalette\n\n        if self.mode not in (\"L\", \"P\"):\n            msg = \"illegal image mode\"\n            raise ValueError(msg)\n\n        bands = 3\n        palette_mode = \"RGB\"\n        if source_palette is None:\n            if self.mode == \"P\":\n                self.load()\n                palette_mode = self.im.getpalettemode()\n                if palette_mode == \"RGBA\":\n                    bands = 4\n                source_palette = self.im.getpalette(palette_mode, palette_mode)\n            else:  # L-mode\n                source_palette = bytearray(i // 3 for i in range(768))\n\n        palette_bytes = b\"\"\n        new_positions = [0] * 256\n\n        # pick only the used colors from the palette\n        for i, oldPosition in enumerate(dest_map):\n            palette_bytes += source_palette[\n                oldPosition * bands : oldPosition * bands + bands\n            ]\n            new_positions[oldPosition] = i\n\n        # replace the palette color id of all pixel with the new id\n\n        # Palette images are [0..255], mapped through a 1 or 3\n        # byte/color map.  We need to remap the whole image\n        # from palette 1 to palette 2. New_positions is\n        # an array of indexes into palette 1.  Palette 2 is\n        # palette 1 with any holes removed.\n\n        # We're going to leverage the convert mechanism to use the\n        # C code to remap the image from palette 1 to palette 2,\n        # by forcing the source image into 'L' mode and adding a\n        # mapping 'L' mode palette, then converting back to 'L'\n        # sans palette thus converting the image bytes, then\n        # assigning the optimized RGB palette.\n\n        # perf reference, 9500x4000 gif, w/~135 colors\n        # 14 sec prepatch, 1 sec postpatch with optimization forced.\n\n        mapping_palette = bytearray(new_positions)\n\n        m_im = self.copy()\n        m_im._mode = \"P\"\n\n        m_im.palette = ImagePalette.ImagePalette(\n            palette_mode, palette=mapping_palette * bands\n        )\n        # possibly set palette dirty, then\n        # m_im.putpalette(mapping_palette, 'L')  # converts to 'P'\n        # or just force it.\n        # UNDONE -- this is part of the general issue with palettes\n        m_im.im.putpalette(palette_mode, palette_mode + \";L\", m_im.palette.tobytes())\n\n        m_im = m_im.convert(\"L\")\n\n        m_im.putpalette(palette_bytes, palette_mode)\n        m_im.palette = ImagePalette.ImagePalette(palette_mode, palette=palette_bytes)\n\n        if \"transparency\" in self.info:\n            try:\n                m_im.info[\"transparency\"] = dest_map.index(self.info[\"transparency\"])\n            except ValueError:\n                if \"transparency\" in m_im.info:\n                    del m_im.info[\"transparency\"]\n\n        return m_im\n\n    def _get_safe_box(self, size, resample, box):\n        \"\"\"Expands the box so it includes adjacent pixels\n        that may be used by resampling with the given resampling filter.\n        \"\"\"\n        filter_support = _filters_support[resample] - 0.5\n        scale_x = (box[2] - box[0]) / size[0]\n        scale_y = (box[3] - box[1]) / size[1]\n        support_x = filter_support * scale_x\n        support_y = filter_support * scale_y\n\n        return (\n            max(0, int(box[0] - support_x)),\n            max(0, int(box[1] - support_y)),\n            min(self.size[0], math.ceil(box[2] + support_x)),\n            min(self.size[1], math.ceil(box[3] + support_y)),\n        )\n\n    def resize(\n        self,\n        size: tuple[int, int],\n        resample: int | None = None,\n        box: tuple[float, float, float, float] | None = None,\n        reducing_gap: float | None = None,\n    ) -> Image:\n        \"\"\"\n        Returns a resized copy of this image.\n\n        :param size: The requested size in pixels, as a 2-tuple:\n           (width, height).\n        :param resample: An optional resampling filter.  This can be\n           one of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`,\n           :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`,\n           :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`.\n           If the image has mode \"1\" or \"P\", it is always set to\n           :py:data:`Resampling.NEAREST`. If the image mode specifies a number\n           of bits, such as \"I;16\", then the default filter is\n           :py:data:`Resampling.NEAREST`. Otherwise, the default filter is\n           :py:data:`Resampling.BICUBIC`. See: :ref:`concept-filters`.\n        :param box: An optional 4-tuple of floats providing\n           the source image region to be scaled.\n           The values must be within (0, 0, width, height) rectangle.\n           If omitted or None, the entire source is used.\n        :param reducing_gap: Apply optimization by resizing the image\n           in two steps. First, reducing the image by integer times\n           using :py:meth:`~PIL.Image.Image.reduce`.\n           Second, resizing using regular resampling. The last step\n           changes size no less than by ``reducing_gap`` times.\n           ``reducing_gap`` may be None (no first step is performed)\n           or should be greater than 1.0. The bigger ``reducing_gap``,\n           the closer the result to the fair resampling.\n           The smaller ``reducing_gap``, the faster resizing.\n           With ``reducing_gap`` greater or equal to 3.0, the result is\n           indistinguishable from fair resampling in most cases.\n           The default value is None (no optimization).\n        :returns: An :py:class:`~PIL.Image.Image` object.\n        \"\"\"\n\n        if resample is None:\n            type_special = \";\" in self.mode\n            resample = Resampling.NEAREST if type_special else Resampling.BICUBIC\n        elif resample not in (\n            Resampling.NEAREST,\n            Resampling.BILINEAR,\n            Resampling.BICUBIC,\n            Resampling.LANCZOS,\n            Resampling.BOX,\n            Resampling.HAMMING,\n        ):\n            msg = f\"Unknown resampling filter ({resample}).\"\n\n            filters = [\n                f\"{filter[1]} ({filter[0]})\"\n                for filter in (\n                    (Resampling.NEAREST, \"Image.Resampling.NEAREST\"),\n                    (Resampling.LANCZOS, \"Image.Resampling.LANCZOS\"),\n                    (Resampling.BILINEAR, \"Image.Resampling.BILINEAR\"),\n                    (Resampling.BICUBIC, \"Image.Resampling.BICUBIC\"),\n                    (Resampling.BOX, \"Image.Resampling.BOX\"),\n                    (Resampling.HAMMING, \"Image.Resampling.HAMMING\"),\n                )\n            ]\n            msg += f\" Use {', '.join(filters[:-1])} or {filters[-1]}\"\n            raise ValueError(msg)\n\n        if reducing_gap is not None and reducing_gap < 1.0:\n            msg = \"reducing_gap must be 1.0 or greater\"\n            raise ValueError(msg)\n\n        self.load()\n        if box is None:\n            box = (0, 0) + self.size\n\n        if self.size == size and box == (0, 0) + self.size:\n            return self.copy()\n\n        if self.mode in (\"1\", \"P\"):\n            resample = Resampling.NEAREST\n\n        if self.mode in [\"LA\", \"RGBA\"] and resample != Resampling.NEAREST:\n            im = self.convert({\"LA\": \"La\", \"RGBA\": \"RGBa\"}[self.mode])\n            im = im.resize(size, resample, box)\n            return im.convert(self.mode)\n\n        self.load()\n\n        if reducing_gap is not None and resample != Resampling.NEAREST:\n            factor_x = int((box[2] - box[0]) / size[0] / reducing_gap) or 1\n            factor_y = int((box[3] - box[1]) / size[1] / reducing_gap) or 1\n            if factor_x > 1 or factor_y > 1:\n                reduce_box = self._get_safe_box(size, resample, box)\n                factor = (factor_x, factor_y)\n                self = (\n                    self.reduce(factor, box=reduce_box)\n                    if callable(self.reduce)\n                    else Image.reduce(self, factor, box=reduce_box)\n                )\n                box = (\n                    (box[0] - reduce_box[0]) / factor_x,\n                    (box[1] - reduce_box[1]) / factor_y,\n                    (box[2] - reduce_box[0]) / factor_x,\n                    (box[3] - reduce_box[1]) / factor_y,\n                )\n\n        return self._new(self.im.resize(size, resample, box))\n\n    def reduce(\n        self,\n        factor: int | tuple[int, int],\n        box: tuple[int, int, int, int] | None = None,\n    ) -> Image:\n        \"\"\"\n        Returns a copy of the image reduced ``factor`` times.\n        If the size of the image is not dividable by ``factor``,\n        the resulting size will be rounded up.\n\n        :param factor: A greater than 0 integer or tuple of two integers\n           for width and height separately.\n        :param box: An optional 4-tuple of ints providing\n           the source image region to be reduced.\n           The values must be within ``(0, 0, width, height)`` rectangle.\n           If omitted or ``None``, the entire source is used.\n        \"\"\"\n        if not isinstance(factor, (list, tuple)):\n            factor = (factor, factor)\n\n        if box is None:\n            box = (0, 0) + self.size\n\n        if factor == (1, 1) and box == (0, 0) + self.size:\n            return self.copy()\n\n        if self.mode in [\"LA\", \"RGBA\"]:\n            im = self.convert({\"LA\": \"La\", \"RGBA\": \"RGBa\"}[self.mode])\n            im = im.reduce(factor, box)\n            return im.convert(self.mode)\n\n        self.load()\n\n        return self._new(self.im.reduce(factor, box))\n\n    def rotate(\n        self,\n        angle: float,\n        resample: Resampling = Resampling.NEAREST,\n        expand: int | bool = False,\n        center: tuple[float, float] | None = None,\n        translate: tuple[int, int] | None = None,\n        fillcolor: float | tuple[float, ...] | str | None = None,\n    ) -> Image:\n        \"\"\"\n        Returns a rotated copy of this image.  This method returns a\n        copy of this image, rotated the given number of degrees counter\n        clockwise around its centre.\n\n        :param angle: In degrees counter clockwise.\n        :param resample: An optional resampling filter.  This can be\n           one of :py:data:`Resampling.NEAREST` (use nearest neighbour),\n           :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2\n           environment), or :py:data:`Resampling.BICUBIC` (cubic spline\n           interpolation in a 4x4 environment). If omitted, or if the image has\n           mode \"1\" or \"P\", it is set to :py:data:`Resampling.NEAREST`.\n           See :ref:`concept-filters`.\n        :param expand: Optional expansion flag.  If true, expands the output\n           image to make it large enough to hold the entire rotated image.\n           If false or omitted, make the output image the same size as the\n           input image.  Note that the expand flag assumes rotation around\n           the center and no translation.\n        :param center: Optional center of rotation (a 2-tuple).  Origin is\n           the upper left corner.  Default is the center of the image.\n        :param translate: An optional post-rotate translation (a 2-tuple).\n        :param fillcolor: An optional color for area outside the rotated image.\n        :returns: An :py:class:`~PIL.Image.Image` object.\n        \"\"\"\n\n        angle = angle % 360.0\n\n        # Fast paths regardless of filter, as long as we're not\n        # translating or changing the center.\n        if not (center or translate):\n            if angle == 0:\n                return self.copy()\n            if angle == 180:\n                return self.transpose(Transpose.ROTATE_180)\n            if angle in (90, 270) and (expand or self.width == self.height):\n                return self.transpose(\n                    Transpose.ROTATE_90 if angle == 90 else Transpose.ROTATE_270\n                )\n\n        # Calculate the affine matrix.  Note that this is the reverse\n        # transformation (from destination image to source) because we\n        # want to interpolate the (discrete) destination pixel from\n        # the local area around the (floating) source pixel.\n\n        # The matrix we actually want (note that it operates from the right):\n        # (1, 0, tx)   (1, 0, cx)   ( cos a, sin a, 0)   (1, 0, -cx)\n        # (0, 1, ty) * (0, 1, cy) * (-sin a, cos a, 0) * (0, 1, -cy)\n        # (0, 0,  1)   (0, 0,  1)   (     0,     0, 1)   (0, 0,   1)\n\n        # The reverse matrix is thus:\n        # (1, 0, cx)   ( cos -a, sin -a, 0)   (1, 0, -cx)   (1, 0, -tx)\n        # (0, 1, cy) * (-sin -a, cos -a, 0) * (0, 1, -cy) * (0, 1, -ty)\n        # (0, 0,  1)   (      0,      0, 1)   (0, 0,   1)   (0, 0,   1)\n\n        # In any case, the final translation may be updated at the end to\n        # compensate for the expand flag.\n\n        w, h = self.size\n\n        if translate is None:\n            post_trans = (0, 0)\n        else:\n            post_trans = translate\n        if center is None:\n            center = (w / 2, h / 2)\n\n        angle = -math.radians(angle)\n        matrix = [\n            round(math.cos(angle), 15),\n            round(math.sin(angle), 15),\n            0.0,\n            round(-math.sin(angle), 15),\n            round(math.cos(angle), 15),\n            0.0,\n        ]\n\n        def transform(x, y, matrix):\n            (a, b, c, d, e, f) = matrix\n            return a * x + b * y + c, d * x + e * y + f\n\n        matrix[2], matrix[5] = transform(\n            -center[0] - post_trans[0], -center[1] - post_trans[1], matrix\n        )\n        matrix[2] += center[0]\n        matrix[5] += center[1]\n\n        if expand:\n            # calculate output size\n            xx = []\n            yy = []\n            for x, y in ((0, 0), (w, 0), (w, h), (0, h)):\n                x, y = transform(x, y, matrix)\n                xx.append(x)\n                yy.append(y)\n            nw = math.ceil(max(xx)) - math.floor(min(xx))\n            nh = math.ceil(max(yy)) - math.floor(min(yy))\n\n            # We multiply a translation matrix from the right.  Because of its\n            # special form, this is the same as taking the image of the\n            # translation vector as new translation vector.\n            matrix[2], matrix[5] = transform(-(nw - w) / 2.0, -(nh - h) / 2.0, matrix)\n            w, h = nw, nh\n\n        return self.transform(\n            (w, h), Transform.AFFINE, matrix, resample, fillcolor=fillcolor\n        )\n\n    def save(\n        self, fp: StrOrBytesPath | IO[bytes], format: str | None = None, **params: Any\n    ) -> None:\n        \"\"\"\n        Saves this image under the given filename.  If no format is\n        specified, the format to use is determined from the filename\n        extension, if possible.\n\n        Keyword options can be used to provide additional instructions\n        to the writer. If a writer doesn't recognise an option, it is\n        silently ignored. The available options are described in the\n        :doc:`image format documentation\n        <../handbook/image-file-formats>` for each writer.\n\n        You can use a file object instead of a filename. In this case,\n        you must always specify the format. The file object must\n        implement the ``seek``, ``tell``, and ``write``\n        methods, and be opened in binary mode.\n\n        :param fp: A filename (string), os.PathLike object or file object.\n        :param format: Optional format override.  If omitted, the\n           format to use is determined from the filename extension.\n           If a file object was used instead of a filename, this\n           parameter should always be used.\n        :param params: Extra parameters to the image writer.\n        :returns: None\n        :exception ValueError: If the output format could not be determined\n           from the file name.  Use the format option to solve this.\n        :exception OSError: If the file could not be written.  The file\n           may have been created, and may contain partial data.\n        \"\"\"\n\n        filename: str | bytes = \"\"\n        open_fp = False\n        if is_path(fp):\n            filename = os.path.realpath(os.fspath(fp))\n            open_fp = True\n        elif fp == sys.stdout:\n            try:\n                fp = sys.stdout.buffer\n            except AttributeError:\n                pass\n        if not filename and hasattr(fp, \"name\") and is_path(fp.name):\n            # only set the name for metadata purposes\n            filename = os.path.realpath(os.fspath(fp.name))\n\n        # may mutate self!\n        self._ensure_mutable()\n\n        save_all = params.pop(\"save_all\", False)\n        self.encoderinfo = params\n        self.encoderconfig: tuple[Any, ...] = ()\n\n        preinit()\n\n        filename_ext = os.path.splitext(filename)[1].lower()\n        ext = filename_ext.decode() if isinstance(filename_ext, bytes) else filename_ext\n\n        if not format:\n            if ext not in EXTENSION:\n                init()\n            try:\n                format = EXTENSION[ext]\n            except KeyError as e:\n                msg = f\"unknown file extension: {ext}\"\n                raise ValueError(msg) from e\n\n        if format.upper() not in SAVE:\n            init()\n        if save_all:\n            save_handler = SAVE_ALL[format.upper()]\n        else:\n            save_handler = SAVE[format.upper()]\n\n        created = False\n        if open_fp:\n            created = not os.path.exists(filename)\n            if params.get(\"append\", False):\n                # Open also for reading (\"+\"), because TIFF save_all\n                # writer needs to go back and edit the written data.\n                fp = builtins.open(filename, \"r+b\")\n            else:\n                fp = builtins.open(filename, \"w+b\")\n        else:\n            fp = cast(IO[bytes], fp)\n\n        try:\n            save_handler(self, fp, filename)\n        except Exception:\n            if open_fp:\n                fp.close()\n            if created:\n                try:\n                    os.remove(filename)\n                except PermissionError:\n                    pass\n            raise\n        if open_fp:\n            fp.close()\n\n    def seek(self, frame: int) -> None:\n        \"\"\"\n        Seeks to the given frame in this sequence file. If you seek\n        beyond the end of the sequence, the method raises an\n        ``EOFError`` exception. When a sequence file is opened, the\n        library automatically seeks to frame 0.\n\n        See :py:meth:`~PIL.Image.Image.tell`.\n\n        If defined, :attr:`~PIL.Image.Image.n_frames` refers to the\n        number of available frames.\n\n        :param frame: Frame number, starting at 0.\n        :exception EOFError: If the call attempts to seek beyond the end\n            of the sequence.\n        \"\"\"\n\n        # overridden by file handlers\n        if frame != 0:\n            msg = \"no more images in file\"\n            raise EOFError(msg)\n\n    def show(self, title: str | None = None) -> None:\n        \"\"\"\n        Displays this image. This method is mainly intended for debugging purposes.\n\n        This method calls :py:func:`PIL.ImageShow.show` internally. You can use\n        :py:func:`PIL.ImageShow.register` to override its default behaviour.\n\n        The image is first saved to a temporary file. By default, it will be in\n        PNG format.\n\n        On Unix, the image is then opened using the **xdg-open**, **display**,\n        **gm**, **eog** or **xv** utility, depending on which one can be found.\n\n        On macOS, the image is opened with the native Preview application.\n\n        On Windows, the image is opened with the standard PNG display utility.\n\n        :param title: Optional title to use for the image window, where possible.\n        \"\"\"\n\n        _show(self, title=title)\n\n    def split(self) -> tuple[Image, ...]:\n        \"\"\"\n        Split this image into individual bands. This method returns a\n        tuple of individual image bands from an image. For example,\n        splitting an \"RGB\" image creates three new images each\n        containing a copy of one of the original bands (red, green,\n        blue).\n\n        If you need only one band, :py:meth:`~PIL.Image.Image.getchannel`\n        method can be more convenient and faster.\n\n        :returns: A tuple containing bands.\n        \"\"\"\n\n        self.load()\n        if self.im.bands == 1:\n            return (self.copy(),)\n        return tuple(map(self._new, self.im.split()))\n\n    def getchannel(self, channel: int | str) -> Image:\n        \"\"\"\n        Returns an image containing a single channel of the source image.\n\n        :param channel: What channel to return. Could be index\n          (0 for \"R\" channel of \"RGB\") or channel name\n          (\"A\" for alpha channel of \"RGBA\").\n        :returns: An image in \"L\" mode.\n\n        .. versionadded:: 4.3.0\n        \"\"\"\n        self.load()\n\n        if isinstance(channel, str):\n            try:\n                channel = self.getbands().index(channel)\n            except ValueError as e:\n                msg = f'The image has no channel \"{channel}\"'\n                raise ValueError(msg) from e\n\n        return self._new(self.im.getband(channel))\n\n    def tell(self) -> int:\n        \"\"\"\n        Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`.\n\n        If defined, :attr:`~PIL.Image.Image.n_frames` refers to the\n        number of available frames.\n\n        :returns: Frame number, starting with 0.\n        \"\"\"\n        return 0\n\n    def thumbnail(\n        self,\n        size: tuple[float, float],\n        resample: Resampling = Resampling.BICUBIC,\n        reducing_gap: float | None = 2.0,\n    ) -> None:\n        \"\"\"\n        Make this image into a thumbnail.  This method modifies the\n        image to contain a thumbnail version of itself, no larger than\n        the given size.  This method calculates an appropriate thumbnail\n        size to preserve the aspect of the image, calls the\n        :py:meth:`~PIL.Image.Image.draft` method to configure the file reader\n        (where applicable), and finally resizes the image.\n\n        Note that this function modifies the :py:class:`~PIL.Image.Image`\n        object in place.  If you need to use the full resolution image as well,\n        apply this method to a :py:meth:`~PIL.Image.Image.copy` of the original\n        image.\n\n        :param size: The requested size in pixels, as a 2-tuple:\n           (width, height).\n        :param resample: Optional resampling filter.  This can be one\n           of :py:data:`Resampling.NEAREST`, :py:data:`Resampling.BOX`,\n           :py:data:`Resampling.BILINEAR`, :py:data:`Resampling.HAMMING`,\n           :py:data:`Resampling.BICUBIC` or :py:data:`Resampling.LANCZOS`.\n           If omitted, it defaults to :py:data:`Resampling.BICUBIC`.\n           (was :py:data:`Resampling.NEAREST` prior to version 2.5.0).\n           See: :ref:`concept-filters`.\n        :param reducing_gap: Apply optimization by resizing the image\n           in two steps. First, reducing the image by integer times\n           using :py:meth:`~PIL.Image.Image.reduce` or\n           :py:meth:`~PIL.Image.Image.draft` for JPEG images.\n           Second, resizing using regular resampling. The last step\n           changes size no less than by ``reducing_gap`` times.\n           ``reducing_gap`` may be None (no first step is performed)\n           or should be greater than 1.0. The bigger ``reducing_gap``,\n           the closer the result to the fair resampling.\n           The smaller ``reducing_gap``, the faster resizing.\n           With ``reducing_gap`` greater or equal to 3.0, the result is\n           indistinguishable from fair resampling in most cases.\n           The default value is 2.0 (very close to fair resampling\n           while still being faster in many cases).\n        :returns: None\n        \"\"\"\n\n        provided_size = tuple(map(math.floor, size))\n\n        def preserve_aspect_ratio() -> tuple[int, int] | None:\n            def round_aspect(number, key):\n                return max(min(math.floor(number), math.ceil(number), key=key), 1)\n\n            x, y = provided_size\n            if x >= self.width and y >= self.height:\n                return None\n\n            aspect = self.width / self.height\n            if x / y >= aspect:\n                x = round_aspect(y * aspect, key=lambda n: abs(aspect - n / y))\n            else:\n                y = round_aspect(\n                    x / aspect, key=lambda n: 0 if n == 0 else abs(aspect - x / n)\n                )\n            return x, y\n\n        box = None\n        final_size: tuple[int, int]\n        if reducing_gap is not None:\n            preserved_size = preserve_aspect_ratio()\n            if preserved_size is None:\n                return\n            final_size = preserved_size\n\n            res = self.draft(\n                None, (int(size[0] * reducing_gap), int(size[1] * reducing_gap))\n            )\n            if res is not None:\n                box = res[1]\n        if box is None:\n            self.load()\n\n            # load() may have changed the size of the image\n            preserved_size = preserve_aspect_ratio()\n            if preserved_size is None:\n                return\n            final_size = preserved_size\n\n        if self.size != final_size:\n            im = self.resize(final_size, resample, box=box, reducing_gap=reducing_gap)\n\n            self.im = im.im\n            self._size = final_size\n            self._mode = self.im.mode\n\n        self.readonly = 0\n        self.pyaccess = None\n\n    # FIXME: the different transform methods need further explanation\n    # instead of bloating the method docs, add a separate chapter.\n    def transform(\n        self,\n        size: tuple[int, int],\n        method: Transform | ImageTransformHandler | SupportsGetData,\n        data: Sequence[Any] | None = None,\n        resample: int = Resampling.NEAREST,\n        fill: int = 1,\n        fillcolor: float | tuple[float, ...] | str | None = None,\n    ) -> Image:\n        \"\"\"\n        Transforms this image.  This method creates a new image with the\n        given size, and the same mode as the original, and copies data\n        to the new image using the given transform.\n\n        :param size: The output size in pixels, as a 2-tuple:\n           (width, height).\n        :param method: The transformation method.  This is one of\n          :py:data:`Transform.EXTENT` (cut out a rectangular subregion),\n          :py:data:`Transform.AFFINE` (affine transform),\n          :py:data:`Transform.PERSPECTIVE` (perspective transform),\n          :py:data:`Transform.QUAD` (map a quadrilateral to a rectangle), or\n          :py:data:`Transform.MESH` (map a number of source quadrilaterals\n          in one operation).\n\n          It may also be an :py:class:`~PIL.Image.ImageTransformHandler`\n          object::\n\n            class Example(Image.ImageTransformHandler):\n                def transform(self, size, data, resample, fill=1):\n                    # Return result\n\n          Implementations of :py:class:`~PIL.Image.ImageTransformHandler`\n          for some of the :py:class:`Transform` methods are provided\n          in :py:mod:`~PIL.ImageTransform`.\n\n          It may also be an object with a ``method.getdata`` method\n          that returns a tuple supplying new ``method`` and ``data`` values::\n\n            class Example:\n                def getdata(self):\n                    method = Image.Transform.EXTENT\n                    data = (0, 0, 100, 100)\n                    return method, data\n        :param data: Extra data to the transformation method.\n        :param resample: Optional resampling filter.  It can be one of\n           :py:data:`Resampling.NEAREST` (use nearest neighbour),\n           :py:data:`Resampling.BILINEAR` (linear interpolation in a 2x2\n           environment), or :py:data:`Resampling.BICUBIC` (cubic spline\n           interpolation in a 4x4 environment). If omitted, or if the image\n           has mode \"1\" or \"P\", it is set to :py:data:`Resampling.NEAREST`.\n           See: :ref:`concept-filters`.\n        :param fill: If ``method`` is an\n          :py:class:`~PIL.Image.ImageTransformHandler` object, this is one of\n          the arguments passed to it. Otherwise, it is unused.\n        :param fillcolor: Optional fill color for the area outside the\n           transform in the output image.\n        :returns: An :py:class:`~PIL.Image.Image` object.\n        \"\"\"\n\n        if self.mode in (\"LA\", \"RGBA\") and resample != Resampling.NEAREST:\n            return (\n                self.convert({\"LA\": \"La\", \"RGBA\": \"RGBa\"}[self.mode])\n                .transform(size, method, data, resample, fill, fillcolor)\n                .convert(self.mode)\n            )\n\n        if isinstance(method, ImageTransformHandler):\n            return method.transform(size, self, resample=resample, fill=fill)\n\n        if hasattr(method, \"getdata\"):\n            # compatibility w. old-style transform objects\n            method, data = method.getdata()\n\n        if data is None:\n            msg = \"missing method data\"\n            raise ValueError(msg)\n\n        im = new(self.mode, size, fillcolor)\n        if self.mode == \"P\" and self.palette:\n            im.palette = self.palette.copy()\n        im.info = self.info.copy()\n        if method == Transform.MESH:\n            # list of quads\n            for box, quad in data:\n                im.__transformer(\n                    box, self, Transform.QUAD, quad, resample, fillcolor is None\n                )\n        else:\n            im.__transformer(\n                (0, 0) + size, self, method, data, resample, fillcolor is None\n            )\n\n        return im\n\n    def __transformer(\n        self, box, image, method, data, resample=Resampling.NEAREST, fill=1\n    ):\n        w = box[2] - box[0]\n        h = box[3] - box[1]\n\n        if method == Transform.AFFINE:\n            data = data[:6]\n\n        elif method == Transform.EXTENT:\n            # convert extent to an affine transform\n            x0, y0, x1, y1 = data\n            xs = (x1 - x0) / w\n            ys = (y1 - y0) / h\n            method = Transform.AFFINE\n            data = (xs, 0, x0, 0, ys, y0)\n\n        elif method == Transform.PERSPECTIVE:\n            data = data[:8]\n\n        elif method == Transform.QUAD:\n            # quadrilateral warp.  data specifies the four corners\n            # given as NW, SW, SE, and NE.\n            nw = data[:2]\n            sw = data[2:4]\n            se = data[4:6]\n            ne = data[6:8]\n            x0, y0 = nw\n            As = 1.0 / w\n            At = 1.0 / h\n            data = (\n                x0,\n                (ne[0] - x0) * As,\n                (sw[0] - x0) * At,\n                (se[0] - sw[0] - ne[0] + x0) * As * At,\n                y0,\n                (ne[1] - y0) * As,\n                (sw[1] - y0) * At,\n                (se[1] - sw[1] - ne[1] + y0) * As * At,\n            )\n\n        else:\n            msg = \"unknown transformation method\"\n            raise ValueError(msg)\n\n        if resample not in (\n            Resampling.NEAREST,\n            Resampling.BILINEAR,\n            Resampling.BICUBIC,\n        ):\n            if resample in (Resampling.BOX, Resampling.HAMMING, Resampling.LANCZOS):\n                msg = {\n                    Resampling.BOX: \"Image.Resampling.BOX\",\n                    Resampling.HAMMING: \"Image.Resampling.HAMMING\",\n                    Resampling.LANCZOS: \"Image.Resampling.LANCZOS\",\n                }[resample] + f\" ({resample}) cannot be used.\"\n            else:\n                msg = f\"Unknown resampling filter ({resample}).\"\n\n            filters = [\n                f\"{filter[1]} ({filter[0]})\"\n                for filter in (\n                    (Resampling.NEAREST, \"Image.Resampling.NEAREST\"),\n                    (Resampling.BILINEAR, \"Image.Resampling.BILINEAR\"),\n                    (Resampling.BICUBIC, \"Image.Resampling.BICUBIC\"),\n                )\n            ]\n            msg += f\" Use {', '.join(filters[:-1])} or {filters[-1]}\"\n            raise ValueError(msg)\n\n        image.load()\n\n        self.load()\n\n        if image.mode in (\"1\", \"P\"):\n            resample = Resampling.NEAREST\n\n        self.im.transform(box, image.im, method, data, resample, fill)\n\n    def transpose(self, method: Transpose) -> Image:\n        \"\"\"\n        Transpose image (flip or rotate in 90 degree steps)\n\n        :param method: One of :py:data:`Transpose.FLIP_LEFT_RIGHT`,\n          :py:data:`Transpose.FLIP_TOP_BOTTOM`, :py:data:`Transpose.ROTATE_90`,\n          :py:data:`Transpose.ROTATE_180`, :py:data:`Transpose.ROTATE_270`,\n          :py:data:`Transpose.TRANSPOSE` or :py:data:`Transpose.TRANSVERSE`.\n        :returns: Returns a flipped or rotated copy of this image.\n        \"\"\"\n\n        self.load()\n        return self._new(self.im.transpose(method))\n\n    def effect_spread(self, distance: int) -> Image:\n        \"\"\"\n        Randomly spread pixels in an image.\n\n        :param distance: Distance to spread pixels.\n        \"\"\"\n        self.load()\n        return self._new(self.im.effect_spread(distance))\n\n    def toqimage(self):\n        \"\"\"Returns a QImage copy of this image\"\"\"\n        from . import ImageQt\n\n        if not ImageQt.qt_is_installed:\n            msg = \"Qt bindings are not installed\"\n            raise ImportError(msg)\n        return ImageQt.toqimage(self)\n\n    def toqpixmap(self):\n        \"\"\"Returns a QPixmap copy of this image\"\"\"\n        from . import ImageQt\n\n        if not ImageQt.qt_is_installed:\n            msg = \"Qt bindings are not installed\"\n            raise ImportError(msg)\n        return ImageQt.toqpixmap(self)\n\n\n# --------------------------------------------------------------------\n# Abstract handlers.\n\n\nclass ImagePointHandler:\n    \"\"\"\n    Used as a mixin by point transforms\n    (for use with :py:meth:`~PIL.Image.Image.point`)\n    \"\"\"\n\n    @abc.abstractmethod\n    def point(self, im: Image) -> Image:\n        pass\n\n\nclass ImageTransformHandler:\n    \"\"\"\n    Used as a mixin by geometry transforms\n    (for use with :py:meth:`~PIL.Image.Image.transform`)\n    \"\"\"\n\n    @abc.abstractmethod\n    def transform(\n        self,\n        size: tuple[int, int],\n        image: Image,\n        **options: Any,\n    ) -> Image:\n        pass\n\n\n# --------------------------------------------------------------------\n# Factories\n\n#\n# Debugging\n\n\ndef _wedge() -> Image:\n    \"\"\"Create grayscale wedge (for debugging only)\"\"\"\n\n    return Image()._new(core.wedge(\"L\"))\n\n\ndef _check_size(size: Any) -> None:\n    \"\"\"\n    Common check to enforce type and sanity check on size tuples\n\n    :param size: Should be a 2 tuple of (width, height)\n    :returns: None, or raises a ValueError\n    \"\"\"\n\n    if not isinstance(size, (list, tuple)):\n        msg = \"Size must be a list or tuple\"\n        raise ValueError(msg)\n    if len(size) != 2:\n        msg = \"Size must be a sequence of length 2\"\n        raise ValueError(msg)\n    if size[0] < 0 or size[1] < 0:\n        msg = \"Width and height must be >= 0\"\n        raise ValueError(msg)\n\n\ndef new(\n    mode: str,\n    size: tuple[int, int] | list[int],\n    color: float | tuple[float, ...] | str | None = 0,\n) -> Image:\n    \"\"\"\n    Creates a new image with the given mode and size.\n\n    :param mode: The mode to use for the new image. See:\n       :ref:`concept-modes`.\n    :param size: A 2-tuple, containing (width, height) in pixels.\n    :param color: What color to use for the image.  Default is black.\n       If given, this should be a single integer or floating point value\n       for single-band modes, and a tuple for multi-band modes (one value\n       per band).  When creating RGB or HSV images, you can also use color\n       strings as supported by the ImageColor module.  If the color is\n       None, the image is not initialised.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    \"\"\"\n\n    if mode in (\"BGR;15\", \"BGR;16\", \"BGR;24\"):\n        deprecate(mode, 12)\n\n    _check_size(size)\n\n    if color is None:\n        # don't initialize\n        return Image()._new(core.new(mode, size))\n\n    if isinstance(color, str):\n        # css3-style specifier\n\n        from . import ImageColor\n\n        color = ImageColor.getcolor(color, mode)\n\n    im = Image()\n    if (\n        mode == \"P\"\n        and isinstance(color, (list, tuple))\n        and all(isinstance(i, int) for i in color)\n    ):\n        color_ints: tuple[int, ...] = cast(Tuple[int, ...], tuple(color))\n        if len(color_ints) == 3 or len(color_ints) == 4:\n            # RGB or RGBA value for a P image\n            from . import ImagePalette\n\n            im.palette = ImagePalette.ImagePalette()\n            color = im.palette.getcolor(color_ints)\n    return im._new(core.fill(mode, size, color))\n\n\ndef frombytes(\n    mode: str,\n    size: tuple[int, int],\n    data: bytes | bytearray,\n    decoder_name: str = \"raw\",\n    *args: Any,\n) -> Image:\n    \"\"\"\n    Creates a copy of an image memory from pixel data in a buffer.\n\n    In its simplest form, this function takes three arguments\n    (mode, size, and unpacked pixel data).\n\n    You can also use any pixel decoder supported by PIL. For more\n    information on available decoders, see the section\n    :ref:`Writing Your Own File Codec <file-codecs>`.\n\n    Note that this function decodes pixel data only, not entire images.\n    If you have an entire image in a string, wrap it in a\n    :py:class:`~io.BytesIO` object, and use :py:func:`~PIL.Image.open` to load\n    it.\n\n    :param mode: The image mode. See: :ref:`concept-modes`.\n    :param size: The image size.\n    :param data: A byte buffer containing raw data for the given mode.\n    :param decoder_name: What decoder to use.\n    :param args: Additional parameters for the given decoder.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    \"\"\"\n\n    _check_size(size)\n\n    im = new(mode, size)\n    if im.width != 0 and im.height != 0:\n        decoder_args: Any = args\n        if len(decoder_args) == 1 and isinstance(decoder_args[0], tuple):\n            # may pass tuple instead of argument list\n            decoder_args = decoder_args[0]\n\n        if decoder_name == \"raw\" and decoder_args == ():\n            decoder_args = mode\n\n        im.frombytes(data, decoder_name, decoder_args)\n    return im\n\n\ndef frombuffer(\n    mode: str, size: tuple[int, int], data, decoder_name: str = \"raw\", *args: Any\n) -> Image:\n    \"\"\"\n    Creates an image memory referencing pixel data in a byte buffer.\n\n    This function is similar to :py:func:`~PIL.Image.frombytes`, but uses data\n    in the byte buffer, where possible.  This means that changes to the\n    original buffer object are reflected in this image).  Not all modes can\n    share memory; supported modes include \"L\", \"RGBX\", \"RGBA\", and \"CMYK\".\n\n    Note that this function decodes pixel data only, not entire images.\n    If you have an entire image file in a string, wrap it in a\n    :py:class:`~io.BytesIO` object, and use :py:func:`~PIL.Image.open` to load it.\n\n    The default parameters used for the \"raw\" decoder differs from that used for\n    :py:func:`~PIL.Image.frombytes`. This is a bug, and will probably be fixed in a\n    future release. The current release issues a warning if you do this; to disable\n    the warning, you should provide the full set of parameters. See below for details.\n\n    :param mode: The image mode. See: :ref:`concept-modes`.\n    :param size: The image size.\n    :param data: A bytes or other buffer object containing raw\n        data for the given mode.\n    :param decoder_name: What decoder to use.\n    :param args: Additional parameters for the given decoder.  For the\n        default encoder (\"raw\"), it's recommended that you provide the\n        full set of parameters::\n\n            frombuffer(mode, size, data, \"raw\", mode, 0, 1)\n\n    :returns: An :py:class:`~PIL.Image.Image` object.\n\n    .. versionadded:: 1.1.4\n    \"\"\"\n\n    _check_size(size)\n\n    # may pass tuple instead of argument list\n    if len(args) == 1 and isinstance(args[0], tuple):\n        args = args[0]\n\n    if decoder_name == \"raw\":\n        if args == ():\n            args = mode, 0, 1\n        if args[0] in _MAPMODES:\n            im = new(mode, (0, 0))\n            im = im._new(core.map_buffer(data, size, decoder_name, 0, args))\n            if mode == \"P\":\n                from . import ImagePalette\n\n                im.palette = ImagePalette.ImagePalette(\"RGB\", im.im.getpalette(\"RGB\"))\n            im.readonly = 1\n            return im\n\n    return frombytes(mode, size, data, decoder_name, args)\n\n\nclass SupportsArrayInterface(Protocol):\n    \"\"\"\n    An object that has an ``__array_interface__`` dictionary.\n    \"\"\"\n\n    @property\n    def __array_interface__(self) -> dict[str, Any]:\n        raise NotImplementedError()\n\n\ndef fromarray(obj: SupportsArrayInterface, mode: str | None = None) -> Image:\n    \"\"\"\n    Creates an image memory from an object exporting the array interface\n    (using the buffer protocol)::\n\n      from PIL import Image\n      import numpy as np\n      a = np.zeros((5, 5))\n      im = Image.fromarray(a)\n\n    If ``obj`` is not contiguous, then the ``tobytes`` method is called\n    and :py:func:`~PIL.Image.frombuffer` is used.\n\n    In the case of NumPy, be aware that Pillow modes do not always correspond\n    to NumPy dtypes. Pillow modes only offer 1-bit pixels, 8-bit pixels,\n    32-bit signed integer pixels, and 32-bit floating point pixels.\n\n    Pillow images can also be converted to arrays::\n\n      from PIL import Image\n      import numpy as np\n      im = Image.open(\"hopper.jpg\")\n      a = np.asarray(im)\n\n    When converting Pillow images to arrays however, only pixel values are\n    transferred. This means that P and PA mode images will lose their palette.\n\n    :param obj: Object with array interface\n    :param mode: Optional mode to use when reading ``obj``. Will be determined from\n      type if ``None``.\n\n      This will not be used to convert the data after reading, but will be used to\n      change how the data is read::\n\n        from PIL import Image\n        import numpy as np\n        a = np.full((1, 1), 300)\n        im = Image.fromarray(a, mode=\"L\")\n        im.getpixel((0, 0))  # 44\n        im = Image.fromarray(a, mode=\"RGB\")\n        im.getpixel((0, 0))  # (44, 1, 0)\n\n      See: :ref:`concept-modes` for general information about modes.\n    :returns: An image object.\n\n    .. versionadded:: 1.1.6\n    \"\"\"\n    arr = obj.__array_interface__\n    shape = arr[\"shape\"]\n    ndim = len(shape)\n    strides = arr.get(\"strides\", None)\n    if mode is None:\n        try:\n            typekey = (1, 1) + shape[2:], arr[\"typestr\"]\n        except KeyError as e:\n            msg = \"Cannot handle this data type\"\n            raise TypeError(msg) from e\n        try:\n            mode, rawmode = _fromarray_typemap[typekey]\n        except KeyError as e:\n            typekey_shape, typestr = typekey\n            msg = f\"Cannot handle this data type: {typekey_shape}, {typestr}\"\n            raise TypeError(msg) from e\n    else:\n        rawmode = mode\n    if mode in [\"1\", \"L\", \"I\", \"P\", \"F\"]:\n        ndmax = 2\n    elif mode == \"RGB\":\n        ndmax = 3\n    else:\n        ndmax = 4\n    if ndim > ndmax:\n        msg = f\"Too many dimensions: {ndim} > {ndmax}.\"\n        raise ValueError(msg)\n\n    size = 1 if ndim == 1 else shape[1], shape[0]\n    if strides is not None:\n        if hasattr(obj, \"tobytes\"):\n            obj = obj.tobytes()\n        elif hasattr(obj, \"tostring\"):\n            obj = obj.tostring()\n        else:\n            msg = \"'strides' requires either tobytes() or tostring()\"\n            raise ValueError(msg)\n\n    return frombuffer(mode, size, obj, \"raw\", rawmode, 0, 1)\n\n\ndef fromqimage(im):\n    \"\"\"Creates an image instance from a QImage image\"\"\"\n    from . import ImageQt\n\n    if not ImageQt.qt_is_installed:\n        msg = \"Qt bindings are not installed\"\n        raise ImportError(msg)\n    return ImageQt.fromqimage(im)\n\n\ndef fromqpixmap(im):\n    \"\"\"Creates an image instance from a QPixmap image\"\"\"\n    from . import ImageQt\n\n    if not ImageQt.qt_is_installed:\n        msg = \"Qt bindings are not installed\"\n        raise ImportError(msg)\n    return ImageQt.fromqpixmap(im)\n\n\n_fromarray_typemap = {\n    # (shape, typestr) => mode, rawmode\n    # first two members of shape are set to one\n    ((1, 1), \"|b1\"): (\"1\", \"1;8\"),\n    ((1, 1), \"|u1\"): (\"L\", \"L\"),\n    ((1, 1), \"|i1\"): (\"I\", \"I;8\"),\n    ((1, 1), \"<u2\"): (\"I\", \"I;16\"),\n    ((1, 1), \">u2\"): (\"I\", \"I;16B\"),\n    ((1, 1), \"<i2\"): (\"I\", \"I;16S\"),\n    ((1, 1), \">i2\"): (\"I\", \"I;16BS\"),\n    ((1, 1), \"<u4\"): (\"I\", \"I;32\"),\n    ((1, 1), \">u4\"): (\"I\", \"I;32B\"),\n    ((1, 1), \"<i4\"): (\"I\", \"I;32S\"),\n    ((1, 1), \">i4\"): (\"I\", \"I;32BS\"),\n    ((1, 1), \"<f4\"): (\"F\", \"F;32F\"),\n    ((1, 1), \">f4\"): (\"F\", \"F;32BF\"),\n    ((1, 1), \"<f8\"): (\"F\", \"F;64F\"),\n    ((1, 1), \">f8\"): (\"F\", \"F;64BF\"),\n    ((1, 1, 2), \"|u1\"): (\"LA\", \"LA\"),\n    ((1, 1, 3), \"|u1\"): (\"RGB\", \"RGB\"),\n    ((1, 1, 4), \"|u1\"): (\"RGBA\", \"RGBA\"),\n    # shortcuts:\n    ((1, 1), f\"{_ENDIAN}i4\"): (\"I\", \"I\"),\n    ((1, 1), f\"{_ENDIAN}f4\"): (\"F\", \"F\"),\n}\n\n\ndef _decompression_bomb_check(size: tuple[int, int]) -> None:\n    if MAX_IMAGE_PIXELS is None:\n        return\n\n    pixels = max(1, size[0]) * max(1, size[1])\n\n    if pixels > 2 * MAX_IMAGE_PIXELS:\n        msg = (\n            f\"Image size ({pixels} pixels) exceeds limit of {2 * MAX_IMAGE_PIXELS} \"\n            \"pixels, could be decompression bomb DOS attack.\"\n        )\n        raise DecompressionBombError(msg)\n\n    if pixels > MAX_IMAGE_PIXELS:\n        warnings.warn(\n            f\"Image size ({pixels} pixels) exceeds limit of {MAX_IMAGE_PIXELS} pixels, \"\n            \"could be decompression bomb DOS attack.\",\n            DecompressionBombWarning,\n        )\n\n\ndef open(\n    fp: StrOrBytesPath | IO[bytes],\n    mode: Literal[\"r\"] = \"r\",\n    formats: list[str] | tuple[str, ...] | None = None,\n) -> ImageFile.ImageFile:\n    \"\"\"\n    Opens and identifies the given image file.\n\n    This is a lazy operation; this function identifies the file, but\n    the file remains open and the actual image data is not read from\n    the file until you try to process the data (or call the\n    :py:meth:`~PIL.Image.Image.load` method).  See\n    :py:func:`~PIL.Image.new`. See :ref:`file-handling`.\n\n    :param fp: A filename (string), os.PathLike object or a file object.\n       The file object must implement ``file.read``,\n       ``file.seek``, and ``file.tell`` methods,\n       and be opened in binary mode. The file object will also seek to zero\n       before reading.\n    :param mode: The mode.  If given, this argument must be \"r\".\n    :param formats: A list or tuple of formats to attempt to load the file in.\n       This can be used to restrict the set of formats checked.\n       Pass ``None`` to try all supported formats. You can print the set of\n       available formats by running ``python3 -m PIL`` or using\n       the :py:func:`PIL.features.pilinfo` function.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    :exception FileNotFoundError: If the file cannot be found.\n    :exception PIL.UnidentifiedImageError: If the image cannot be opened and\n       identified.\n    :exception ValueError: If the ``mode`` is not \"r\", or if a ``StringIO``\n       instance is used for ``fp``.\n    :exception TypeError: If ``formats`` is not ``None``, a list or a tuple.\n    \"\"\"\n\n    if mode != \"r\":\n        msg = f\"bad mode {repr(mode)}\"  # type: ignore[unreachable]\n        raise ValueError(msg)\n    elif isinstance(fp, io.StringIO):\n        msg = (  # type: ignore[unreachable]\n            \"StringIO cannot be used to open an image. \"\n            \"Binary data must be used instead.\"\n        )\n        raise ValueError(msg)\n\n    if formats is None:\n        formats = ID\n    elif not isinstance(formats, (list, tuple)):\n        msg = \"formats must be a list or tuple\"  # type: ignore[unreachable]\n        raise TypeError(msg)\n\n    exclusive_fp = False\n    filename: str | bytes = \"\"\n    if is_path(fp):\n        filename = os.path.realpath(os.fspath(fp))\n\n    if filename:\n        fp = builtins.open(filename, \"rb\")\n        exclusive_fp = True\n    else:\n        fp = cast(IO[bytes], fp)\n\n    try:\n        fp.seek(0)\n    except (AttributeError, io.UnsupportedOperation):\n        fp = io.BytesIO(fp.read())\n        exclusive_fp = True\n\n    prefix = fp.read(16)\n\n    preinit()\n\n    warning_messages: list[str] = []\n\n    def _open_core(\n        fp: IO[bytes],\n        filename: str | bytes,\n        prefix: bytes,\n        formats: list[str] | tuple[str, ...],\n    ) -> ImageFile.ImageFile | None:\n        for i in formats:\n            i = i.upper()\n            if i not in OPEN:\n                init()\n            try:\n                factory, accept = OPEN[i]\n                result = not accept or accept(prefix)\n                if isinstance(result, str):\n                    warning_messages.append(result)\n                elif result:\n                    fp.seek(0)\n                    im = factory(fp, filename)\n                    _decompression_bomb_check(im.size)\n                    return im\n            except (SyntaxError, IndexError, TypeError, struct.error) as e:\n                if WARN_POSSIBLE_FORMATS:\n                    warning_messages.append(i + \" opening failed. \" + str(e))\n            except BaseException:\n                if exclusive_fp:\n                    fp.close()\n                raise\n        return None\n\n    im = _open_core(fp, filename, prefix, formats)\n\n    if im is None and formats is ID:\n        checked_formats = ID.copy()\n        if init():\n            im = _open_core(\n                fp,\n                filename,\n                prefix,\n                tuple(format for format in formats if format not in checked_formats),\n            )\n\n    if im:\n        im._exclusive_fp = exclusive_fp\n        return im\n\n    if exclusive_fp:\n        fp.close()\n    for message in warning_messages:\n        warnings.warn(message)\n    msg = \"cannot identify image file %r\" % (filename if filename else fp)\n    raise UnidentifiedImageError(msg)\n\n\n#\n# Image processing.\n\n\ndef alpha_composite(im1: Image, im2: Image) -> Image:\n    \"\"\"\n    Alpha composite im2 over im1.\n\n    :param im1: The first image. Must have mode RGBA.\n    :param im2: The second image.  Must have mode RGBA, and the same size as\n       the first image.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    \"\"\"\n\n    im1.load()\n    im2.load()\n    return im1._new(core.alpha_composite(im1.im, im2.im))\n\n\ndef blend(im1: Image, im2: Image, alpha: float) -> Image:\n    \"\"\"\n    Creates a new image by interpolating between two input images, using\n    a constant alpha::\n\n        out = image1 * (1.0 - alpha) + image2 * alpha\n\n    :param im1: The first image.\n    :param im2: The second image.  Must have the same mode and size as\n       the first image.\n    :param alpha: The interpolation alpha factor.  If alpha is 0.0, a\n       copy of the first image is returned. If alpha is 1.0, a copy of\n       the second image is returned. There are no restrictions on the\n       alpha value. If necessary, the result is clipped to fit into\n       the allowed output range.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    \"\"\"\n\n    im1.load()\n    im2.load()\n    return im1._new(core.blend(im1.im, im2.im, alpha))\n\n\ndef composite(image1: Image, image2: Image, mask: Image) -> Image:\n    \"\"\"\n    Create composite image by blending images using a transparency mask.\n\n    :param image1: The first image.\n    :param image2: The second image.  Must have the same mode and\n       size as the first image.\n    :param mask: A mask image.  This image can have mode\n       \"1\", \"L\", or \"RGBA\", and must have the same size as the\n       other two images.\n    \"\"\"\n\n    image = image2.copy()\n    image.paste(image1, None, mask)\n    return image\n\n\ndef eval(image, *args):\n    \"\"\"\n    Applies the function (which should take one argument) to each pixel\n    in the given image. If the image has more than one band, the same\n    function is applied to each band. Note that the function is\n    evaluated once for each possible pixel value, so you cannot use\n    random components or other generators.\n\n    :param image: The input image.\n    :param function: A function object, taking one integer argument.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    \"\"\"\n\n    return image.point(args[0])\n\n\ndef merge(mode: str, bands: Sequence[Image]) -> Image:\n    \"\"\"\n    Merge a set of single band images into a new multiband image.\n\n    :param mode: The mode to use for the output image. See:\n        :ref:`concept-modes`.\n    :param bands: A sequence containing one single-band image for\n        each band in the output image.  All bands must have the\n        same size.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    \"\"\"\n\n    if getmodebands(mode) != len(bands) or \"*\" in mode:\n        msg = \"wrong number of bands\"\n        raise ValueError(msg)\n    for band in bands[1:]:\n        if band.mode != getmodetype(mode):\n            msg = \"mode mismatch\"\n            raise ValueError(msg)\n        if band.size != bands[0].size:\n            msg = \"size mismatch\"\n            raise ValueError(msg)\n    for band in bands:\n        band.load()\n    return bands[0]._new(core.merge(mode, *[b.im for b in bands]))\n\n\n# --------------------------------------------------------------------\n# Plugin registry\n\n\ndef register_open(\n    id: str,\n    factory: Callable[[IO[bytes], str | bytes], ImageFile.ImageFile],\n    accept: Callable[[bytes], bool | str] | None = None,\n) -> None:\n    \"\"\"\n    Register an image file plugin.  This function should not be used\n    in application code.\n\n    :param id: An image format identifier.\n    :param factory: An image file factory method.\n    :param accept: An optional function that can be used to quickly\n       reject images having another format.\n    \"\"\"\n    id = id.upper()\n    if id not in ID:\n        ID.append(id)\n    OPEN[id] = factory, accept\n\n\ndef register_mime(id: str, mimetype: str) -> None:\n    \"\"\"\n    Registers an image MIME type by populating ``Image.MIME``. This function\n    should not be used in application code.\n\n    ``Image.MIME`` provides a mapping from image format identifiers to mime\n    formats, but :py:meth:`~PIL.ImageFile.ImageFile.get_format_mimetype` can\n    provide a different result for specific images.\n\n    :param id: An image format identifier.\n    :param mimetype: The image MIME type for this format.\n    \"\"\"\n    MIME[id.upper()] = mimetype\n\n\ndef register_save(\n    id: str, driver: Callable[[Image, IO[bytes], str | bytes], None]\n) -> None:\n    \"\"\"\n    Registers an image save function.  This function should not be\n    used in application code.\n\n    :param id: An image format identifier.\n    :param driver: A function to save images in this format.\n    \"\"\"\n    SAVE[id.upper()] = driver\n\n\ndef register_save_all(\n    id: str, driver: Callable[[Image, IO[bytes], str | bytes], None]\n) -> None:\n    \"\"\"\n    Registers an image function to save all the frames\n    of a multiframe format.  This function should not be\n    used in application code.\n\n    :param id: An image format identifier.\n    :param driver: A function to save images in this format.\n    \"\"\"\n    SAVE_ALL[id.upper()] = driver\n\n\ndef register_extension(id: str, extension: str) -> None:\n    \"\"\"\n    Registers an image extension.  This function should not be\n    used in application code.\n\n    :param id: An image format identifier.\n    :param extension: An extension used for this format.\n    \"\"\"\n    EXTENSION[extension.lower()] = id.upper()\n\n\ndef register_extensions(id: str, extensions: list[str]) -> None:\n    \"\"\"\n    Registers image extensions.  This function should not be\n    used in application code.\n\n    :param id: An image format identifier.\n    :param extensions: A list of extensions used for this format.\n    \"\"\"\n    for extension in extensions:\n        register_extension(id, extension)\n\n\ndef registered_extensions() -> dict[str, str]:\n    \"\"\"\n    Returns a dictionary containing all file extensions belonging\n    to registered plugins\n    \"\"\"\n    init()\n    return EXTENSION\n\n\ndef register_decoder(name: str, decoder: type[ImageFile.PyDecoder]) -> None:\n    \"\"\"\n    Registers an image decoder.  This function should not be\n    used in application code.\n\n    :param name: The name of the decoder\n    :param decoder: An ImageFile.PyDecoder object\n\n    .. versionadded:: 4.1.0\n    \"\"\"\n    DECODERS[name] = decoder\n\n\ndef register_encoder(name: str, encoder: type[ImageFile.PyEncoder]) -> None:\n    \"\"\"\n    Registers an image encoder.  This function should not be\n    used in application code.\n\n    :param name: The name of the encoder\n    :param encoder: An ImageFile.PyEncoder object\n\n    .. versionadded:: 4.1.0\n    \"\"\"\n    ENCODERS[name] = encoder\n\n\n# --------------------------------------------------------------------\n# Simple display support.\n\n\ndef _show(image: Image, **options: Any) -> None:\n    from . import ImageShow\n\n    ImageShow.show(image, **options)\n\n\n# --------------------------------------------------------------------\n# Effects\n\n\ndef effect_mandelbrot(\n    size: tuple[int, int], extent: tuple[float, float, float, float], quality: int\n) -> Image:\n    \"\"\"\n    Generate a Mandelbrot set covering the given extent.\n\n    :param size: The requested size in pixels, as a 2-tuple:\n       (width, height).\n    :param extent: The extent to cover, as a 4-tuple:\n       (x0, y0, x1, y1).\n    :param quality: Quality.\n    \"\"\"\n    return Image()._new(core.effect_mandelbrot(size, extent, quality))\n\n\ndef effect_noise(size: tuple[int, int], sigma: float) -> Image:\n    \"\"\"\n    Generate Gaussian noise centered around 128.\n\n    :param size: The requested size in pixels, as a 2-tuple:\n       (width, height).\n    :param sigma: Standard deviation of noise.\n    \"\"\"\n    return Image()._new(core.effect_noise(size, sigma))\n\n\ndef linear_gradient(mode: str) -> Image:\n    \"\"\"\n    Generate 256x256 linear gradient from black to white, top to bottom.\n\n    :param mode: Input mode.\n    \"\"\"\n    return Image()._new(core.linear_gradient(mode))\n\n\ndef radial_gradient(mode: str) -> Image:\n    \"\"\"\n    Generate 256x256 radial gradient from black to white, centre to edge.\n\n    :param mode: Input mode.\n    \"\"\"\n    return Image()._new(core.radial_gradient(mode))\n\n\n# --------------------------------------------------------------------\n# Resources\n\n\ndef _apply_env_variables(env: dict[str, str] | None = None) -> None:\n    env_dict = env if env is not None else os.environ\n\n    for var_name, setter in [\n        (\"PILLOW_ALIGNMENT\", core.set_alignment),\n        (\"PILLOW_BLOCK_SIZE\", core.set_block_size),\n        (\"PILLOW_BLOCKS_MAX\", core.set_blocks_max),\n    ]:\n        if var_name not in env_dict:\n            continue\n\n        var = env_dict[var_name].lower()\n\n        units = 1\n        for postfix, mul in [(\"k\", 1024), (\"m\", 1024 * 1024)]:\n            if var.endswith(postfix):\n                units = mul\n                var = var[: -len(postfix)]\n\n        try:\n            var_int = int(var) * units\n        except ValueError:\n            warnings.warn(f\"{var_name} is not int\")\n            continue\n\n        try:\n            setter(var_int)\n        except ValueError as e:\n            warnings.warn(f\"{var_name}: {e}\")\n\n\n_apply_env_variables()\natexit.register(core.clear_cache)\n\n\nif TYPE_CHECKING:\n    _ExifBase = MutableMapping[int, Any]\nelse:\n    _ExifBase = MutableMapping\n\n\nclass Exif(_ExifBase):\n    \"\"\"\n    This class provides read and write access to EXIF image data::\n\n      from PIL import Image\n      im = Image.open(\"exif.png\")\n      exif = im.getexif()  # Returns an instance of this class\n\n    Information can be read and written, iterated over or deleted::\n\n      print(exif[274])  # 1\n      exif[274] = 2\n      for k, v in exif.items():\n        print(\"Tag\", k, \"Value\", v)  # Tag 274 Value 2\n      del exif[274]\n\n    To access information beyond IFD0, :py:meth:`~PIL.Image.Exif.get_ifd`\n    returns a dictionary::\n\n      from PIL import ExifTags\n      im = Image.open(\"exif_gps.jpg\")\n      exif = im.getexif()\n      gps_ifd = exif.get_ifd(ExifTags.IFD.GPSInfo)\n      print(gps_ifd)\n\n    Other IFDs include ``ExifTags.IFD.Exif``, ``ExifTags.IFD.Makernote``,\n    ``ExifTags.IFD.Interop`` and ``ExifTags.IFD.IFD1``.\n\n    :py:mod:`~PIL.ExifTags` also has enum classes to provide names for data::\n\n      print(exif[ExifTags.Base.Software])  # PIL\n      print(gps_ifd[ExifTags.GPS.GPSDateStamp])  # 1999:99:99 99:99:99\n    \"\"\"\n\n    endian = None\n    bigtiff = False\n    _loaded = False\n\n    def __init__(self):\n        self._data = {}\n        self._hidden_data = {}\n        self._ifds = {}\n        self._info = None\n        self._loaded_exif = None\n\n    def _fixup(self, value):\n        try:\n            if len(value) == 1 and isinstance(value, tuple):\n                return value[0]\n        except Exception:\n            pass\n        return value\n\n    def _fixup_dict(self, src_dict):\n        # Helper function\n        # returns a dict with any single item tuples/lists as individual values\n        return {k: self._fixup(v) for k, v in src_dict.items()}\n\n    def _get_ifd_dict(self, offset, group=None):\n        try:\n            # an offset pointer to the location of the nested embedded IFD.\n            # It should be a long, but may be corrupted.\n            self.fp.seek(offset)\n        except (KeyError, TypeError):\n            pass\n        else:\n            from . import TiffImagePlugin\n\n            info = TiffImagePlugin.ImageFileDirectory_v2(self.head, group=group)\n            info.load(self.fp)\n            return self._fixup_dict(info)\n\n    def _get_head(self):\n        version = b\"\\x2B\" if self.bigtiff else b\"\\x2A\"\n        if self.endian == \"<\":\n            head = b\"II\" + version + b\"\\x00\" + o32le(8)\n        else:\n            head = b\"MM\\x00\" + version + o32be(8)\n        if self.bigtiff:\n            head += o32le(8) if self.endian == \"<\" else o32be(8)\n            head += b\"\\x00\\x00\\x00\\x00\"\n        return head\n\n    def load(self, data):\n        # Extract EXIF information.  This is highly experimental,\n        # and is likely to be replaced with something better in a future\n        # version.\n\n        # The EXIF record consists of a TIFF file embedded in a JPEG\n        # application marker (!).\n        if data == self._loaded_exif:\n            return\n        self._loaded_exif = data\n        self._data.clear()\n        self._hidden_data.clear()\n        self._ifds.clear()\n        if data and data.startswith(b\"Exif\\x00\\x00\"):\n            data = data[6:]\n        if not data:\n            self._info = None\n            return\n\n        self.fp = io.BytesIO(data)\n        self.head = self.fp.read(8)\n        # process dictionary\n        from . import TiffImagePlugin\n\n        self._info = TiffImagePlugin.ImageFileDirectory_v2(self.head)\n        self.endian = self._info._endian\n        self.fp.seek(self._info.next)\n        self._info.load(self.fp)\n\n    def load_from_fp(self, fp, offset=None):\n        self._loaded_exif = None\n        self._data.clear()\n        self._hidden_data.clear()\n        self._ifds.clear()\n\n        # process dictionary\n        from . import TiffImagePlugin\n\n        self.fp = fp\n        if offset is not None:\n            self.head = self._get_head()\n        else:\n            self.head = self.fp.read(8)\n        self._info = TiffImagePlugin.ImageFileDirectory_v2(self.head)\n        if self.endian is None:\n            self.endian = self._info._endian\n        if offset is None:\n            offset = self._info.next\n        self.fp.tell()\n        self.fp.seek(offset)\n        self._info.load(self.fp)\n\n    def _get_merged_dict(self):\n        merged_dict = dict(self)\n\n        # get EXIF extension\n        if ExifTags.IFD.Exif in self:\n            ifd = self._get_ifd_dict(self[ExifTags.IFD.Exif], ExifTags.IFD.Exif)\n            if ifd:\n                merged_dict.update(ifd)\n\n        # GPS\n        if ExifTags.IFD.GPSInfo in self:\n            merged_dict[ExifTags.IFD.GPSInfo] = self._get_ifd_dict(\n                self[ExifTags.IFD.GPSInfo], ExifTags.IFD.GPSInfo\n            )\n\n        return merged_dict\n\n    def tobytes(self, offset: int = 8) -> bytes:\n        from . import TiffImagePlugin\n\n        head = self._get_head()\n        ifd = TiffImagePlugin.ImageFileDirectory_v2(ifh=head)\n        for tag, value in self.items():\n            if tag in [\n                ExifTags.IFD.Exif,\n                ExifTags.IFD.GPSInfo,\n            ] and not isinstance(value, dict):\n                value = self.get_ifd(tag)\n                if (\n                    tag == ExifTags.IFD.Exif\n                    and ExifTags.IFD.Interop in value\n                    and not isinstance(value[ExifTags.IFD.Interop], dict)\n                ):\n                    value = value.copy()\n                    value[ExifTags.IFD.Interop] = self.get_ifd(ExifTags.IFD.Interop)\n            ifd[tag] = value\n        return b\"Exif\\x00\\x00\" + head + ifd.tobytes(offset)\n\n    def get_ifd(self, tag):\n        if tag not in self._ifds:\n            if tag == ExifTags.IFD.IFD1:\n                if self._info is not None and self._info.next != 0:\n                    self._ifds[tag] = self._get_ifd_dict(self._info.next)\n            elif tag in [ExifTags.IFD.Exif, ExifTags.IFD.GPSInfo]:\n                offset = self._hidden_data.get(tag, self.get(tag))\n                if offset is not None:\n                    self._ifds[tag] = self._get_ifd_dict(offset, tag)\n            elif tag in [ExifTags.IFD.Interop, ExifTags.IFD.Makernote]:\n                if ExifTags.IFD.Exif not in self._ifds:\n                    self.get_ifd(ExifTags.IFD.Exif)\n                tag_data = self._ifds[ExifTags.IFD.Exif][tag]\n                if tag == ExifTags.IFD.Makernote:\n                    from .TiffImagePlugin import ImageFileDirectory_v2\n\n                    if tag_data[:8] == b\"FUJIFILM\":\n                        ifd_offset = i32le(tag_data, 8)\n                        ifd_data = tag_data[ifd_offset:]\n\n                        makernote = {}\n                        for i in range(0, struct.unpack(\"<H\", ifd_data[:2])[0]):\n                            ifd_tag, typ, count, data = struct.unpack(\n                                \"<HHL4s\", ifd_data[i * 12 + 2 : (i + 1) * 12 + 2]\n                            )\n                            try:\n                                (\n                                    unit_size,\n                                    handler,\n                                ) = ImageFileDirectory_v2._load_dispatch[typ]\n                            except KeyError:\n                                continue\n                            size = count * unit_size\n                            if size > 4:\n                                (offset,) = struct.unpack(\"<L\", data)\n                                data = ifd_data[offset - 12 : offset + size - 12]\n                            else:\n                                data = data[:size]\n\n                            if len(data) != size:\n                                warnings.warn(\n                                    \"Possibly corrupt EXIF MakerNote data.  \"\n                                    f\"Expecting to read {size} bytes but only got \"\n                                    f\"{len(data)}. Skipping tag {ifd_tag}\"\n                                )\n                                continue\n\n                            if not data:\n                                continue\n\n                            makernote[ifd_tag] = handler(\n                                ImageFileDirectory_v2(), data, False\n                            )\n                        self._ifds[tag] = dict(self._fixup_dict(makernote))\n                    elif self.get(0x010F) == \"Nintendo\":\n                        makernote = {}\n                        for i in range(0, struct.unpack(\">H\", tag_data[:2])[0]):\n                            ifd_tag, typ, count, data = struct.unpack(\n                                \">HHL4s\", tag_data[i * 12 + 2 : (i + 1) * 12 + 2]\n                            )\n                            if ifd_tag == 0x1101:\n                                # CameraInfo\n                                (offset,) = struct.unpack(\">L\", data)\n                                self.fp.seek(offset)\n\n                                camerainfo = {\"ModelID\": self.fp.read(4)}\n\n                                self.fp.read(4)\n                                # Seconds since 2000\n                                camerainfo[\"TimeStamp\"] = i32le(self.fp.read(12))\n\n                                self.fp.read(4)\n                                camerainfo[\"InternalSerialNumber\"] = self.fp.read(4)\n\n                                self.fp.read(12)\n                                parallax = self.fp.read(4)\n                                handler = ImageFileDirectory_v2._load_dispatch[\n                                    TiffTags.FLOAT\n                                ][1]\n                                camerainfo[\"Parallax\"] = handler(\n                                    ImageFileDirectory_v2(), parallax, False\n                                )\n\n                                self.fp.read(4)\n                                camerainfo[\"Category\"] = self.fp.read(2)\n\n                                makernote = {0x1101: dict(self._fixup_dict(camerainfo))}\n                        self._ifds[tag] = makernote\n                else:\n                    # Interop\n                    self._ifds[tag] = self._get_ifd_dict(tag_data, tag)\n        ifd = self._ifds.get(tag, {})\n        if tag == ExifTags.IFD.Exif and self._hidden_data:\n            ifd = {\n                k: v\n                for (k, v) in ifd.items()\n                if k not in (ExifTags.IFD.Interop, ExifTags.IFD.Makernote)\n            }\n        return ifd\n\n    def hide_offsets(self) -> None:\n        for tag in (ExifTags.IFD.Exif, ExifTags.IFD.GPSInfo):\n            if tag in self:\n                self._hidden_data[tag] = self[tag]\n                del self[tag]\n\n    def __str__(self) -> str:\n        if self._info is not None:\n            # Load all keys into self._data\n            for tag in self._info:\n                self[tag]\n\n        return str(self._data)\n\n    def __len__(self) -> int:\n        keys = set(self._data)\n        if self._info is not None:\n            keys.update(self._info)\n        return len(keys)\n\n    def __getitem__(self, tag):\n        if self._info is not None and tag not in self._data and tag in self._info:\n            self._data[tag] = self._fixup(self._info[tag])\n            del self._info[tag]\n        return self._data[tag]\n\n    def __contains__(self, tag) -> bool:\n        return tag in self._data or (self._info is not None and tag in self._info)\n\n    def __setitem__(self, tag, value) -> None:\n        if self._info is not None and tag in self._info:\n            del self._info[tag]\n        self._data[tag] = value\n\n    def __delitem__(self, tag: int) -> None:\n        if self._info is not None and tag in self._info:\n            del self._info[tag]\n        else:\n            del self._data[tag]\n\n    def __iter__(self):\n        keys = set(self._data)\n        if self._info is not None:\n            keys.update(self._info)\n        return iter(keys)\n",
            "header": {
                "file": {
                    "path": "src/PIL/Image.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "970437e9a",
                "new_commit_hash": "d41c06523",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/src/PIL/Image.py"
            },
            "plus_file": {
                "path": "b/src/PIL/Image.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 85,
                            "length": 6
                        },
                        "new_range": {
                            "start": 85,
                            "length": 8
                        },
                        "section": "class DecompressionBombError(Exception):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "    pass",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "WARN_POSSIBLE_FORMATS: bool = False",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "# Limit to around a quarter gigabyte for a 24-bit (3 bpp) image",
                                "type": "context"
                            },
                            {
                                "content": "MAX_IMAGE_PIXELS: int | None = int(1024 * 1024 * 1024 // 4 // 3)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "src/PIL/Image.py",
                            "type": "statement",
                            "name": "",
                            "content": "WARN_POSSIBLE_FORMATS: bool = False",
                            "ast_type_str": "AnnAssign",
                            "start_lineno": 88,
                            "end_lineno": 88,
                            "parent": null
                        }
                    ],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 3441,
                            "length": 7
                        },
                        "new_range": {
                            "start": 3443,
                            "length": 7
                        },
                        "section": "def open("
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    preinit()",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    accept_warnings: list[str] = []",
                                "type": "deleted"
                            },
                            {
                                "content": "    warning_messages: list[str] = []",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def _open_core(",
                                "type": "context"
                            },
                            {
                                "content": "        fp: IO[bytes],",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "src/PIL/Image.py",
                            "type": "function",
                            "name": "open",
                            "content": "def open(\n    fp: StrOrBytesPath | IO[bytes],\n    mode: Literal[\"r\"] = \"r\",\n    formats: list[str] | tuple[str, ...] | None = None,\n) -> ImageFile.ImageFile:\n    \"\"\"\n    Opens and identifies the given image file.\n\n    This is a lazy operation; this function identifies the file, but\n    the file remains open and the actual image data is not read from\n    the file until you try to process the data (or call the\n    :py:meth:`~PIL.Image.Image.load` method).  See\n    :py:func:`~PIL.Image.new`. See :ref:`file-handling`.\n\n    :param fp: A filename (string), os.PathLike object or a file object.\n       The file object must implement ``file.read``,\n       ``file.seek``, and ``file.tell`` methods,\n       and be opened in binary mode. The file object will also seek to zero\n       before reading.\n    :param mode: The mode.  If given, this argument must be \"r\".\n    :param formats: A list or tuple of formats to attempt to load the file in.\n       This can be used to restrict the set of formats checked.\n       Pass ``None`` to try all supported formats. You can print the set of\n       available formats by running ``python3 -m PIL`` or using\n       the :py:func:`PIL.features.pilinfo` function.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    :exception FileNotFoundError: If the file cannot be found.\n    :exception PIL.UnidentifiedImageError: If the image cannot be opened and\n       identified.\n    :exception ValueError: If the ``mode`` is not \"r\", or if a ``StringIO``\n       instance is used for ``fp``.\n    :exception TypeError: If ``formats`` is not ``None``, a list or a tuple.\n    \"\"\"\n\n    if mode != \"r\":\n        msg = f\"bad mode {repr(mode)}\"  # type: ignore[unreachable]\n        raise ValueError(msg)\n    elif isinstance(fp, io.StringIO):\n        msg = (  # type: ignore[unreachable]\n            \"StringIO cannot be used to open an image. \"\n            \"Binary data must be used instead.\"\n        )\n        raise ValueError(msg)\n\n    if formats is None:\n        formats = ID\n    elif not isinstance(formats, (list, tuple)):\n        msg = \"formats must be a list or tuple\"  # type: ignore[unreachable]\n        raise TypeError(msg)\n\n    exclusive_fp = False\n    filename: str | bytes = \"\"\n    if is_path(fp):\n        filename = os.path.realpath(os.fspath(fp))\n\n    if filename:\n        fp = builtins.open(filename, \"rb\")\n        exclusive_fp = True\n    else:\n        fp = cast(IO[bytes], fp)\n\n    try:\n        fp.seek(0)\n    except (AttributeError, io.UnsupportedOperation):\n        fp = io.BytesIO(fp.read())\n        exclusive_fp = True\n\n    prefix = fp.read(16)\n\n    preinit()\n\n    accept_warnings: list[str] = []\n\n    def _open_core(\n        fp: IO[bytes],\n        filename: str | bytes,\n        prefix: bytes,\n        formats: list[str] | tuple[str, ...],\n    ) -> ImageFile.ImageFile | None:\n        for i in formats:\n            i = i.upper()\n            if i not in OPEN:\n                init()\n            try:\n                factory, accept = OPEN[i]\n                result = not accept or accept(prefix)\n                if isinstance(result, str):\n                    accept_warnings.append(result)\n                elif result:\n                    fp.seek(0)\n                    im = factory(fp, filename)\n                    _decompression_bomb_check(im.size)\n                    return im\n            except (SyntaxError, IndexError, TypeError, struct.error):\n                # Leave disabled by default, spams the logs with image\n                # opening failures that are entirely expected.\n                # logger.debug(\"\", exc_info=True)\n                continue\n            except BaseException:\n                if exclusive_fp:\n                    fp.close()\n                raise\n        return None\n\n    im = _open_core(fp, filename, prefix, formats)\n\n    if im is None and formats is ID:\n        checked_formats = ID.copy()\n        if init():\n            im = _open_core(\n                fp,\n                filename,\n                prefix,\n                tuple(format for format in formats if format not in checked_formats),\n            )\n\n    if im:\n        im._exclusive_fp = exclusive_fp\n        return im\n\n    if exclusive_fp:\n        fp.close()\n    for message in accept_warnings:\n        warnings.warn(message)\n    msg = \"cannot identify image file %r\" % (filename if filename else fp)\n    raise UnidentifiedImageError(msg)",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 3373,
                            "end_lineno": 3498,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 3457,
                            "length": 17
                        },
                        "new_range": {
                            "start": 3459,
                            "length": 15
                        },
                        "section": "def open("
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "                factory, accept = OPEN[i]",
                                "type": "context"
                            },
                            {
                                "content": "                result = not accept or accept(prefix)",
                                "type": "context"
                            },
                            {
                                "content": "                if isinstance(result, str):",
                                "type": "context"
                            },
                            {
                                "content": "                    accept_warnings.append(result)",
                                "type": "deleted"
                            },
                            {
                                "content": "                    warning_messages.append(result)",
                                "type": "added"
                            },
                            {
                                "content": "                elif result:",
                                "type": "context"
                            },
                            {
                                "content": "                    fp.seek(0)",
                                "type": "context"
                            },
                            {
                                "content": "                    im = factory(fp, filename)",
                                "type": "context"
                            },
                            {
                                "content": "                    _decompression_bomb_check(im.size)",
                                "type": "context"
                            },
                            {
                                "content": "                    return im",
                                "type": "context"
                            },
                            {
                                "content": "            except (SyntaxError, IndexError, TypeError, struct.error):",
                                "type": "deleted"
                            },
                            {
                                "content": "                # Leave disabled by default, spams the logs with image",
                                "type": "deleted"
                            },
                            {
                                "content": "                # opening failures that are entirely expected.",
                                "type": "deleted"
                            },
                            {
                                "content": "                # logger.debug(\"\", exc_info=True)",
                                "type": "deleted"
                            },
                            {
                                "content": "                continue",
                                "type": "deleted"
                            },
                            {
                                "content": "            except (SyntaxError, IndexError, TypeError, struct.error) as e:",
                                "type": "added"
                            },
                            {
                                "content": "                if WARN_POSSIBLE_FORMATS:",
                                "type": "added"
                            },
                            {
                                "content": "                    warning_messages.append(i + \" opening failed. \" + str(e))",
                                "type": "added"
                            },
                            {
                                "content": "            except BaseException:",
                                "type": "context"
                            },
                            {
                                "content": "                if exclusive_fp:",
                                "type": "context"
                            },
                            {
                                "content": "                    fp.close()",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "src/PIL/Image.py",
                            "type": "function",
                            "name": "open",
                            "content": "def open(\n    fp: StrOrBytesPath | IO[bytes],\n    mode: Literal[\"r\"] = \"r\",\n    formats: list[str] | tuple[str, ...] | None = None,\n) -> ImageFile.ImageFile:\n    \"\"\"\n    Opens and identifies the given image file.\n\n    This is a lazy operation; this function identifies the file, but\n    the file remains open and the actual image data is not read from\n    the file until you try to process the data (or call the\n    :py:meth:`~PIL.Image.Image.load` method).  See\n    :py:func:`~PIL.Image.new`. See :ref:`file-handling`.\n\n    :param fp: A filename (string), os.PathLike object or a file object.\n       The file object must implement ``file.read``,\n       ``file.seek``, and ``file.tell`` methods,\n       and be opened in binary mode. The file object will also seek to zero\n       before reading.\n    :param mode: The mode.  If given, this argument must be \"r\".\n    :param formats: A list or tuple of formats to attempt to load the file in.\n       This can be used to restrict the set of formats checked.\n       Pass ``None`` to try all supported formats. You can print the set of\n       available formats by running ``python3 -m PIL`` or using\n       the :py:func:`PIL.features.pilinfo` function.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    :exception FileNotFoundError: If the file cannot be found.\n    :exception PIL.UnidentifiedImageError: If the image cannot be opened and\n       identified.\n    :exception ValueError: If the ``mode`` is not \"r\", or if a ``StringIO``\n       instance is used for ``fp``.\n    :exception TypeError: If ``formats`` is not ``None``, a list or a tuple.\n    \"\"\"\n\n    if mode != \"r\":\n        msg = f\"bad mode {repr(mode)}\"  # type: ignore[unreachable]\n        raise ValueError(msg)\n    elif isinstance(fp, io.StringIO):\n        msg = (  # type: ignore[unreachable]\n            \"StringIO cannot be used to open an image. \"\n            \"Binary data must be used instead.\"\n        )\n        raise ValueError(msg)\n\n    if formats is None:\n        formats = ID\n    elif not isinstance(formats, (list, tuple)):\n        msg = \"formats must be a list or tuple\"  # type: ignore[unreachable]\n        raise TypeError(msg)\n\n    exclusive_fp = False\n    filename: str | bytes = \"\"\n    if is_path(fp):\n        filename = os.path.realpath(os.fspath(fp))\n\n    if filename:\n        fp = builtins.open(filename, \"rb\")\n        exclusive_fp = True\n    else:\n        fp = cast(IO[bytes], fp)\n\n    try:\n        fp.seek(0)\n    except (AttributeError, io.UnsupportedOperation):\n        fp = io.BytesIO(fp.read())\n        exclusive_fp = True\n\n    prefix = fp.read(16)\n\n    preinit()\n\n    accept_warnings: list[str] = []\n\n    def _open_core(\n        fp: IO[bytes],\n        filename: str | bytes,\n        prefix: bytes,\n        formats: list[str] | tuple[str, ...],\n    ) -> ImageFile.ImageFile | None:\n        for i in formats:\n            i = i.upper()\n            if i not in OPEN:\n                init()\n            try:\n                factory, accept = OPEN[i]\n                result = not accept or accept(prefix)\n                if isinstance(result, str):\n                    accept_warnings.append(result)\n                elif result:\n                    fp.seek(0)\n                    im = factory(fp, filename)\n                    _decompression_bomb_check(im.size)\n                    return im\n            except (SyntaxError, IndexError, TypeError, struct.error):\n                # Leave disabled by default, spams the logs with image\n                # opening failures that are entirely expected.\n                # logger.debug(\"\", exc_info=True)\n                continue\n            except BaseException:\n                if exclusive_fp:\n                    fp.close()\n                raise\n        return None\n\n    im = _open_core(fp, filename, prefix, formats)\n\n    if im is None and formats is ID:\n        checked_formats = ID.copy()\n        if init():\n            im = _open_core(\n                fp,\n                filename,\n                prefix,\n                tuple(format for format in formats if format not in checked_formats),\n            )\n\n    if im:\n        im._exclusive_fp = exclusive_fp\n        return im\n\n    if exclusive_fp:\n        fp.close()\n    for message in accept_warnings:\n        warnings.warn(message)\n    msg = \"cannot identify image file %r\" % (filename if filename else fp)\n    raise UnidentifiedImageError(msg)",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 3373,
                            "end_lineno": 3498,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 3492,
                            "length": 7
                        },
                        "new_range": {
                            "start": 3492,
                            "length": 7
                        },
                        "section": "def open("
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    if exclusive_fp:",
                                "type": "context"
                            },
                            {
                                "content": "        fp.close()",
                                "type": "context"
                            },
                            {
                                "content": "    for message in accept_warnings:",
                                "type": "deleted"
                            },
                            {
                                "content": "    for message in warning_messages:",
                                "type": "added"
                            },
                            {
                                "content": "        warnings.warn(message)",
                                "type": "context"
                            },
                            {
                                "content": "    msg = \"cannot identify image file %r\" % (filename if filename else fp)",
                                "type": "context"
                            },
                            {
                                "content": "    raise UnidentifiedImageError(msg)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "src/PIL/Image.py",
                            "type": "function",
                            "name": "open",
                            "content": "def open(\n    fp: StrOrBytesPath | IO[bytes],\n    mode: Literal[\"r\"] = \"r\",\n    formats: list[str] | tuple[str, ...] | None = None,\n) -> ImageFile.ImageFile:\n    \"\"\"\n    Opens and identifies the given image file.\n\n    This is a lazy operation; this function identifies the file, but\n    the file remains open and the actual image data is not read from\n    the file until you try to process the data (or call the\n    :py:meth:`~PIL.Image.Image.load` method).  See\n    :py:func:`~PIL.Image.new`. See :ref:`file-handling`.\n\n    :param fp: A filename (string), os.PathLike object or a file object.\n       The file object must implement ``file.read``,\n       ``file.seek``, and ``file.tell`` methods,\n       and be opened in binary mode. The file object will also seek to zero\n       before reading.\n    :param mode: The mode.  If given, this argument must be \"r\".\n    :param formats: A list or tuple of formats to attempt to load the file in.\n       This can be used to restrict the set of formats checked.\n       Pass ``None`` to try all supported formats. You can print the set of\n       available formats by running ``python3 -m PIL`` or using\n       the :py:func:`PIL.features.pilinfo` function.\n    :returns: An :py:class:`~PIL.Image.Image` object.\n    :exception FileNotFoundError: If the file cannot be found.\n    :exception PIL.UnidentifiedImageError: If the image cannot be opened and\n       identified.\n    :exception ValueError: If the ``mode`` is not \"r\", or if a ``StringIO``\n       instance is used for ``fp``.\n    :exception TypeError: If ``formats`` is not ``None``, a list or a tuple.\n    \"\"\"\n\n    if mode != \"r\":\n        msg = f\"bad mode {repr(mode)}\"  # type: ignore[unreachable]\n        raise ValueError(msg)\n    elif isinstance(fp, io.StringIO):\n        msg = (  # type: ignore[unreachable]\n            \"StringIO cannot be used to open an image. \"\n            \"Binary data must be used instead.\"\n        )\n        raise ValueError(msg)\n\n    if formats is None:\n        formats = ID\n    elif not isinstance(formats, (list, tuple)):\n        msg = \"formats must be a list or tuple\"  # type: ignore[unreachable]\n        raise TypeError(msg)\n\n    exclusive_fp = False\n    filename: str | bytes = \"\"\n    if is_path(fp):\n        filename = os.path.realpath(os.fspath(fp))\n\n    if filename:\n        fp = builtins.open(filename, \"rb\")\n        exclusive_fp = True\n    else:\n        fp = cast(IO[bytes], fp)\n\n    try:\n        fp.seek(0)\n    except (AttributeError, io.UnsupportedOperation):\n        fp = io.BytesIO(fp.read())\n        exclusive_fp = True\n\n    prefix = fp.read(16)\n\n    preinit()\n\n    accept_warnings: list[str] = []\n\n    def _open_core(\n        fp: IO[bytes],\n        filename: str | bytes,\n        prefix: bytes,\n        formats: list[str] | tuple[str, ...],\n    ) -> ImageFile.ImageFile | None:\n        for i in formats:\n            i = i.upper()\n            if i not in OPEN:\n                init()\n            try:\n                factory, accept = OPEN[i]\n                result = not accept or accept(prefix)\n                if isinstance(result, str):\n                    accept_warnings.append(result)\n                elif result:\n                    fp.seek(0)\n                    im = factory(fp, filename)\n                    _decompression_bomb_check(im.size)\n                    return im\n            except (SyntaxError, IndexError, TypeError, struct.error):\n                # Leave disabled by default, spams the logs with image\n                # opening failures that are entirely expected.\n                # logger.debug(\"\", exc_info=True)\n                continue\n            except BaseException:\n                if exclusive_fp:\n                    fp.close()\n                raise\n        return None\n\n    im = _open_core(fp, filename, prefix, formats)\n\n    if im is None and formats is ID:\n        checked_formats = ID.copy()\n        if init():\n            im = _open_core(\n                fp,\n                filename,\n                prefix,\n                tuple(format for format in formats if format not in checked_formats),\n            )\n\n    if im:\n        im._exclusive_fp = exclusive_fp\n        return im\n\n    if exclusive_fp:\n        fp.close()\n    for message in accept_warnings:\n        warnings.warn(message)\n    msg = \"cannot identify image file %r\" % (filename if filename else fp)\n    raise UnidentifiedImageError(msg)",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 3373,
                            "end_lineno": 3498,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "3fdaecb0255abab55d7269fc80b26e532307886c^",
    "new_commit_hash": "3fdaecb0255abab55d7269fc80b26e532307886c",
    "commit_message": "Merge pull request #8063 from radarhere/possible_formats",
    "commit_date": "2024-06-28T00:18:10-06:00",
    "metadata": {}
}
{
    "repo_name": "pillow",
    "new_commit_hash": "3fdaecb0255abab55d7269fc80b26e532307886c",
    "test_file_codes": [
        "from __future__ import annotations\n\nimport io\nimport logging\nimport os\nimport shutil\nimport sys\nimport tempfile\nimport warnings\nfrom pathlib import Path\nfrom types import ModuleType\nfrom typing import IO, Any\n\nimport pytest\n\nfrom PIL import (\n    ExifTags,\n    Image,\n    ImageDraw,\n    ImageFile,\n    ImagePalette,\n    UnidentifiedImageError,\n    features,\n)\n\nfrom .helper import (\n    assert_image_equal,\n    assert_image_equal_tofile,\n    assert_image_similar,\n    assert_image_similar_tofile,\n    assert_not_all_same,\n    hopper,\n    is_big_endian,\n    is_win32,\n    mark_if_feature_version,\n    skip_unless_feature,\n)\n\nElementTree: ModuleType | None\ntry:\n    from defusedxml import ElementTree\nexcept ImportError:\n    ElementTree = None\n\n\n# Deprecation helper\ndef helper_image_new(mode: str, size: tuple[int, int]) -> Image.Image:\n    if mode.startswith(\"BGR;\"):\n        with pytest.warns(DeprecationWarning):\n            return Image.new(mode, size)\n    else:\n        return Image.new(mode, size)\n\n\nclass TestImage:\n    @pytest.mark.parametrize(\"mode\", Image.MODES + [\"BGR;15\", \"BGR;16\", \"BGR;24\"])\n    def test_image_modes_success(self, mode: str) -> None:\n        helper_image_new(mode, (1, 1))\n\n    @pytest.mark.parametrize(\"mode\", (\"\", \"bad\", \"very very long\"))\n    def test_image_modes_fail(self, mode: str) -> None:\n        with pytest.raises(ValueError) as e:\n            Image.new(mode, (1, 1))\n        assert str(e.value) == \"unrecognized image mode\"\n\n    def test_exception_inheritance(self) -> None:\n        assert issubclass(UnidentifiedImageError, OSError)\n\n    def test_sanity(self) -> None:\n        im = Image.new(\"L\", (100, 100))\n        assert repr(im)[:45] == \"<PIL.Image.Image image mode=L size=100x100 at\"\n        assert im.mode == \"L\"\n        assert im.size == (100, 100)\n\n        im = Image.new(\"RGB\", (100, 100))\n        assert repr(im)[:45] == \"<PIL.Image.Image image mode=RGB size=100x100 \"\n        assert im.mode == \"RGB\"\n        assert im.size == (100, 100)\n\n        Image.new(\"L\", (100, 100), None)\n        im2 = Image.new(\"L\", (100, 100), 0)\n        im3 = Image.new(\"L\", (100, 100), \"black\")\n\n        assert im2.getcolors() == [(10000, 0)]\n        assert im3.getcolors() == [(10000, 0)]\n\n        with pytest.raises(ValueError):\n            Image.new(\"X\", (100, 100))\n        with pytest.raises(ValueError):\n            Image.new(\"\", (100, 100))\n        # with pytest.raises(MemoryError):\n        #   Image.new(\"L\", (1000000, 1000000))\n\n    def test_repr_pretty(self) -> None:\n        class Pretty:\n            def text(self, text: str) -> None:\n                self.pretty_output = text\n\n        im = Image.new(\"L\", (100, 100))\n\n        p = Pretty()\n        im._repr_pretty_(p, None)\n        assert p.pretty_output == \"<PIL.Image.Image image mode=L size=100x100>\"\n\n    def test_open_formats(self) -> None:\n        PNGFILE = \"Tests/images/hopper.png\"\n        JPGFILE = \"Tests/images/hopper.jpg\"\n\n        with pytest.raises(TypeError):\n            with Image.open(PNGFILE, formats=123):  # type: ignore[arg-type]\n                pass\n\n        format_list: list[list[str] | tuple[str, ...]] = [\n            [\"JPEG\"],\n            (\"JPEG\",),\n            [\"jpeg\"],\n            [\"Jpeg\"],\n            [\"jPeG\"],\n            [\"JpEg\"],\n        ]\n        for formats in format_list:\n            with pytest.raises(UnidentifiedImageError):\n                with Image.open(PNGFILE, formats=formats):\n                    pass\n\n            with Image.open(JPGFILE, formats=formats) as im:\n                assert im.mode == \"RGB\"\n                assert im.size == (128, 128)\n\n        for file in [PNGFILE, JPGFILE]:\n            with Image.open(file, formats=None) as im:\n                assert im.mode == \"RGB\"\n                assert im.size == (128, 128)\n\n    def test_open_verbose_failure(self, monkeypatch: pytest.MonkeyPatch) -> None:\n        monkeypatch.setattr(Image, \"WARN_POSSIBLE_FORMATS\", True)\n\n        im = io.BytesIO(b\"\")\n        with pytest.warns(UserWarning):\n            with pytest.raises(UnidentifiedImageError):\n                with Image.open(im):\n                    pass\n\n    def test_width_height(self) -> None:\n        im = Image.new(\"RGB\", (1, 2))\n        assert im.width == 1\n        assert im.height == 2\n\n        with pytest.raises(AttributeError):\n            im.size = (3, 4)  # type: ignore[misc]\n\n    def test_set_mode(self) -> None:\n        im = Image.new(\"RGB\", (1, 1))\n\n        with pytest.raises(AttributeError):\n            im.mode = \"P\"  # type: ignore[misc]\n\n    def test_invalid_image(self) -> None:\n        im = io.BytesIO(b\"\")\n        with pytest.raises(UnidentifiedImageError):\n            with Image.open(im):\n                pass\n\n    def test_bad_mode(self) -> None:\n        with pytest.raises(ValueError):\n            with Image.open(\"filename\", \"bad mode\"):  # type: ignore[arg-type]\n                pass\n\n    def test_stringio(self) -> None:\n        with pytest.raises(ValueError):\n            with Image.open(io.StringIO()):  # type: ignore[arg-type]\n                pass\n\n    def test_pathlib(self, tmp_path: Path) -> None:\n        with Image.open(Path(\"Tests/images/multipage-mmap.tiff\")) as im:\n            assert im.mode == \"P\"\n            assert im.size == (10, 10)\n\n        with Image.open(Path(\"Tests/images/hopper.jpg\")) as im:\n            assert im.mode == \"RGB\"\n            assert im.size == (128, 128)\n\n            for ext in (\".jpg\", \".jp2\"):\n                if ext == \".jp2\" and not features.check_codec(\"jpg_2000\"):\n                    pytest.skip(\"jpg_2000 not available\")\n                temp_file = str(tmp_path / (\"temp.\" + ext))\n                if os.path.exists(temp_file):\n                    os.remove(temp_file)\n                im.save(Path(temp_file))\n\n    def test_fp_name(self, tmp_path: Path) -> None:\n        temp_file = str(tmp_path / \"temp.jpg\")\n\n        class FP(io.BytesIO):\n            name: str\n\n            if sys.version_info >= (3, 12):\n                from collections.abc import Buffer\n\n                def write(self, data: Buffer) -> int:\n                    return len(data)\n\n            else:\n\n                def write(self, data: Any) -> int:\n                    return len(data)\n\n        fp = FP()\n        fp.name = temp_file\n\n        im = hopper()\n        im.save(fp)\n\n    def test_tempfile(self) -> None:\n        # see #1460, pathlib support breaks tempfile.TemporaryFile on py27\n        # Will error out on save on 3.0.0\n        im = hopper()\n        with tempfile.TemporaryFile() as fp:\n            im.save(fp, \"JPEG\")\n            fp.seek(0)\n            with Image.open(fp) as reloaded:\n                assert_image_similar(im, reloaded, 20)\n\n    def test_unknown_extension(self, tmp_path: Path) -> None:\n        im = hopper()\n        temp_file = str(tmp_path / \"temp.unknown\")\n        with pytest.raises(ValueError):\n            im.save(temp_file)\n\n    def test_internals(self) -> None:\n        im = Image.new(\"L\", (100, 100))\n        im.readonly = 1\n        im._copy()\n        assert not im.readonly\n\n        im.readonly = 1\n        im.paste(0, (0, 0, 100, 100))\n        assert not im.readonly\n\n    @pytest.mark.skipif(is_win32(), reason=\"Test requires opening tempfile twice\")\n    @pytest.mark.skipif(\n        sys.platform == \"cygwin\",\n        reason=\"Test requires opening an mmaped file for writing\",\n    )\n    def test_readonly_save(self, tmp_path: Path) -> None:\n        temp_file = str(tmp_path / \"temp.bmp\")\n        shutil.copy(\"Tests/images/rgb32bf-rgba.bmp\", temp_file)\n\n        with Image.open(temp_file) as im:\n            assert im.readonly\n            im.save(temp_file)\n\n    def test_dump(self, tmp_path: Path) -> None:\n        im = Image.new(\"L\", (10, 10))\n        im._dump(str(tmp_path / \"temp_L.ppm\"))\n\n        im = Image.new(\"RGB\", (10, 10))\n        im._dump(str(tmp_path / \"temp_RGB.ppm\"))\n\n        im = Image.new(\"HSV\", (10, 10))\n        with pytest.raises(ValueError):\n            im._dump(str(tmp_path / \"temp_HSV.ppm\"))\n\n    def test_comparison_with_other_type(self) -> None:\n        # Arrange\n        item = Image.new(\"RGB\", (25, 25), \"#000\")\n        num = 12\n\n        # Act/Assert\n        # Shouldn't cause AttributeError (#774)\n        assert item is not None\n        assert item != num\n\n    def test_expand_x(self) -> None:\n        # Arrange\n        im = hopper()\n        orig_size = im.size\n        xmargin = 5\n\n        # Act\n        im = im._expand(xmargin)\n\n        # Assert\n        assert im.size[0] == orig_size[0] + 2 * xmargin\n        assert im.size[1] == orig_size[1] + 2 * xmargin\n\n    def test_expand_xy(self) -> None:\n        # Arrange\n        im = hopper()\n        orig_size = im.size\n        xmargin = 5\n        ymargin = 3\n\n        # Act\n        im = im._expand(xmargin, ymargin)\n\n        # Assert\n        assert im.size[0] == orig_size[0] + 2 * xmargin\n        assert im.size[1] == orig_size[1] + 2 * ymargin\n\n    def test_getbands(self) -> None:\n        # Assert\n        assert hopper(\"RGB\").getbands() == (\"R\", \"G\", \"B\")\n        assert hopper(\"YCbCr\").getbands() == (\"Y\", \"Cb\", \"Cr\")\n\n    def test_getchannel_wrong_params(self) -> None:\n        im = hopper()\n\n        with pytest.raises(ValueError):\n            im.getchannel(-1)\n        with pytest.raises(ValueError):\n            im.getchannel(3)\n        with pytest.raises(ValueError):\n            im.getchannel(\"Z\")\n        with pytest.raises(ValueError):\n            im.getchannel(\"1\")\n\n    def test_getchannel(self) -> None:\n        im = hopper(\"YCbCr\")\n        Y, Cb, Cr = im.split()\n\n        assert_image_equal(Y, im.getchannel(0))\n        assert_image_equal(Y, im.getchannel(\"Y\"))\n        assert_image_equal(Cb, im.getchannel(1))\n        assert_image_equal(Cb, im.getchannel(\"Cb\"))\n        assert_image_equal(Cr, im.getchannel(2))\n        assert_image_equal(Cr, im.getchannel(\"Cr\"))\n\n    def test_getbbox(self) -> None:\n        # Arrange\n        im = hopper()\n\n        # Act\n        bbox = im.getbbox()\n\n        # Assert\n        assert bbox == (0, 0, 128, 128)\n\n    def test_ne(self) -> None:\n        # Arrange\n        im1 = Image.new(\"RGB\", (25, 25), \"black\")\n        im2 = Image.new(\"RGB\", (25, 25), \"white\")\n\n        # Act / Assert\n        assert im1 != im2\n\n    def test_alpha_composite(self) -> None:\n        # https://stackoverflow.com/questions/3374878\n        # Arrange\n        expected_colors = sorted(\n            [\n                (1122, (128, 127, 0, 255)),\n                (1089, (0, 255, 0, 255)),\n                (3300, (255, 0, 0, 255)),\n                (1156, (170, 85, 0, 192)),\n                (1122, (0, 255, 0, 128)),\n                (1122, (255, 0, 0, 128)),\n                (1089, (0, 255, 0, 0)),\n            ]\n        )\n\n        dst = Image.new(\"RGBA\", size=(100, 100), color=(0, 255, 0, 255))\n        draw = ImageDraw.Draw(dst)\n        draw.rectangle((0, 33, 100, 66), fill=(0, 255, 0, 128))\n        draw.rectangle((0, 67, 100, 100), fill=(0, 255, 0, 0))\n        src = Image.new(\"RGBA\", size=(100, 100), color=(255, 0, 0, 255))\n        draw = ImageDraw.Draw(src)\n        draw.rectangle((33, 0, 66, 100), fill=(255, 0, 0, 128))\n        draw.rectangle((67, 0, 100, 100), fill=(255, 0, 0, 0))\n\n        # Act\n        img = Image.alpha_composite(dst, src)\n\n        # Assert\n        img_colors = sorted(img.getcolors())\n        assert img_colors == expected_colors\n\n    def test_alpha_inplace(self) -> None:\n        src = Image.new(\"RGBA\", (128, 128), \"blue\")\n\n        over = Image.new(\"RGBA\", (128, 128), \"red\")\n        mask = hopper(\"L\")\n        over.putalpha(mask)\n\n        target = Image.alpha_composite(src, over)\n\n        # basic\n        full = src.copy()\n        full.alpha_composite(over)\n        assert_image_equal(full, target)\n\n        # with offset down to right\n        offset = src.copy()\n        offset.alpha_composite(over, (64, 64))\n        assert_image_equal(offset.crop((64, 64, 127, 127)), target.crop((0, 0, 63, 63)))\n        assert offset.size == (128, 128)\n\n        # with negative offset\n        offset = src.copy()\n        offset.alpha_composite(over, (-64, -64))\n        assert_image_equal(offset.crop((0, 0, 63, 63)), target.crop((64, 64, 127, 127)))\n        assert offset.size == (128, 128)\n\n        # offset and crop\n        box = src.copy()\n        box.alpha_composite(over, (64, 64), (0, 0, 32, 32))\n        assert_image_equal(box.crop((64, 64, 96, 96)), target.crop((0, 0, 32, 32)))\n        assert_image_equal(box.crop((96, 96, 128, 128)), src.crop((0, 0, 32, 32)))\n        assert box.size == (128, 128)\n\n        # source point\n        source = src.copy()\n        source.alpha_composite(over, (32, 32), (32, 32, 96, 96))\n\n        assert_image_equal(source.crop((32, 32, 96, 96)), target.crop((32, 32, 96, 96)))\n        assert source.size == (128, 128)\n\n        # errors\n        with pytest.raises(ValueError):\n            source.alpha_composite(over, \"invalid destination\")  # type: ignore[arg-type]\n        with pytest.raises(ValueError):\n            source.alpha_composite(over, (0, 0), \"invalid source\")  # type: ignore[arg-type]\n        with pytest.raises(ValueError):\n            source.alpha_composite(over, 0)  # type: ignore[arg-type]\n        with pytest.raises(ValueError):\n            source.alpha_composite(over, (0, 0), 0)  # type: ignore[arg-type]\n        with pytest.raises(ValueError):\n            source.alpha_composite(over, (0, 0), (0, -1))\n\n    def test_register_open_duplicates(self) -> None:\n        # Arrange\n        factory, accept = Image.OPEN[\"JPEG\"]\n        id_length = len(Image.ID)\n\n        # Act\n        Image.register_open(\"JPEG\", factory, accept)\n\n        # Assert\n        assert len(Image.ID) == id_length\n\n    def test_registered_extensions_uninitialized(self) -> None:\n        # Arrange\n        Image._initialized = 0\n\n        # Act\n        Image.registered_extensions()\n\n        # Assert\n        assert Image._initialized == 2\n\n    def test_registered_extensions(self) -> None:\n        # Arrange\n        # Open an image to trigger plugin registration\n        with Image.open(\"Tests/images/rgb.jpg\"):\n            pass\n\n        # Act\n        extensions = Image.registered_extensions()\n\n        # Assert\n        assert extensions\n        for ext in [\".cur\", \".icns\", \".tif\", \".tiff\"]:\n            assert ext in extensions\n\n    def test_effect_mandelbrot(self) -> None:\n        # Arrange\n        size = (512, 512)\n        extent = (-3, -2.5, 2, 2.5)\n        quality = 100\n\n        # Act\n        im = Image.effect_mandelbrot(size, extent, quality)\n\n        # Assert\n        assert im.size == (512, 512)\n        assert_image_equal_tofile(im, \"Tests/images/effect_mandelbrot.png\")\n\n    def test_effect_mandelbrot_bad_arguments(self) -> None:\n        # Arrange\n        size = (512, 512)\n        # Get coordinates the wrong way round:\n        extent = (+3, +2.5, -2, -2.5)\n        # Quality < 2:\n        quality = 1\n\n        # Act/Assert\n        with pytest.raises(ValueError):\n            Image.effect_mandelbrot(size, extent, quality)\n\n    def test_effect_noise(self) -> None:\n        # Arrange\n        size = (100, 100)\n        sigma = 128\n\n        # Act\n        im = Image.effect_noise(size, sigma)\n\n        # Assert\n        assert im.size == (100, 100)\n        assert im.mode == \"L\"\n        p0 = im.getpixel((0, 0))\n        p1 = im.getpixel((0, 1))\n        p2 = im.getpixel((0, 2))\n        p3 = im.getpixel((0, 3))\n        p4 = im.getpixel((0, 4))\n        assert_not_all_same([p0, p1, p2, p3, p4])\n\n    def test_effect_spread(self) -> None:\n        # Arrange\n        im = hopper()\n        distance = 10\n\n        # Act\n        im2 = im.effect_spread(distance)\n\n        # Assert\n        assert im.size == (128, 128)\n        assert_image_similar_tofile(im2, \"Tests/images/effect_spread.png\", 110)\n\n    def test_effect_spread_zero(self) -> None:\n        # Arrange\n        im = hopper()\n        distance = 0\n\n        # Act\n        im2 = im.effect_spread(distance)\n\n        # Assert\n        assert_image_equal(im, im2)\n\n    def test_check_size(self) -> None:\n        # Checking that the _check_size function throws value errors when we want it to\n        with pytest.raises(ValueError):\n            # not a tuple\n            Image.new(\"RGB\", 0)  # type: ignore[arg-type]\n        with pytest.raises(ValueError):\n            # tuple too short\n            Image.new(\"RGB\", (0,))  # type: ignore[arg-type]\n        with pytest.raises(ValueError):\n            Image.new(\"RGB\", (-1, -1))  # w,h < 0\n\n        # this should pass with 0 sized images, #2259\n        im = Image.new(\"L\", (0, 0))\n        assert im.size == (0, 0)\n\n        im = Image.new(\"L\", (0, 100))\n        assert im.size == (0, 100)\n\n        im = Image.new(\"L\", (100, 0))\n        assert im.size == (100, 0)\n\n        assert Image.new(\"RGB\", (1, 1))\n        # Should pass lists too\n        i = Image.new(\"RGB\", [1, 1])\n        assert isinstance(i.size, tuple)\n\n    @pytest.mark.timeout(0.75)\n    @pytest.mark.skipif(\n        \"PILLOW_VALGRIND_TEST\" in os.environ, reason=\"Valgrind is slower\"\n    )\n    @pytest.mark.parametrize(\"size\", ((0, 100000000), (100000000, 0)))\n    def test_empty_image(self, size: tuple[int, int]) -> None:\n        Image.new(\"RGB\", size)\n\n    def test_storage_neg(self) -> None:\n        # Storage.c accepted negative values for xsize, ysize.  Was\n        # test_neg_ppm, but the core function for that has been\n        # removed Calling directly into core to test the error in\n        # Storage.c, rather than the size check above\n\n        with pytest.raises(ValueError):\n            Image.core.fill(\"RGB\", (2, -2), (0, 0, 0))\n\n    def test_one_item_tuple(self) -> None:\n        for mode in (\"I\", \"F\", \"L\"):\n            im = Image.new(mode, (100, 100), (5,))\n            px = im.load()\n            assert px[0, 0] == 5\n\n    def test_linear_gradient_wrong_mode(self) -> None:\n        # Arrange\n        wrong_mode = \"RGB\"\n\n        # Act / Assert\n        with pytest.raises(ValueError):\n            Image.linear_gradient(wrong_mode)\n\n    @pytest.mark.parametrize(\"mode\", (\"L\", \"P\", \"I\", \"F\"))\n    def test_linear_gradient(self, mode: str) -> None:\n        # Arrange\n        target_file = \"Tests/images/linear_gradient.png\"\n\n        # Act\n        im = Image.linear_gradient(mode)\n\n        # Assert\n        assert im.size == (256, 256)\n        assert im.mode == mode\n        assert im.getpixel((0, 0)) == 0\n        assert im.getpixel((255, 255)) == 255\n        with Image.open(target_file) as target:\n            target = target.convert(mode)\n        assert_image_equal(im, target)\n\n    def test_radial_gradient_wrong_mode(self) -> None:\n        # Arrange\n        wrong_mode = \"RGB\"\n\n        # Act / Assert\n        with pytest.raises(ValueError):\n            Image.radial_gradient(wrong_mode)\n\n    @pytest.mark.parametrize(\"mode\", (\"L\", \"P\", \"I\", \"F\"))\n    def test_radial_gradient(self, mode: str) -> None:\n        # Arrange\n        target_file = \"Tests/images/radial_gradient.png\"\n\n        # Act\n        im = Image.radial_gradient(mode)\n\n        # Assert\n        assert im.size == (256, 256)\n        assert im.mode == mode\n        assert im.getpixel((0, 0)) == 255\n        assert im.getpixel((128, 128)) == 0\n        with Image.open(target_file) as target:\n            target = target.convert(mode)\n        assert_image_equal(im, target)\n\n    def test_register_extensions(self) -> None:\n        test_format = \"a\"\n        exts = [\"b\", \"c\"]\n        for ext in exts:\n            Image.register_extension(test_format, ext)\n        ext_individual = Image.EXTENSION.copy()\n        for ext in exts:\n            del Image.EXTENSION[ext]\n\n        Image.register_extensions(test_format, exts)\n        ext_multiple = Image.EXTENSION.copy()\n        for ext in exts:\n            del Image.EXTENSION[ext]\n\n        assert ext_individual == ext_multiple\n\n    def test_remap_palette(self) -> None:\n        # Test identity transform\n        with Image.open(\"Tests/images/hopper.gif\") as im:\n            assert_image_equal(im, im.remap_palette(list(range(256))))\n\n        # Test identity transform with an RGBA palette\n        im = Image.new(\"P\", (256, 1))\n        for x in range(256):\n            im.putpixel((x, 0), x)\n        im.putpalette(list(range(256)) * 4, \"RGBA\")\n        im_remapped = im.remap_palette(list(range(256)))\n        assert_image_equal(im, im_remapped)\n        assert im.palette.palette == im_remapped.palette.palette\n\n        # Test illegal image mode\n        with hopper() as im:\n            with pytest.raises(ValueError):\n                im.remap_palette(None)\n\n    def test_remap_palette_transparency(self) -> None:\n        im = Image.new(\"P\", (1, 2), (0, 0, 0))\n        im.putpixel((0, 1), (255, 0, 0))\n        im.info[\"transparency\"] = 0\n\n        im_remapped = im.remap_palette([1, 0])\n        assert im_remapped.info[\"transparency\"] == 1\n        assert len(im_remapped.getpalette()) == 6\n\n        # Test unused transparency\n        im.info[\"transparency\"] = 2\n\n        im_remapped = im.remap_palette([1, 0])\n        assert \"transparency\" not in im_remapped.info\n\n    def test__new(self) -> None:\n        im = hopper(\"RGB\")\n        im_p = hopper(\"P\")\n\n        blank_p = Image.new(\"P\", (10, 10))\n        blank_pa = Image.new(\"PA\", (10, 10))\n        blank_p.palette = None\n        blank_pa.palette = None\n\n        def _make_new(\n            base_image: Image.Image,\n            image: Image.Image,\n            palette_result: ImagePalette.ImagePalette | None = None,\n        ) -> None:\n            new_image = base_image._new(image.im)\n            assert new_image.mode == image.mode\n            assert new_image.size == image.size\n            assert new_image.info == base_image.info\n            if palette_result is not None:\n                assert new_image.palette.tobytes() == palette_result.tobytes()\n            else:\n                assert new_image.palette is None\n\n        _make_new(im, im_p, ImagePalette.ImagePalette(list(range(256)) * 3))\n        _make_new(im_p, im, None)\n        _make_new(im, blank_p, ImagePalette.ImagePalette())\n        _make_new(im, blank_pa, ImagePalette.ImagePalette())\n\n    @pytest.mark.parametrize(\n        \"mode, color\",\n        (\n            (\"RGB\", \"#DDEEFF\"),\n            (\"RGB\", (221, 238, 255)),\n            (\"RGBA\", (221, 238, 255, 255)),\n        ),\n    )\n    def test_p_from_rgb_rgba(self, mode: str, color: str | tuple[int, ...]) -> None:\n        im = Image.new(\"P\", (100, 100), color)\n        expected = Image.new(mode, (100, 100), color)\n        assert_image_equal(im.convert(mode), expected)\n\n    def test_no_resource_warning_on_save(self, tmp_path: Path) -> None:\n        # https://github.com/python-pillow/Pillow/issues/835\n        # Arrange\n        test_file = \"Tests/images/hopper.png\"\n        temp_file = str(tmp_path / \"temp.jpg\")\n\n        # Act/Assert\n        with Image.open(test_file) as im:\n            with warnings.catch_warnings():\n                im.save(temp_file)\n\n    def test_no_new_file_on_error(self, tmp_path: Path) -> None:\n        temp_file = str(tmp_path / \"temp.jpg\")\n\n        im = Image.new(\"RGB\", (0, 0))\n        with pytest.raises(ValueError):\n            im.save(temp_file)\n\n        assert not os.path.exists(temp_file)\n\n    def test_load_on_nonexclusive_multiframe(self) -> None:\n        with open(\"Tests/images/frozenpond.mpo\", \"rb\") as fp:\n\n            def act(fp: IO[bytes]) -> None:\n                im = Image.open(fp)\n                im.load()\n\n            act(fp)\n\n            with Image.open(fp) as im:\n                im.load()\n\n            assert not fp.closed\n\n    def test_empty_exif(self) -> None:\n        with Image.open(\"Tests/images/exif.png\") as im:\n            exif = im.getexif()\n        assert dict(exif)\n\n        # Test that exif data is cleared after another load\n        exif.load(None)\n        assert not dict(exif)\n\n        # Test loading just the EXIF header\n        exif.load(b\"Exif\\x00\\x00\")\n        assert not dict(exif)\n\n    @mark_if_feature_version(\n        pytest.mark.valgrind_known_error, \"libjpeg_turbo\", \"2.0\", reason=\"Known Failing\"\n    )\n    def test_exif_jpeg(self, tmp_path: Path) -> None:\n        with Image.open(\"Tests/images/exif-72dpi-int.jpg\") as im:  # Little endian\n            exif = im.getexif()\n            assert 258 not in exif\n            assert 274 in exif\n            assert 282 in exif\n            assert exif[296] == 2\n            assert exif[11] == \"gThumb 3.0.1\"\n\n            out = str(tmp_path / \"temp.jpg\")\n            exif[258] = 8\n            del exif[274]\n            del exif[282]\n            exif[296] = 455\n            exif[11] = \"Pillow test\"\n            im.save(out, exif=exif)\n        with Image.open(out) as reloaded:\n            reloaded_exif = reloaded.getexif()\n            assert reloaded_exif[258] == 8\n            assert 274 not in reloaded_exif\n            assert 282 not in reloaded_exif\n            assert reloaded_exif[296] == 455\n            assert reloaded_exif[11] == \"Pillow test\"\n\n        with Image.open(\"Tests/images/no-dpi-in-exif.jpg\") as im:  # Big endian\n            exif = im.getexif()\n            assert 258 not in exif\n            assert 306 in exif\n            assert exif[274] == 1\n            assert exif[305] == \"Adobe Photoshop CC 2017 (Macintosh)\"\n\n            out = str(tmp_path / \"temp.jpg\")\n            exif[258] = 8\n            del exif[306]\n            exif[274] = 455\n            exif[305] = \"Pillow test\"\n            im.save(out, exif=exif)\n        with Image.open(out) as reloaded:\n            reloaded_exif = reloaded.getexif()\n            assert reloaded_exif[258] == 8\n            assert 306 not in reloaded_exif\n            assert reloaded_exif[274] == 455\n            assert reloaded_exif[305] == \"Pillow test\"\n\n    @skip_unless_feature(\"webp\")\n    @skip_unless_feature(\"webp_anim\")\n    def test_exif_webp(self, tmp_path: Path) -> None:\n        with Image.open(\"Tests/images/hopper.webp\") as im:\n            exif = im.getexif()\n            assert exif == {}\n\n            out = str(tmp_path / \"temp.webp\")\n            exif[258] = 8\n            exif[40963] = 455\n            exif[305] = \"Pillow test\"\n\n            def check_exif() -> None:\n                with Image.open(out) as reloaded:\n                    reloaded_exif = reloaded.getexif()\n                    assert reloaded_exif[258] == 8\n                    assert reloaded_exif[40963] == 455\n                    assert reloaded_exif[305] == \"Pillow test\"\n\n            im.save(out, exif=exif)\n            check_exif()\n            im.save(out, exif=exif, save_all=True)\n            check_exif()\n\n    def test_exif_png(self, tmp_path: Path) -> None:\n        with Image.open(\"Tests/images/exif.png\") as im:\n            exif = im.getexif()\n            assert exif == {274: 1}\n\n            out = str(tmp_path / \"temp.png\")\n            exif[258] = 8\n            del exif[274]\n            exif[40963] = 455\n            exif[305] = \"Pillow test\"\n            im.save(out, exif=exif)\n\n        with Image.open(out) as reloaded:\n            reloaded_exif = reloaded.getexif()\n            assert reloaded_exif == {258: 8, 40963: 455, 305: \"Pillow test\"}\n\n    def test_exif_interop(self) -> None:\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            exif = im.getexif()\n            assert exif.get_ifd(0xA005) == {\n                1: \"R98\",\n                2: b\"0100\",\n                4097: 2272,\n                4098: 1704,\n            }\n\n            reloaded_exif = Image.Exif()\n            reloaded_exif.load(exif.tobytes())\n            assert reloaded_exif.get_ifd(0xA005) == exif.get_ifd(0xA005)\n\n    def test_exif_ifd1(self) -> None:\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            exif = im.getexif()\n            assert exif.get_ifd(ExifTags.IFD.IFD1) == {\n                513: 2036,\n                514: 5448,\n                259: 6,\n                296: 2,\n                282: 180.0,\n                283: 180.0,\n            }\n\n    def test_exif_ifd(self) -> None:\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            exif = im.getexif()\n        del exif.get_ifd(0x8769)[0xA005]\n\n        reloaded_exif = Image.Exif()\n        reloaded_exif.load(exif.tobytes())\n        assert reloaded_exif.get_ifd(0x8769) == exif.get_ifd(0x8769)\n\n    def test_exif_load_from_fp(self) -> None:\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            data = im.info[\"exif\"]\n            if data.startswith(b\"Exif\\x00\\x00\"):\n                data = data[6:]\n            fp = io.BytesIO(data)\n\n            exif = Image.Exif()\n            exif.load_from_fp(fp)\n            assert exif == {\n                271: \"Canon\",\n                272: \"Canon PowerShot S40\",\n                274: 1,\n                282: 180.0,\n                283: 180.0,\n                296: 2,\n                306: \"2003:12:14 12:01:44\",\n                531: 1,\n                34665: 196,\n            }\n\n    def test_exif_hide_offsets(self) -> None:\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            exif = im.getexif()\n\n        # Check offsets are present initially\n        assert 0x8769 in exif\n        for tag in (0xA005, 0x927C):\n            assert tag in exif.get_ifd(0x8769)\n        assert exif.get_ifd(0xA005)\n        loaded_exif = exif\n\n        with Image.open(\"Tests/images/flower.jpg\") as im:\n            new_exif = im.getexif()\n\n            for exif in (loaded_exif, new_exif):\n                exif.hide_offsets()\n\n                # Assert they are hidden afterwards,\n                # but that the IFDs are still available\n                assert 0x8769 not in exif\n                assert exif.get_ifd(0x8769)\n                for tag in (0xA005, 0x927C):\n                    assert tag not in exif.get_ifd(0x8769)\n                assert exif.get_ifd(0xA005)\n\n    def test_empty_xmp(self) -> None:\n        with Image.open(\"Tests/images/hopper.gif\") as im:\n            assert im.getxmp() == {}\n\n    def test_getxmp_padded(self) -> None:\n        im = Image.new(\"RGB\", (1, 1))\n        im.info[\"xmp\"] = (\n            b'<?xpacket begin=\"\\xef\\xbb\\xbf\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\\n'\n            b'<x:xmpmeta xmlns:x=\"adobe:ns:meta/\" />\\n<?xpacket end=\"w\"?>\\x00\\x00'\n        )\n        if ElementTree is None:\n            with pytest.warns(\n                UserWarning,\n                match=\"XMP data cannot be read without defusedxml dependency\",\n            ):\n                assert im.getxmp() == {}\n        else:\n            assert im.getxmp() == {\"xmpmeta\": None}\n\n    @pytest.mark.parametrize(\"size\", ((1, 0), (0, 1), (0, 0)))\n    def test_zero_tobytes(self, size: tuple[int, int]) -> None:\n        im = Image.new(\"RGB\", size)\n        assert im.tobytes() == b\"\"\n\n    @pytest.mark.parametrize(\"size\", ((1, 0), (0, 1), (0, 0)))\n    def test_zero_frombytes(self, size: tuple[int, int]) -> None:\n        Image.frombytes(\"RGB\", size, b\"\")\n\n        im = Image.new(\"RGB\", size)\n        im.frombytes(b\"\")\n\n    def test_has_transparency_data(self) -> None:\n        for mode in (\"1\", \"L\", \"P\", \"RGB\"):\n            im = Image.new(mode, (1, 1))\n            assert not im.has_transparency_data\n\n        for mode in (\"LA\", \"La\", \"PA\", \"RGBA\", \"RGBa\"):\n            im = Image.new(mode, (1, 1))\n            assert im.has_transparency_data\n\n        # P mode with \"transparency\" info\n        with Image.open(\"Tests/images/first_frame_transparency.gif\") as im:\n            assert \"transparency\" in im.info\n            assert im.has_transparency_data\n\n        # RGB mode with \"transparency\" info\n        with Image.open(\"Tests/images/rgb_trns.png\") as im:\n            assert \"transparency\" in im.info\n            assert im.has_transparency_data\n\n        # P mode with RGBA palette\n        im = Image.new(\"RGBA\", (1, 1)).convert(\"P\")\n        assert im.mode == \"P\"\n        assert im.palette.mode == \"RGBA\"\n        assert im.has_transparency_data\n\n    def test_apply_transparency(self) -> None:\n        im = Image.new(\"P\", (1, 1))\n        im.putpalette((0, 0, 0, 1, 1, 1))\n        assert im.palette.colors == {(0, 0, 0): 0, (1, 1, 1): 1}\n\n        # Test that no transformation is applied without transparency\n        im.apply_transparency()\n        assert im.palette.colors == {(0, 0, 0): 0, (1, 1, 1): 1}\n\n        # Test that a transparency index is applied\n        im.info[\"transparency\"] = 0\n        im.apply_transparency()\n        assert \"transparency\" not in im.info\n        assert im.palette.colors == {(0, 0, 0, 0): 0, (1, 1, 1, 255): 1}\n\n        # Test that existing transparency is kept\n        im = Image.new(\"P\", (1, 1))\n        im.putpalette((0, 0, 0, 255, 1, 1, 1, 128), \"RGBA\")\n        im.info[\"transparency\"] = 0\n        im.apply_transparency()\n        assert im.palette.colors == {(0, 0, 0, 0): 0, (1, 1, 1, 128): 1}\n\n        # Test that transparency bytes are applied\n        with Image.open(\"Tests/images/pil123p.png\") as im:\n            assert isinstance(im.info[\"transparency\"], bytes)\n            assert im.palette.colors[(27, 35, 6)] == 24\n            im.apply_transparency()\n            assert im.palette.colors[(27, 35, 6, 214)] == 24\n\n    def test_constants(self) -> None:\n        for enum in (\n            Image.Transpose,\n            Image.Transform,\n            Image.Resampling,\n            Image.Dither,\n            Image.Palette,\n            Image.Quantize,\n        ):\n            for name in enum.__members__:\n                assert getattr(Image, name) == enum[name]\n\n    @pytest.mark.parametrize(\n        \"path\",\n        [\n            \"fli_overrun.bin\",\n            \"sgi_overrun.bin\",\n            \"sgi_overrun_expandrow.bin\",\n            \"sgi_overrun_expandrow2.bin\",\n            \"pcx_overrun.bin\",\n            \"pcx_overrun2.bin\",\n            \"ossfuzz-4836216264589312.pcx\",\n            \"01r_00.pcx\",\n        ],\n    )\n    def test_overrun(self, path: str) -> None:\n        \"\"\"For overrun completeness, test as:\n        valgrind pytest -qq Tests/test_image.py::TestImage::test_overrun | grep decode.c\n        \"\"\"\n        with Image.open(os.path.join(\"Tests/images\", path)) as im:\n            try:\n                im.load()\n                pytest.fail()\n            except OSError as e:\n                buffer_overrun = str(e) == \"buffer overrun when reading image file\"\n                truncated = \"image file is truncated\" in str(e)\n\n                assert buffer_overrun or truncated\n\n    def test_fli_overrun2(self) -> None:\n        with Image.open(\"Tests/images/fli_overrun2.bin\") as im:\n            try:\n                im.seek(1)\n                pytest.fail()\n            except OSError as e:\n                assert str(e) == \"buffer overrun when reading image file\"\n\n    def test_exit_fp(self) -> None:\n        with Image.new(\"L\", (1, 1)) as im:\n            pass\n        assert not hasattr(im, \"fp\")\n\n    def test_close_graceful(self, caplog: pytest.LogCaptureFixture) -> None:\n        with Image.open(\"Tests/images/hopper.jpg\") as im:\n            copy = im.copy()\n            with caplog.at_level(logging.DEBUG):\n                im.close()\n                copy.close()\n            assert len(caplog.records) == 0\n            assert im.fp is None\n\n\nclass TestImageBytes:\n    @pytest.mark.parametrize(\"mode\", Image.MODES + [\"BGR;15\", \"BGR;16\", \"BGR;24\"])\n    def test_roundtrip_bytes_constructor(self, mode: str) -> None:\n        im = hopper(mode)\n        source_bytes = im.tobytes()\n\n        if mode.startswith(\"BGR;\"):\n            with pytest.warns(DeprecationWarning):\n                reloaded = Image.frombytes(mode, im.size, source_bytes)\n        else:\n            reloaded = Image.frombytes(mode, im.size, source_bytes)\n        assert reloaded.tobytes() == source_bytes\n\n    @pytest.mark.parametrize(\"mode\", Image.MODES + [\"BGR;15\", \"BGR;16\", \"BGR;24\"])\n    def test_roundtrip_bytes_method(self, mode: str) -> None:\n        im = hopper(mode)\n        source_bytes = im.tobytes()\n\n        reloaded = helper_image_new(mode, im.size)\n        reloaded.frombytes(source_bytes)\n        assert reloaded.tobytes() == source_bytes\n\n    @pytest.mark.parametrize(\"mode\", Image.MODES + [\"BGR;15\", \"BGR;16\", \"BGR;24\"])\n    def test_getdata_putdata(self, mode: str) -> None:\n        if is_big_endian() and mode == \"BGR;15\":\n            pytest.xfail(\"Known failure of BGR;15 on big-endian\")\n        im = hopper(mode)\n        reloaded = helper_image_new(mode, im.size)\n        reloaded.putdata(im.getdata())\n        assert_image_equal(im, reloaded)\n\n\nclass MockEncoder(ImageFile.PyEncoder):\n    pass\n\n\nclass TestRegistry:\n    def test_encode_registry(self) -> None:\n        Image.register_encoder(\"MOCK\", MockEncoder)\n        assert \"MOCK\" in Image.ENCODERS\n\n        enc = Image._getencoder(\"RGB\", \"MOCK\", (\"args\",), extra=(\"extra\",))\n\n        assert isinstance(enc, MockEncoder)\n        assert enc.mode == \"RGB\"\n        assert enc.args == (\"args\", \"extra\")\n\n    def test_encode_registry_fail(self) -> None:\n        with pytest.raises(OSError):\n            Image._getencoder(\"RGB\", \"DoesNotExist\", (\"args\",), extra=(\"extra\",))\n"
    ],
    "test_file_names": [
        "test_1.py"
    ],
    "setup_res_code": 0,
    "setup_res_stdout": "Starting Pillow installation attempts...\nVerifying Pillow installation...\n✅ Pillow installation successful!\nSuccessfully installed Pillow\n",
    "setup_res_stderr": "warning: `VIRTUAL_ENV=/home/gcpuser/r2e-edits-internal/.venv` does not match the project environment path `.venv` and will be ignored\nUsing CPython 3.9.21\nCreating virtual environment at: .venv\nActivate with: source .venv/bin/activate\nResolved 12 packages in 15ms\nInstalled 12 packages in 142ms\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 980ms\nPrepared 1 package in 36.02s\nInstalled 1 package in 0.84ms\n + pillow==10.4.0.dev0 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/pillow_3fdaecb0255abab55d7269fc80b26e532307886c)\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_3fdaecb0255abab55d7269fc80b26e532307886c\nconfigfile: pyproject.toml\nplugins: cov-6.0.0\ncollected 188 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.\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.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[33ms\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[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 [ 27%]\n\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.\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.\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.\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.\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 [ 65%]\n\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.\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.\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.\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.\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[1mTestImage::test_image_modes_success[1]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[CMYK]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[F]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[HSV]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[I]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[I;16]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[I;16B]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[I;16L]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[I;16N]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[L]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[LA]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[La]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[LAB]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[P]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[PA]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[RGB]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[RGBA]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[RGBa]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[RGBX]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[YCbCr]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[BGR;15]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[BGR;16]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[BGR;24]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_fail[]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_fail[bad]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_fail[very very long]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_exception_inheritance\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_sanity\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_repr_pretty\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_open_formats\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_open_verbose_failure\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_width_height\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_set_mode\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_invalid_image\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_bad_mode\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_stringio\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_fp_name\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_tempfile\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_unknown_extension\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_internals\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_readonly_save\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_dump\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_comparison_with_other_type\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_expand_x\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_expand_xy\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_getbands\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_getchannel_wrong_params\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_getchannel\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_getbbox\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_ne\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_alpha_composite\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_alpha_inplace\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_register_open_duplicates\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_registered_extensions_uninitialized\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_registered_extensions\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_effect_mandelbrot\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_effect_mandelbrot_bad_arguments\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_effect_noise\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_effect_spread\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_effect_spread_zero\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_check_size\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_empty_image[size0]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_empty_image[size1]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_storage_neg\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_one_item_tuple\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_linear_gradient_wrong_mode\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_linear_gradient[L]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_linear_gradient[P]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_linear_gradient[I]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_linear_gradient[F]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_radial_gradient_wrong_mode\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_radial_gradient[L]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_radial_gradient[P]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_radial_gradient[I]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_radial_gradient[F]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_register_extensions\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_remap_palette\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_remap_palette_transparency\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test__new\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_p_from_rgb_rgba[RGB-#DDEEFF]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_p_from_rgb_rgba[RGB-color1]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_p_from_rgb_rgba[RGBA-color2]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_no_resource_warning_on_save\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_no_new_file_on_error\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_load_on_nonexclusive_multiframe\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_empty_exif\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_exif_jpeg\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_exif_webp\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_exif_png\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_exif_interop\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_exif_ifd1\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_exif_ifd\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_exif_load_from_fp\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_exif_hide_offsets\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_empty_xmp\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_getxmp_padded\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_zero_tobytes[size0]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_zero_tobytes[size1]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_zero_tobytes[size2]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_zero_frombytes[size0]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_zero_frombytes[size1]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_zero_frombytes[size2]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_has_transparency_data\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_apply_transparency\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_constants\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_overrun[fli_overrun.bin]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_overrun[sgi_overrun.bin]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_overrun[sgi_overrun_expandrow.bin]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_overrun[sgi_overrun_expandrow2.bin]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_overrun[pcx_overrun.bin]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_overrun[pcx_overrun2.bin]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_overrun[ossfuzz-4836216264589312.pcx]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_overrun[01r_00.pcx]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_fli_overrun2\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_exit_fp\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_close_graceful\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[1]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[CMYK]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[F]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[HSV]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[I]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[I;16]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[I;16B]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[I;16L]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[I;16N]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[L]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[LA]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[La]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[LAB]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[P]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[PA]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[RGB]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[RGBA]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[RGBa]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[RGBX]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[YCbCr]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[BGR;15]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[BGR;16]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[BGR;24]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[1]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[CMYK]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[F]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[HSV]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[I]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[I;16]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[I;16B]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[I;16L]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[I;16N]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[L]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[LA]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[La]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[LAB]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[P]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[PA]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[RGB]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[RGBA]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[RGBa]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[RGBX]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[YCbCr]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[BGR;15]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[BGR;16]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[BGR;24]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[1]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[CMYK]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[F]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[HSV]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[I]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[I;16]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[I;16B]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[I;16L]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[I;16N]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[L]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[LA]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[La]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[LAB]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[P]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[PA]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[RGB]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[RGBA]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[RGBa]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[RGBX]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[YCbCr]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[BGR;15]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[BGR;16]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[BGR;24]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestRegistry::test_encode_registry\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestRegistry::test_encode_registry_fail\u001b[0m\n\u001b[33mSKIPPED\u001b[0m [1] r2e_tests/test_1.py:185: jpg_2000 not available\n\u001b[32m======================== \u001b[32m\u001b[1m187 passed\u001b[0m, \u001b[33m1 skipped\u001b[0m\u001b[32m in 0.66s\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_3fdaecb0255abab55d7269fc80b26e532307886c\nconfigfile: pyproject.toml\nplugins: cov-6.0.0\ncollected 188 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.\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[31mF\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[33ms\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[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[31m [ 27%]\n\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.\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.\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.\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.\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[31m [ 65%]\n\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.\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.\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.\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.\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_____________________ TestImage.test_open_verbose_failure ______________________\u001b[0m\n\nself = <r2e_tests.test_1.TestImage object at 0x78acf00b4ac0>\nmonkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x78acefe64880>\n\n    def test_open_verbose_failure(self, monkeypatch: pytest.MonkeyPatch) -> None:\n>       monkeypatch.setattr(Image, \"WARN_POSSIBLE_FORMATS\", True)\n\u001b[1m\u001b[31mE       AttributeError: <module 'PIL.Image' from '/home/gcpuser/buckets/local_repoeval_bucket/repos/pillow_3fdaecb0255abab55d7269fc80b26e532307886c/src/PIL/Image.py'> has no attribute 'WARN_POSSIBLE_FORMATS'\u001b[0m\n\n\u001b[1m\u001b[31mr2e_tests/test_1.py\u001b[0m:136: AttributeError\n==================================== PASSES ====================================\n\u001b[36m\u001b[1m=========================== short test summary info ============================\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[1]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[CMYK]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[F]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[HSV]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[I]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[I;16]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[I;16B]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[I;16L]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[I;16N]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[L]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[LA]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[La]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[LAB]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[P]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[PA]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[RGB]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[RGBA]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[RGBa]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[RGBX]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[YCbCr]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[BGR;15]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[BGR;16]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_success[BGR;24]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_fail[]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_fail[bad]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_image_modes_fail[very very long]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_exception_inheritance\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_sanity\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_repr_pretty\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_open_formats\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_width_height\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_set_mode\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_invalid_image\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_bad_mode\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_stringio\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_fp_name\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_tempfile\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_unknown_extension\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_internals\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_readonly_save\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_dump\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_comparison_with_other_type\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_expand_x\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_expand_xy\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_getbands\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_getchannel_wrong_params\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_getchannel\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_getbbox\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_ne\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_alpha_composite\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_alpha_inplace\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_register_open_duplicates\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_registered_extensions_uninitialized\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_registered_extensions\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_effect_mandelbrot\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_effect_mandelbrot_bad_arguments\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_effect_noise\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_effect_spread\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_effect_spread_zero\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_check_size\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_empty_image[size0]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_empty_image[size1]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_storage_neg\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_one_item_tuple\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_linear_gradient_wrong_mode\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_linear_gradient[L]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_linear_gradient[P]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_linear_gradient[I]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_linear_gradient[F]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_radial_gradient_wrong_mode\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_radial_gradient[L]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_radial_gradient[P]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_radial_gradient[I]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_radial_gradient[F]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_register_extensions\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_remap_palette\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_remap_palette_transparency\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test__new\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_p_from_rgb_rgba[RGB-#DDEEFF]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_p_from_rgb_rgba[RGB-color1]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_p_from_rgb_rgba[RGBA-color2]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_no_resource_warning_on_save\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_no_new_file_on_error\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_load_on_nonexclusive_multiframe\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_empty_exif\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_exif_jpeg\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_exif_webp\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_exif_png\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_exif_interop\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_exif_ifd1\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_exif_ifd\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_exif_load_from_fp\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_exif_hide_offsets\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_empty_xmp\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_getxmp_padded\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_zero_tobytes[size0]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_zero_tobytes[size1]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_zero_tobytes[size2]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_zero_frombytes[size0]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_zero_frombytes[size1]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_zero_frombytes[size2]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_has_transparency_data\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_apply_transparency\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_constants\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_overrun[fli_overrun.bin]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_overrun[sgi_overrun.bin]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_overrun[sgi_overrun_expandrow.bin]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_overrun[sgi_overrun_expandrow2.bin]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_overrun[pcx_overrun.bin]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_overrun[pcx_overrun2.bin]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_overrun[ossfuzz-4836216264589312.pcx]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_overrun[01r_00.pcx]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_fli_overrun2\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_exit_fp\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_close_graceful\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[1]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[CMYK]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[F]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[HSV]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[I]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[I;16]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[I;16B]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[I;16L]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[I;16N]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[L]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[LA]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[La]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[LAB]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[P]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[PA]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[RGB]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[RGBA]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[RGBa]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[RGBX]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[YCbCr]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[BGR;15]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[BGR;16]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_constructor[BGR;24]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[1]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[CMYK]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[F]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[HSV]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[I]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[I;16]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[I;16B]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[I;16L]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[I;16N]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[L]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[LA]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[La]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[LAB]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[P]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[PA]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[RGB]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[RGBA]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[RGBa]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[RGBX]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[YCbCr]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[BGR;15]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[BGR;16]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_roundtrip_bytes_method[BGR;24]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[1]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[CMYK]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[F]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[HSV]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[I]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[I;16]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[I;16B]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[I;16L]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[I;16N]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[L]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[LA]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[La]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[LAB]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[P]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[PA]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[RGB]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[RGBA]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[RGBa]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[RGBX]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[YCbCr]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[BGR;15]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[BGR;16]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImageBytes::test_getdata_putdata[BGR;24]\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestRegistry::test_encode_registry\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestRegistry::test_encode_registry_fail\u001b[0m\n\u001b[33mSKIPPED\u001b[0m [1] r2e_tests/test_1.py:185: jpg_2000 not available\n\u001b[31mFAILED\u001b[0m r2e_tests/test_1.py::\u001b[1mTestImage::test_open_verbose_failure\u001b[0m - AttributeError: <module 'PIL.Image' from '/home/gcpuser/buckets/local_repoe...\n\u001b[31m=================== \u001b[31m\u001b[1m1 failed\u001b[0m, \u001b[32m186 passed\u001b[0m, \u001b[33m1 skipped\u001b[0m\u001b[31m in 0.47s\u001b[0m\u001b[31m ===================\u001b[0m\n",
    "old_commit_res_stderr": ""
}
Tests/test_image.py docs/reference/Image.rst src/PIL/Image.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** AttributeError: 'PIL.Image' object has no attribute 'WARN_POSSIBLE_FORMATS' when enabling verbose format warnings

**Description:**
Attempting to enable verbose warnings for possible image formats results in an `AttributeError`. This prevents developers from receiving detailed warnings when opening images with unrecognized formats.

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

# Attempt to enable verbose format warnings
Image.WARN_POSSIBLE_FORMATS = True

# Try opening an invalid image to trigger a warning
im = io.BytesIO(b"")
with warnings.catch_warnings(record=True) as w:
    with Image.open(im):
        pass
```

**Expected Behavior:**
Setting `Image.WARN_POSSIBLE_FORMATS` to `True` should enable verbose warnings when attempting to open images with potentially unsupported or unrecognized formats. This should allow developers to receive `UserWarning` messages detailing the issues encountered during image opening.

**Actual Behavior:**
Assigning `True` to `Image.WARN_POSSIBLE_FORMATS` raises an `AttributeError`:
```
AttributeError: <module 'PIL.Image' from '.../PIL/Image.py'> has no attribute 'WARN_POSSIBLE_FORMATS'
```
This error occurs because the `WARN_POSSIBLE_FORMATS` attribute does not exist in the `PIL.Image` module, preventing the intended verbose warning functionality.

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

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

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

from __future__ import annotations

import abc
import atexit
import builtins
import io
import logging
import math
import os
import re
import struct
import sys
import tempfile
import warnings
from collections.abc import Callable, MutableMapping
from enum import IntEnum
from types import ModuleType
from typing import (
    IO,
    TYPE_CHECKING,
    Any,
    Literal,
    Protocol,
    Sequence,
    Tuple,
    cast,
)

# VERSION was removed in Pillow 6.0.0.
# PILLOW_VERSION was removed in Pillow 9.0.0.
# Use __version__ instead.
from . import (
    ExifTags,
    ImageMode,
    TiffTags,
    UnidentifiedImageError,
    __version__,
    _plugins,
)
from ._binary import i32le, o32be, o32le
from ._deprecate import deprecate
from ._typing import StrOrBytesPath, TypeGuard
from ._util import DeferredError, is_path

ElementTree: ModuleType | None
try:
    from defusedxml import ElementTree
except ImportError:
    ElementTree = None

logger = logging.getLogger(__name__)


class DecompressionBombWarning(RuntimeWarning):
    pass


class DecompressionBombError(Exception):
    pass


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


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

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

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


USE_CFFI_ACCESS = False
cffi: ModuleType | None
try:
    import cffi
except ImportError:
    cffi = None


def isImageType(t: Any) -> TypeGuard[Image]:
    """
    Checks if an object is an image object.

    .. warning::

       This function is for internal use only.

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


#
# Constants


# transpose
class Transpose(IntEnum):
    FLIP_LEFT_RIGHT = 0
    FLIP_TOP_BOTTOM = 1
    ROTATE_90 = 2
    ROTATE_180 = 3
    ROTATE_270 = 4
    TRANSPOSE = 5
    TRANSVERSE = 6


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


# resampling filters (also defined in Imaging.h)
class Resampling(IntEnum):
    NEAREST = 0
    BOX = 4
    BILINEAR = 2
    HAMMING = 5
    BICUBIC = 3
    LANCZOS = 1


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


# dithers
class Dither(IntEnum):
    NONE = 0
    ORDERED = 1  # Not yet implemented
    RASTERIZE = 2  # Not yet implemented
    FLOYDSTEINBERG = 3  # default


# palettes/quantizers
class Palette(IntEnum):
    WEB = 0
    ADAPTIVE = 1


class Quantize(IntEnum):
    MEDIANCUT = 0
    MAXCOVERAGE = 1
    FASTOCTREE = 2
    LIBIMAGEQUANT = 3


module = sys.modules[__name__]
for enum in (Transpose, Transform, Resampling, Dither, Palette, Quantize):
    for item in enum:
        setattr(module, item.name, item.value)


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


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

if TYPE_CHECKING:
    from . import ImageFile, PyAccess
ID: list[str] = []
OPEN: dict[
    str,
    tuple[
        Callable[[IO[bytes], str | bytes], ImageFile.ImageFile],
        Callable[[bytes], bool | str] | None,
    ],
] = {}
MIME: dict[str, str] = {}
SAVE: dict[str, Callable[[Image, IO[bytes], str | bytes], None]] = {}
SAVE_ALL: dict[str, Callable[[Image, IO[bytes], str | bytes], None]] = {}
EXTENSION: dict[str, str] = {}
DECODERS: dict[str, type[ImageFile.PyDecoder]] = {}
ENCODERS: dict[str, type[ImageFile.PyEncoder]] = {}

# --------------------------------------------------------------------
# Modes

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


def _conv_type_shape(im):
    m = ImageMode.getmode(im.mode)
    shape = (im.height, im.width)
    extra = len(m.bands)
    if extra != 1:
        shape += (extra,)
    return shape, m.typestr


MODES = [
    "1",
    "CMYK",
    "F",
    "HSV",
    "I",
    "I;16",
    "I;16B",
    "I;16L",
    "I;16N",
    "L",
    "LA",
    "La",
    "LAB",
    "P",
    "PA",
    "RGB",
    "RGBA",
    "RGBa",
    "RGBX",
    "YCbCr",
]

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


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

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


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

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


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

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


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

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


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

_initialized = 0


def preinit() -> None:
    """
    Explicitly loads BMP, GIF, JPEG, PPM and PPM file format drivers.

    It is called when opening or saving images.
    """

    global _initialized
    if _initialized >= 1:
        return

    try:
        from . import BmpImagePlugin

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

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

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

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

        assert PngImagePlugin
    except ImportError:
        pass

    _initialized = 1


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

    It is called when opening or saving images if :py:meth:`~preinit()` is
    insufficient, and by :py:meth:`~PIL.features.pilinfo`.
    """

    global _initialized
    if _initialized >= 2:
        return False

    parent_name = __name__.rpartition(".")[0]
    for plugin in _plugins:
        try:
            logger.debug("Importing %s", plugin)
            __import__(f"{parent_name}.{plugin}", globals(), locals(), [])
        except ImportError as e:
            logger.debug("Image: failed to import %s: %s", plugin, e)

    if OPEN or SAVE:
        _initialized = 2
        return True
    return False


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


def _getdecoder(
    mode: str, decoder_name: str, args: Any, extra: tuple[Any, ...] = ()
) -> core.ImagingDecoder | ImageFile.PyDecoder:
    # tweak arguments
    if args is None:
        args = ()
    elif not isinstance(args, tuple):
        args = (args,)

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

    try:
        # get decoder
        decoder = getattr(core, f"{decoder_name}_decoder")
    except AttributeError as e:
        msg = f"decoder {decoder_name} not available"
        raise OSError(msg) from e
    return decoder(mode, *args + extra)


def _getencoder(
    mode: str, encoder_name: str, args: Any, extra: tuple[Any, ...] = ()
) -> core.ImagingEncoder | ImageFile.PyEncoder:
    # tweak arguments
    if args is None:
        args = ()
    elif not isinstance(args, tuple):
        args = (args,)

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

    try:
        # get encoder
        encoder = getattr(core, f"{encoder_name}_encoder")
    except AttributeError as e:
        msg = f"encoder {encoder_name} not available"
        raise OSError(msg) from e
    return encoder(mode, *args + extra)


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


class _E:
    def __init__(self, scale, offset) -> None:
        self.scale = scale
        self.offset = offset

    def __neg__(self):
        return _E(-self.scale, -self.offset)

    def __add__(self, other):
        if isinstance(other, _E):
            return _E(self.scale + other.scale, self.offset + other.offset)
        return _E(self.scale, self.offset + other)

    __radd__ = __add__

    def __sub__(self, other):
        return self + -other

    def __rsub__(self, other):
        return other + -self

    def __mul__(self, other):
        if isinstance(other, _E):
            return NotImplemented
        return _E(self.scale * other, self.offset * other)

    __rmul__ = __mul__

    def __truediv__(self, other):
        if isinstance(other, _E):
            return NotImplemented
        return _E(self.scale / other, self.offset / other)


def _getscaleoffset(expr):
    a = expr(_E(1, 0))
    return (a.scale, a.offset) if isinstance(a, _E) else (0, a)


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


class SupportsGetData(Protocol):
    def getdata(
        self,
    ) -> tuple[Transform, Sequence[int]]: ...


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

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

    format: str | None = None
    format_description: str | None = None
    _close_exclusive_fp_after_loading = True

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

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

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

    @property
    def size(self) -> tuple[int, int]:
        return self._size

    @property
    def mode(self) -> str:
        return self._mode

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

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

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

    def _close_fp(self):
        if getattr(self, "_fp", False):
            if self._fp != self.fp:
                self._fp.close()
            self._fp = DeferredError(ValueError("Operation on closed image"))
        if self.fp:
            self.fp.close()

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

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

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

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

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

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

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

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

    def _dump(
        self, file: str | None = None, format: str | None = None, **options: Any
    ) -> str:
        suffix = ""
        if format:
            suffix = f".{format}"

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

        self.load()

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

        return filename

    def __eq__(self, other: object) -> bool:
        if self.__class__ is not other.__class__:
            return False
        assert isinstance(other, Image)
        return (
            self.mode == other.mode
            and self.size == other.size
            and self.info == other.info
            and self.getpalette() == other.getpalette()
            and self.tobytes() == other.tobytes()
        )

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

    def _repr_pretty_(self, p, cycle) -> None:
        """IPython plain text display support"""

        # Same as __repr__ but without unpredictable id(self),
        # to keep Jupyter notebook `text/plain` output stable.
        p.text(
            "<%s.%s image mode=%s size=%dx%d>"
            % (
                self.__class__.__module__,
                self.__class__.__name__,
                self.mode,
                self.size[0],
                self.size[1],
            )
        )

    def _repr_image(self, image_format: str, **kwargs: Any) -> bytes | None:
        """Helper function for iPython display hook.

        :param image_format: Image format.
        :returns: image as bytes, saved into the given format.
        """
        b = io.BytesIO()
        try:
            self.save(b, image_format, **kwargs)
        except Exception:
            return None
        return b.getvalue()

    def _repr_png_(self) -> bytes | None:
        """iPython display hook support for PNG format.

        :returns: PNG version of the image as bytes
        """
        return self._repr_image("PNG", compress_level=1)

    def _repr_jpeg_(self) -> bytes | None:
        """iPython display hook support for JPEG format.

        :returns: JPEG version of the image as bytes
        """
        return self._repr_image("JPEG")

    @property
    def __array_interface__(self):
        # numpy array interface support
        new = {"version": 3}
        try:
            if self.mode == "1":
                # Binary images need to be extended from bits to bytes
                # See: https://github.com/python-pillow/Pillow/issues/350
                new["data"] = self.tobytes("raw", "L")
            else:
                new["data"] = self.tobytes()
        except Exception as e:
            if not isinstance(e, (MemoryError, RecursionError)):
                try:
                    import numpy
                    from packaging.version import parse as parse_version
                except ImportError:
                    pass
                else:
                    if parse_version(numpy.__version__) < parse_version("1.23"):
                        warnings.warn(str(e))
            raise
        new["shape"], new["typestr"] = _conv_type_shape(self)
        return new

    def __getstate__(self):
        im_data = self.tobytes()  # load image first
        return [self.info, self.mode, self.size, self.getpalette(), im_data]

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

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

        .. warning::

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

        :param encoder_name: What encoder to use.  The default is to
                             use the standard "raw" encoder.

                             A list of C encoders can be seen under
                             codecs section of the function array in
                             :file:`_imaging.c`. Python encoders are
                             registered within the relevant plugins.
        :param args: Extra arguments to the encoder.
        :returns: A :py:class:`bytes` object.
        """

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

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

        self.load()

        if self.width == 0 or self.height == 0:
            return b""

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

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

        output = []
        while True:
            bytes_consumed, errcode, data = e.encode(bufsize)
            output.append(data)
            if errcode:
                break
        if errcode < 0:
            msg = f"encoder error {errcode} in tobytes"
            raise RuntimeError(msg)

        return b"".join(output)

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

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

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

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

    def frombytes(
        self, data: bytes | bytearray, decoder_name: str = "raw", *args: Any
    ) -> None:
        """
        Loads this image with pixel data from a bytes object.

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

        if self.width == 0 or self.height == 0:
            return

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

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

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

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

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

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

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

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

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

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

    def convert(
        self,
        mode: str | None = None,
        matrix: tuple[float, ...] | None = None,
        dither: Dither | None = None,
        palette: Palette = Palette.WEB,
        colors: int = 256,
    ) -> Image:
        """
        Returns a converted copy of this image. For the "P" mode, this
        method translates pixels through the palette.  If mode is
        omitted, a mode is chosen so that all information in the image
        and the palette can be represented without a palette.

        This supports all possible conversions between "L", "RGB" and "CMYK". The
        ``matrix`` argument only supports "L" and "RGB".

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

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

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

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

        When converting from "PA", if an "RGBA" palette is present, the alpha
        channel from the image will be used instead of the values from the palette.

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

        if mode in ("BGR;15", "BGR;16", "BGR;24"):
            deprecate(mode, 12)

        self.load()

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

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

                def convert_transparency(
                    m: tuple[float, ...], v: tuple[int, int, int]
                ) -> int:
                    value = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * 0.5
                    return max(0, min(255, int(value)))

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

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

        trns = None
        delete_trns = False
        # transparency handling
        if has_transparency:
            if (self.mode in ("1", "L", "I", "I;16") and mode in ("LA", "RGBA")) or (
                self.mode == "RGB" and mode in ("La", "LA", "RGBa", "RGBA")
            ):
                # Use transparent conversion to promote from transparent
                # color to an alpha channel.
                new_im = self._new(
                    self.im.convert_transparent(mode, self.info["transparency"])
                )
                del new_im.info["transparency"]
                return new_im
            elif self.mode in ("L", "RGB", "P") and mode in ("L", "RGB", "P"):
                t = self.info["transparency"]
                if isinstance(t, bytes):
                    # Dragons. This can't be represented by a single color
                    warnings.warn(
                        "Palette images with Transparency expressed in bytes should be "
                        "converted to RGBA images"
                    )
                    delete_trns = True
                else:
                    # get the new transparency color.
                    # use existing conversions
                    trns_im = new(self.mode, (1, 1))
                    if self.mode == "P":
                        trns_im.putpalette(self.palette)
                        if isinstance(t, tuple):
                            err = "Couldn't allocate a palette color for transparency"
                            try:
                                t = trns_im.palette.getcolor(t, self)
                            except ValueError as e:
                                if str(e) == "cannot allocate more than 256 colors":
                                    # If all 256 colors are in use,
                                    # then there is no need for transparency
                                    t = None
                                else:
                                    raise ValueError(err) from e
                    if t is None:
                        trns = None
                    else:
                        trns_im.putpixel((0, 0), t)

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

            elif self.mode == "P" and mode in ("LA", "PA", "RGBA"):
                t = self.info["transparency"]
                delete_trns = True

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

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

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

        if "LAB" in (self.mode, mode):
            other_mode = mode if self.mode == "LAB" else self.mode
            if other_mode in ("RGB", "RGBA", "RGBX"):
                from . import ImageCms

                srgb = ImageCms.createProfile("sRGB")
                lab = ImageCms.createProfile("LAB")
                profiles = [lab, srgb] if self.mode == "LAB" else [srgb, lab]
                transform = ImageCms.buildTransform(
                    profiles[0], profiles[1], self.mode, mode
                )
                return transform.apply(self)

        # colorspace conversion
        if dither is None:
            dither = Dither.FLOYDSTEINBERG

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

        new_im = self._new(im)
        if mode == "P" and palette != Palette.ADAPTIVE:
            from . import ImagePalette

            new_im.palette = ImagePalette.ImagePalette("RGB", im.getpalette("RGB"))
        if delete_trns:
            # crash fail if we leave a bytes transparency in an rgb/l mode.
            del new_im.info["transparency"]
        if trns is not None:
            if new_im.mode == "P" and new_im.palette:
                try:
                    new_im.info["transparency"] = new_im.palette.getcolor(trns, new_im)
                except ValueError as e:
                    del new_im.info["transparency"]
                    if str(e) != "cannot allocate more than 256 colors":
                        # If all 256 colors are in use,
                        # then there is no need for transparency
                        warnings.warn(
                            "Couldn't allocate palette entry for transparency"
                        )
            else:
                new_im.info["transparency"] = trns
        return new_im

    def quantize(
        self,
        colors: int = 256,
        method: int | None = None,
        kmeans: int = 0,
        palette=None,
        dither: Dither = Dither.FLOYDSTEINBERG,
    ) -> Image:
        """
        Convert the image to 'P' mode with the specified number
        of colors.

        :param colors: The desired number of colors, <= 256
        :param method: :data:`Quantize.MEDIANCUT` (median cut),
                       :data:`Quantize.MAXCOVERAGE` (maximum coverage),
                       :data:`Quantize.FASTOCTREE` (fast octree),
                       :data:`Quantize.LIBIMAGEQUANT` (libimagequant; check support
                       using :py:func:`PIL.features.check_feature` with
                       ``feature="libimagequant"``).

                       By default, :data:`Quantize.MEDIANCUT` will be used.

                       The exception to this is RGBA images. :data:`Quantize.MEDIANCUT`
                       and :data:`Quantize.MAXCOVERAGE` do not support RGBA images, so
                       :data:`Quantize.FASTOCTREE` is used by default instead.
        :param kmeans: Integer greater than or equal to zero.
        :param palette: Quantize to the palette of given
                        :py:class:`PIL.Image.Image`.
        :param dither: Dithering method, used when converting from
           mode "RGB" to "P" or from "RGB" or "L" to "1".
           Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG`
           (default).
        :returns: A new image
        """

        self.load()

        if method is None:
            # defaults:
            method = Quantize.MEDIANCUT
            if self.mode == "RGBA":
                method = Quantize.FASTOCTREE

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

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

        if kmeans < 0:
            msg = "kmeans must not be negative"
            raise ValueError(msg)

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

        from . import ImagePalette

        mode = im.im.getpalettemode()
        palette = im.im.getpalette(mode, mode)[: colors * len(mode)]
        im.palette = ImagePalette.ImagePalette(mode, palette)

        return im

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

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

    __copy__ = copy

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

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

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

        if box is None:
            return self.copy()

        if box[2] < box[0]:
            msg = "Coordinate 'right' is less than 'left'"
            raise ValueError(msg)
        elif box[3] < box[1]:
            msg = "Coordinate 'lower' is less than 'upper'"
            raise ValueError(msg)

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

    def _crop(
        self, im: core.ImagingCore, box: tuple[float, float, float, float]
    ) -> core.ImagingCore:
        """
        Returns a rectangular region from the core image object im.

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

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

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

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

        _decompression_bomb_check(absolute_values)

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

    def draft(
        self, mode: str | None, size: tuple[int, int] | None
    ) -> tuple[str, tuple[int, int, float, float]] | None:
        """
        Configures the image file loader so it returns a version of the
        image that as closely as possible matches the given mode and
        size. For example, you can use this method to convert a color
        JPEG to grayscale while loading it.

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

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

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

        :param mode: The requested mode.
        :param size: The requested size in pixels, as a 2-tuple:
           (width, height).
        """
        pass

    def _expand(self, xmargin: int, ymargin: int | None = None) -> Image:
        if ymargin is None:
            ymargin = xmargin
        self.load()
        return self._new(self.im.expand(xmargin, ymargin))

    if TYPE_CHECKING:
        from . import ImageFilter

    def filter(self, filter: ImageFilter.Filter | type[ImageFilter.Filter]) -> Image:
        """
        Filters this image using the given filter.  For a list of
        available filters, see the :py:mod:`~PIL.ImageFilter` module.

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

        from . import ImageFilter

        self.load()

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

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

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

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

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

    def getbbox(self, *, alpha_only: bool = True) -> tuple[int, int, int, int] | None:
        """
        Calculates the bounding box of the non-zero regions in the
        image.

        :param alpha_only: Optional flag, defaulting to ``True``.
           If ``True`` and the image has an alpha channel, trim transparent pixels.
           Otherwise, trim pixels when all channels are zero.
           Keyword-only argument.
        :returns: The bounding box is returned as a 4-tuple defining the
           left, upper, right, and lower pixel coordinate. See
           :ref:`coordinate-system`. If the image is completely empty, this
           method returns None.

        """

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

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

        The colors will be in the image's mode. For example, an RGB image will
        return a tuple of (red, green, blue) color values, and a P image will
        return the index of the color in the palette.

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

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

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

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

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

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

    def getextrema(self) -> tuple[float, float] | tuple[tuple[int, int], ...]:
        """
        Gets the minimum and maximum pixel values for each band in
        the image.

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

        self.load()
        if self.im.bands > 1:
            return tuple(self.im.getband(i).getextrema() for i in range(self.im.bands))
        return self.im.getextrema()

    def getxmp(self):
        """
        Returns a dictionary containing the XMP tags.
        Requires defusedxml to be installed.

        :returns: XMP tags in a dictionary.
        """

        def get_name(tag: str) -> str:
            return re.sub("^{[^}]+}", "", tag)

        def get_value(element):
            value = {get_name(k): v for k, v in element.attrib.items()}
            children = list(element)
            if children:
                for child in children:
                    name = get_name(child.tag)
                    child_value = get_value(child)
                    if name in value:
                        if not isinstance(value[name], list):
                            value[name] = [value[name]]
                        value[name].append(child_value)
                    else:
                        value[name] = child_value
            elif value:
                if element.text:
                    value["text"] = element.text
            else:
                return element.text
            return value

        if ElementTree is None:
            warnings.warn("XMP data cannot be read without defusedxml dependency")
            return {}
        if "xmp" not in self.info:
            return {}
        root = ElementTree.fromstring(self.info["xmp"].rstrip(b"\x00"))
        return {get_name(root.tag): get_value(root)}

    def getexif(self) -> Exif:
        """
        Gets EXIF data from the image.

        :returns: an :py:class:`~PIL.Image.Exif` object.
        """
        if self._exif is None:
            self._exif = Exif()
        elif self._exif._loaded:
            return self._exif
        self._exif._loaded = True

        exif_info = self.info.get("exif")
        if exif_info is None:
            if "Raw profile type exif" in self.info:
                exif_info = bytes.fromhex(
                    "".join(self.info["Raw profile type exif"].split("\n")[3:])
                )
            elif hasattr(self, "tag_v2"):
                self._exif.bigtiff = self.tag_v2._bigtiff
                self._exif.endian = self.tag_v2._endian
                self._exif.load_from_fp(self.fp, self.tag_v2._offset)
        if exif_info is not None:
            self._exif.load(exif_info)

        # XMP tags
        if ExifTags.Base.Orientation not in self._exif:
            xmp_tags = self.info.get("XML:com.adobe.xmp")
            if xmp_tags:
                match = re.search(r'tiff:Orientation(="|>)([0-9])', xmp_tags)
                if match:
                    self._exif[ExifTags.Base.Orientation] = int(match[2])

        return self._exif

    def _reload_exif(self) -> None:
        if self._exif is None or not self._exif._loaded:
            return
        self._exif._loaded = False
        self.getexif()

    def get_child_images(self) -> list[ImageFile.ImageFile]:
        child_images = []
        exif = self.getexif()
        ifds = []
        if ExifTags.Base.SubIFDs in exif:
            subifd_offsets = exif[ExifTags.Base.SubIFDs]
            if subifd_offsets:
                if not isinstance(subifd_offsets, tuple):
                    subifd_offsets = (subifd_offsets,)
                for subifd_offset in subifd_offsets:
                    ifds.append((exif._get_ifd_dict(subifd_offset), subifd_offset))
        ifd1 = exif.get_ifd(ExifTags.IFD.IFD1)
        if ifd1 and ifd1.get(513):
            ifds.append((ifd1, exif._info.next))

        offset = None
        for ifd, ifd_offset in ifds:
            current_offset = self.fp.tell()
            if offset is None:
                offset = current_offset

            fp = self.fp
            thumbnail_offset = ifd.get(513)
            if thumbnail_offset is not None:
                thumbnail_offset += getattr(self, "_exif_offset", 0)
                self.fp.seek(thumbnail_offset)
                data = self.fp.read(ifd.get(514))
                fp = io.BytesIO(data)

            with open(fp) as im:
                from . import TiffImagePlugin

                if thumbnail_offset is None and isinstance(
                    im, TiffImagePlugin.TiffImageFile
                ):
                    im._frame_pos = [ifd_offset]
                    im._seek(0)
                im.load()
                child_images.append(im)

        if offset is not None:
            self.fp.seek(offset)
        return child_images

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

        :returns: A capsule object.
        """

        self.load()
        return self.im.ptr

    def getpalette(self, rawmode: str | None = "RGB") -> list[int] | None:
        """
        Returns the image palette as a list.

        :param rawmode: The mode in which to return the palette. ``None`` will
           return the palette in its current mode.

           .. versionadded:: 9.1.0

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

        self.load()
        try:
            mode = self.im.getpalettemode()
        except ValueError:
            return None  # no palette
        if rawmode is None:
            rawmode = mode
        return list(self.im.getpalette(mode, rawmode))

    @property
    def has_transparency_data(self) -> bool:
        """
        Determine if an image has transparency data, whether in the form of an
        alpha channel, a palette with an alpha channel, or a "transparency" key
        in the info dictionary.

        Note the image might still appear solid, if all of the values shown
        within are opaque.

        :returns: A boolean.
        """
        return (
            self.mode in ("LA", "La", "PA", "RGBA", "RGBa")
            or (self.mode == "P" and self.palette.mode.endswith("A"))
            or "transparency" in self.info
        )

    def apply_transparency(self) -> None:
        """
        If a P mode image has a "transparency" key in the info dictionary,
        remove the key and instead apply the transparency to the palette.
        Otherwise, the image is unchanged.
        """
        if self.mode != "P" or "transparency" not in self.info:
            return

        from . import ImagePalette

        palette = self.getpalette("RGBA")
        assert palette is not None
        transparency = self.info["transparency"]
        if isinstance(transparency, bytes):
            for i, alpha in enumerate(transparency):
                palette[i * 4 + 3] = alpha
        else:
            palette[transparency * 4 + 3] = 0
        self.palette = ImagePalette.ImagePalette("RGBA", bytes(palette))
        self.palette.dirty = 1

        del self.info["transparency"]

    def getpixel(
        self, xy: tuple[int, int] | list[int]
    ) -> float | tuple[int, ...] | None:
        """
        Returns the pixel value at a given position.

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

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

    def getprojection(self) -> tuple[list[int], list[int]]:
        """
        Get projection to x and y axes

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

        self.load()
        x, y = self.im.getprojection()
        return list(x), list(y)

    def histogram(self, mask: Image | None = None, extrema=None) -> list[int]:
        """
        Returns a histogram for the image. The histogram is returned as a
        list of pixel counts, one for each pixel value in the source
        image. Counts are grouped into 256 bins for each band, even if
        the image has more than 8 bits per band. If the image has more
        than one band, the histograms for all bands are concatenated (for
        example, the histogram for an "RGB" image contains 768 values).

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        if isImageType(box):
            if mask is not None:
                msg = "If using second argument as mask, third argument must be None"
                raise ValueError(msg)
            # abbreviated paste(im, mask) syntax
            mask = box
            box = None
        assert not isinstance(box, Image)

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

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

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

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

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

        self._ensure_mutable()

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

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

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

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

        if not isinstance(source, (list, tuple)):
            msg = "Source must be a list or tuple"
            raise ValueError(msg)
        if not isinstance(dest, (list, tuple)):
            msg = "Destination must be a list or tuple"
            raise ValueError(msg)

        if len(source) == 4:
            overlay_crop_box = tuple(source)
        elif len(source) == 2:
            overlay_crop_box = tuple(source) + im.size
        else:
            msg = "Source must be a sequence of length 2 or 4"
            raise ValueError(msg)

        if not len(dest) == 2:
            msg = "Destination must be a sequence of length 2"
            raise ValueError(msg)
        if min(source) < 0:
            msg = "Source must be non-negative"
            raise ValueError(msg)

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

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

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

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

    def point(
        self,
        lut: Sequence[float] | Callable[[int], float] | ImagePointHandler,
        mode: str | None = None,
    ) -> Image:
        """
        Maps this image through a lookup table or function.

        :param lut: A lookup table, containing 256 (or 65536 if
           self.mode=="I" and mode == "L") values per band in the
           image.  A function can be used instead, it should take a
           single argument. The function is called once for each
           possible pixel value, and the resulting table is applied to
           all bands of the image.

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

               class Example(Image.ImagePointHandler):
                 def point(self, data):
                   # Return result
        :param mode: Output mode (default is same as input). This can only be used if
           the source image has mode "L" or "P", and the output has mode "1" or the
           source image mode is "I" and the output mode is "L".
        :returns: An :py:class:`~PIL.Image.Image` object.
        """

        self.load()

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

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

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

        if mode != "F":
            flatLut = [round(i) for i in flatLut]
        return self._new(self.im.point(flatLut, mode))

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

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

        self._ensure_mutable()

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

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

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

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

    def putdata(
        self,
        data: Sequence[float] | Sequence[Sequence[int]],
        scale: float = 1.0,
        offset: float = 0.0,
    ) -> None:
        """
        Copies pixel data from a flattened sequence object into the image. The
        values should start at the upper left corner (0, 0), continue to the
        end of the line, followed directly by the first value of the second
        line, and so on. Data will be read until either the image or the
        sequence ends. The scale and offset values are used to adjust the
        sequence values: **pixel = value*scale + offset**.

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

        self._ensure_mutable()

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

    def putpalette(self, data, rawmode="RGB") -> None:
        """
        Attaches a palette to this image.  The image must be a "P", "PA", "L"
        or "LA" image.

        The palette sequence must contain at most 256 colors, made up of one
        integer value for each channel in the raw mode.
        For example, if the raw mode is "RGB", then it can contain at most 768
        values, made up of red, green and blue values for the corresponding pixel
        index in the 256 colors.
        If the raw mode is "RGBA", then it can contain at most 1024 values,
        containing red, green, blue and alpha values.

        Alternatively, an 8-bit string may be used instead of an integer sequence.

        :param data: A palette sequence (either a list or a string).
        :param rawmode: The raw mode of the palette. Either "RGB", "RGBA", or a mode
           that can be transformed to "RGB" or "RGBA" (e.g. "R", "BGR;15", "RGBA;L").
        """
        from . import ImagePalette

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

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

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

        See:

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

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

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

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

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

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

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

        """
        from . import ImagePalette

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

        bands = 3
        palette_mode = "RGB"
        if source_palette is None:
            if self.mode == "P":
                self.load()
                palette_mode = self.im.getpalettemode()
                if palette_mode == "RGBA":
                    bands = 4
                source_palette = self.im.getpalette(palette_mode, palette_mode)
            else:  # L-mode
                source_palette = bytearray(i // 3 for i in range(768))

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

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

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

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

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

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

        mapping_palette = bytearray(new_positions)

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

        m_im.palette = ImagePalette.ImagePalette(
            palette_mode, palette=mapping_palette * bands
        )
        # possibly set palette dirty, then
        # m_im.putpalette(mapping_palette, 'L')  # converts to 'P'
        # or just force it.
        # UNDONE -- this is part of the general issue with palettes
        m_im.im.putpalette(palette_mode, palette_mode + ";L", m_im.palette.tobytes())

        m_im = m_im.convert("L")

        m_im.putpalette(palette_bytes, palette_mode)
        m_im.palette = ImagePalette.ImagePalette(palette_mode, palette=palette_bytes)

        if "transparency" in self.info:
            try:
                m_im.info["transparency"] = dest_map.index(self.info["transparency"])
            except ValueError:
                if "transparency" in m_im.info:
                    del m_im.info["transparency"]

        return m_im

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

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

    def resize(
        self,
        size: tuple[int, int],
        resample: int | None = None,
        box: tuple[float, float, float, float] | None = None,
        reducing_gap: float | None = None,
    ) -> Image:
        """
        Returns a resized copy of this image.

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

        if resample is None:
            type_special = ";" in self.mode
            resample = Resampling.NEAREST if type_special else Resampling.BICUBIC
        elif resample not in (
            Resampling.NEAREST,
            Resampling.BILINEAR,
            Resampling.BICUBIC,
            Resampling.LANCZOS,
            Resampling.BOX,
            Resampling.HAMMING,
        ):
            msg = f"Unknown resampling filter ({resample})."

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

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

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

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

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

        if self.mode in ["LA", "RGBA"] and resample != Resampling.NEAREST:
            im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode])
            im = im.resize(size, resample, box)
            return im.convert(self.mode)

        self.load()

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

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

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

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

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

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

        if self.mode in ["LA", "RGBA"]:
            im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode])
            im = im.reduce(factor, box)
            return im.convert(self.mode)

        self.load()

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

    def rotate(
        self,
        angle: float,
        resample: Resampling = Resampling.NEAREST,
        expand: int | bool = False,
        center: tuple[float, float] | None = None,
        translate: tuple[int, int] | None = None,
        fillcolor: float | tuple[float, ...] | str | None = None,
    ) -> Image:
        """
        Returns a rotated copy of this image.  This method returns a
        copy of this image, rotated the given number of degrees counter
        clockwise around its centre.

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

        angle = angle % 360.0

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

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

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

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

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

        w, h = self.size

        if translate is None:
            post_trans = (0, 0)
        else:
            post_trans = translate
        if center is None:
            center = (w / 2, h / 2)

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

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

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

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

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

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

    def save(
        self, fp: StrOrBytesPath | IO[bytes], format: str | None = None, **params: Any
    ) -> None:
        """
        Saves this image under the given filename.  If no format is
        specified, the format to use is determined from the filename
        extension, if possible.

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

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

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

        filename: str | bytes = ""
        open_fp = False
        if is_path(fp):
            filename = os.path.realpath(os.fspath(fp))
            open_fp = True
        elif fp == sys.stdout:
            try:
                fp = sys.stdout.buffer
            except AttributeError:
                pass
        if not filename and hasattr(fp, "name") and is_path(fp.name):
            # only set the name for metadata purposes
            filename = os.path.realpath(os.fspath(fp.name))

        # may mutate self!
        self._ensure_mutable()

        save_all = params.pop("save_all", False)
        self.encoderinfo = params
        self.encoderconfig: tuple[Any, ...] = ()

        preinit()

        filename_ext = os.path.splitext(filename)[1].lower()
        ext = filename_ext.decode() if isinstance(filename_ext, bytes) else filename_ext

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

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

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

        try:
            save_handler(self, fp, filename)
        except Exception:
            if open_fp:
                fp.close()
            if created:
                try:
                    os.remove(filename)
                except PermissionError:
                    pass
            raise
        if open_fp:
            fp.close()

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

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

        If defined, :attr:`~PIL.Image.Image.n_frames` refers to the
        number of available frames.

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

        # overridden by file handlers
        if frame != 0:
            msg = "no more images in file"
            raise EOFError(msg)

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

        This method calls :py:func:`PIL.ImageShow.show` internally. You can use
        :py:func:`PIL.ImageShow.register` to override its default behaviour.

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

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

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

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

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

        _show(self, title=title)

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

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

        :returns: A tuple containing bands.
        """

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

    def getchannel(self, channel: int | str) -> Image:
        """
        Returns an image containing a single channel of the source image.

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

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

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

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

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

        If defined, :attr:`~PIL.Image.Image.n_frames` refers to the
        number of available frames.

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

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

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

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

        provided_size = tuple(map(math.floor, size))

        def preserve_aspect_ratio() -> tuple[int, int] | None:
            def round_aspect(number, key):
                return max(min(math.floor(number), math.ceil(number), key=key), 1)

            x, y = provided_size
            if x >= self.width and y >= self.height:
                return None

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

        box = None
        final_size: tuple[int, int]
        if reducing_gap is not None:
            preserved_size = preserve_aspect_ratio()
            if preserved_size is None:
                return
            final_size = preserved_size

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

            # load() may have changed the size of the image
            preserved_size = preserve_aspect_ratio()
            if preserved_size is None:
                return
            final_size = preserved_size

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

            self.im = im.im
            self._size = final_size
            self._mode = self.im.mode

        self.readonly = 0
        self.pyaccess = None

    # FIXME: the different transform methods need further explanation
    # instead of bloating the method docs, add a separate chapter.
    def transform(
        self,
        size: tuple[int, int],
        method: Transform | ImageTransformHandler | SupportsGetData,
        data: Sequence[Any] | None = None,
        resample: int = Resampling.NEAREST,
        fill: int = 1,
        fillcolor: float | tuple[float, ...] | str | None = None,
    ) -> Image:
        """
        Transforms this image.  This method creates a new image with the
        given size, and the same mode as the original, and copies data
        to the new image using the given transform.

        :param size: The output size in pixels, as a 2-tuple:
           (width, height).
        :param method: The transformation method.  This is one of
          :py:data:`Transform.EXTENT` (cut out a rectangular subregion),
          :py:data:`Transform.AFFINE` (affine transform),
          :py:data:`Transform.PERSPECTIVE` (perspective transform),
          :py:data:`Transform.QUAD` (map a quadrilateral to a rectangle), or
          :py:data:`Transform.MESH` (map a number of source quadrilaterals
          in one operation).

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

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

          Implementations of :py:class:`~PIL.Image.ImageTransformHandler`
          for some of the :py:class:`Transform` methods are provided
          in :py:mod:`~PIL.ImageTransform`.

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

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

        if self.mode in ("LA", "RGBA") and resample != Resampling.NEAREST:
            return (
                self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode])
                .transform(size, method, data, resample, fill, fillcolor)
                .convert(self.mode)
            )

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

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

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

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

        return im

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

        if method == Transform.AFFINE:
            data = data[:6]

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

        elif method == Transform.PERSPECTIVE:
            data = data[:8]

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

        else:
            msg = "unknown transformation method"
            raise ValueError(msg)

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

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

        image.load()

        self.load()

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

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

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

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

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

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

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

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

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

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

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


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


class ImagePointHandler:
    """
    Used as a mixin by point transforms
    (for use with :py:meth:`~PIL.Image.Image.point`)
    """

    @abc.abstractmethod
    def point(self, im: Image) -> Image:
        pass


class ImageTransformHandler:
    """
    Used as a mixin by geometry transforms
    (for use with :py:meth:`~PIL.Image.Image.transform`)
    """

    @abc.abstractmethod
    def transform(
        self,
        size: tuple[int, int],
        image: Image,
        **options: Any,
    ) -> Image:
        pass


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

#
# Debugging


def _wedge() -> Image:
    """Create grayscale wedge (for debugging only)"""

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


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

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

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


def new(
    mode: str,
    size: tuple[int, int] | list[int],
    color: float | tuple[float, ...] | str | None = 0,
) -> Image:
    """
    Creates a new image with the given mode and size.

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

    if mode in ("BGR;15", "BGR;16", "BGR;24"):
        deprecate(mode, 12)

    _check_size(size)

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

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

        from . import ImageColor

        color = ImageColor.getcolor(color, mode)

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

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


def frombytes(
    mode: str,
    size: tuple[int, int],
    data: bytes | bytearray,
    decoder_name: str = "raw",
    *args: Any,
) -> Image:
    """
    Creates a copy of an image memory from pixel data in a buffer.

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

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

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

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

    _check_size(size)

    im = new(mode, size)
    if im.width != 0 and im.height != 0:
        decoder_args: Any = args
        if len(decoder_args) == 1 and isinstance(decoder_args[0], tuple):
            # may pass tuple instead of argument list
            decoder_args = decoder_args[0]

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

        im.frombytes(data, decoder_name, decoder_args)
    return im


def frombuffer(
    mode: str, size: tuple[int, int], data, decoder_name: str = "raw", *args: Any
) -> Image:
    """
    Creates an image memory referencing pixel data in a byte buffer.

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

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

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

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

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

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

    .. versionadded:: 1.1.4
    """

    _check_size(size)

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

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

                im.palette = ImagePalette.ImagePalette("RGB", im.im.getpalette("RGB"))
            im.readonly = 1
            return im

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


class SupportsArrayInterface(Protocol):
    """
    An object that has an ``__array_interface__`` dictionary.
    """

    @property
    def __array_interface__(self) -> dict[str, Any]:
        raise NotImplementedError()


def fromarray(obj: SupportsArrayInterface, mode: str | None = None) -> Image:
    """
    Creates an image memory from an object exporting the array interface
    (using the buffer protocol)::

      from PIL import Image
      import numpy as np
      a = np.zeros((5, 5))
      im = Image.fromarray(a)

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

    In the case of NumPy, be aware that Pillow modes do not always correspond
    to NumPy dtypes. Pillow modes only offer 1-bit pixels, 8-bit pixels,
    32-bit signed integer pixels, and 32-bit floating point pixels.

    Pillow images can also be converted to arrays::

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

    When converting Pillow images to arrays however, only pixel values are
    transferred. This means that P and PA mode images will lose their palette.

    :param obj: Object with array interface
    :param mode: Optional mode to use when reading ``obj``. Will be determined from
      type if ``None``.

      This will not be used to convert the data after reading, but will be used to
      change how the data is read::

        from PIL import Image
        import numpy as np
        a = np.full((1, 1), 300)
        im = Image.fromarray(a, mode="L")
        im.getpixel((0, 0))  # 44
        im = Image.fromarray(a, mode="RGB")
        im.getpixel((0, 0))  # (44, 1, 0)

      See: :ref:`concept-modes` for general information about modes.
    :returns: An image object.

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

    size = 1 if ndim == 1 else shape[1], shape[0]
    if strides is not None:
        if hasattr(obj, "tobytes"):
            obj = obj.tobytes()
        elif hasattr(obj, "tostring"):
            obj = obj.tostring()
        else:
            msg = "'strides' requires either tobytes() or tostring()"
            raise ValueError(msg)

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


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

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


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

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


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


def _decompression_bomb_check(size: tuple[int, int]) -> None:
    if MAX_IMAGE_PIXELS is None:
        return

    pixels = max(1, size[0]) * max(1, size[1])

    if pixels > 2 * MAX_IMAGE_PIXELS:
        msg = (
            f"Image size ({pixels} pixels) exceeds limit of {2 * MAX_IMAGE_PIXELS} "
            "pixels, could be decompression bomb DOS attack."
        )
        raise DecompressionBombError(msg)

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


def open(
    fp: StrOrBytesPath | IO[bytes],
    mode: Literal["r"] = "r",
    formats: list[str] | tuple[str, ...] | None = None,
) -> ImageFile.ImageFile:
    """
    Opens and identifies the given image file.

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

    :param fp: A filename (string), os.PathLike object or a file object.
       The file object must implement ``file.read``,
       ``file.seek``, and ``file.tell`` methods,
       and be opened in binary mode. The file object will also seek to zero
       before reading.
    :param mode: The mode.  If given, this argument must be "r".
    :param formats: A list or tuple of formats to attempt to load the file in.
       This can be used to restrict the set of formats checked.
       Pass ``None`` to try all supported formats. You can print the set of
       available formats by running ``python3 -m PIL`` or using
       the :py:func:`PIL.features.pilinfo` function.
    :returns: An :py:class:`~PIL.Image.Image` object.
    :exception FileNotFoundError: If the file cannot be found.
    :exception PIL.UnidentifiedImageError: If the image cannot be opened and
       identified.
    :exception ValueError: If the ``mode`` is not "r", or if a ``StringIO``
       instance is used for ``fp``.
    :exception TypeError: If ``formats`` is not ``None``, a list or a tuple.
    """

    if mode != "r":
        msg = f"bad mode {repr(mode)}"  # type: ignore[unreachable]
        raise ValueError(msg)
    elif isinstance(fp, io.StringIO):
        msg = (  # type: ignore[unreachable]
            "StringIO cannot be used to open an image. "
            "Binary data must be used instead."
        )
        raise ValueError(msg)

    if formats is None:
        formats = ID
    elif not isinstance(formats, (list, tuple)):
        msg = "formats must be a list or tuple"  # type: ignore[unreachable]
        raise TypeError(msg)

    exclusive_fp = False
    filename: str | bytes = ""
    if is_path(fp):
        filename = os.path.realpath(os.fspath(fp))

    if filename:
        fp = builtins.open(filename, "rb")
        exclusive_fp = True
    else:
        fp = cast(IO[bytes], fp)

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

    prefix = fp.read(16)

    preinit()

    accept_warnings: list[str] = []

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

    im = _open_core(fp, filename, prefix, formats)

    if im is None and formats is ID:
        checked_formats = ID.copy()
        if init():
            im = _open_core(
                fp,
                filename,
                prefix,
                tuple(format for format in formats if format not in checked_formats),
            )

    if im:
        im._exclusive_fp = exclusive_fp
        return im

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


#
# Image processing.


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

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

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


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

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

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

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


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

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

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


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

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

    return image.point(args[0])


def merge(mode: str, bands: Sequence[Image]) -> Image:
    """
    Merge a set of single band images into a new multiband image.

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

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


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


def register_open(
    id: str,
    factory: Callable[[IO[bytes], str | bytes], ImageFile.ImageFile],
    accept: Callable[[bytes], bool | str] | None = None,
) -> None:
    """
    Register an image file plugin.  This function should not be used
    in application code.

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


def register_mime(id: str, mimetype: str) -> None:
    """
    Registers an image MIME type by populating ``Image.MIME``. This function
    should not be used in application code.

    ``Image.MIME`` provides a mapping from image format identifiers to mime
    formats, but :py:meth:`~PIL.ImageFile.ImageFile.get_format_mimetype` can
    provide a different result for specific images.

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


def register_save(
    id: str, driver: Callable[[Image, IO[bytes], str | bytes], None]
) -> None:
    """
    Registers an image save function.  This function should not be
    used in application code.

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


def register_save_all(
    id: str, driver: Callable[[Image, IO[bytes], str | bytes], None]
) -> None:
    """
    Registers an image function to save all the frames
    of a multiframe format.  This function should not be
    used in application code.

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


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

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


def register_extensions(id: str, extensions: list[str]) -> None:
    """
    Registers image extensions.  This function should not be
    used in application code.

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


def registered_extensions() -> dict[str, str]:
    """
    Returns a dictionary containing all file extensions belonging
    to registered plugins
    """
    init()
    return EXTENSION


def register_decoder(name: str, decoder: type[ImageFile.PyDecoder]) -> None:
    """
    Registers an image decoder.  This function should not be
    used in application code.

    :param name: The name of the decoder
    :param decoder: An ImageFile.PyDecoder object

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


def register_encoder(name: str, encoder: type[ImageFile.PyEncoder]) -> None:
    """
    Registers an image encoder.  This function should not be
    used in application code.

    :param name: The name of the encoder
    :param encoder: An ImageFile.PyEncoder object

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


# --------------------------------------------------------------------
# Simple display support.


def _show(image: Image, **options: Any) -> None:
    from . import ImageShow

    ImageShow.show(image, **options)


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


def effect_mandelbrot(
    size: tuple[int, int], extent: tuple[float, float, float, float], quality: int
) -> Image:
    """
    Generate a Mandelbrot set covering the given extent.

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


def effect_noise(size: tuple[int, int], sigma: float) -> Image:
    """
    Generate Gaussian noise centered around 128.

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


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

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


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

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


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


def _apply_env_variables(env: dict[str, str] | None = None) -> None:
    env_dict = env if env is not None else os.environ

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

        var = env_dict[var_name].lower()

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

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

        try:
            setter(var_int)
        except ValueError as e:
            warnings.warn(f"{var_name}: {e}")


_apply_env_variables()
atexit.register(core.clear_cache)


if TYPE_CHECKING:
    _ExifBase = MutableMapping[int, Any]
else:
    _ExifBase = MutableMapping


class Exif(_ExifBase):
    """
    This class provides read and write access to EXIF image data::

      from PIL import Image
      im = Image.open("exif.png")
      exif = im.getexif()  # Returns an instance of this class

    Information can be read and written, iterated over or deleted::

      print(exif[274])  # 1
      exif[274] = 2
      for k, v in exif.items():
        print("Tag", k, "Value", v)  # Tag 274 Value 2
      del exif[274]

    To access information beyond IFD0, :py:meth:`~PIL.Image.Exif.get_ifd`
    returns a dictionary::

      from PIL import ExifTags
      im = Image.open("exif_gps.jpg")
      exif = im.getexif()
      gps_ifd = exif.get_ifd(ExifTags.IFD.GPSInfo)
      print(gps_ifd)

    Other IFDs include ``ExifTags.IFD.Exif``, ``ExifTags.IFD.Makernote``,
    ``ExifTags.IFD.Interop`` and ``ExifTags.IFD.IFD1``.

    :py:mod:`~PIL.ExifTags` also has enum classes to provide names for data::

      print(exif[ExifTags.Base.Software])  # PIL
      print(gps_ifd[ExifTags.GPS.GPSDateStamp])  # 1999:99:99 99:99:99
    """

    endian = None
    bigtiff = False
    _loaded = False

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

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

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

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

            info = TiffImagePlugin.ImageFileDirectory_v2(self.head, group=group)
            info.load(self.fp)
            return self._fixup_dict(info)

    def _get_head(self):
        version = b"\x2B" if self.bigtiff else b"\x2A"
        if self.endian == "<":
            head = b"II" + version + b"\x00" + o32le(8)
        else:
            head = b"MM\x00" + version + o32be(8)
        if self.bigtiff:
            head += o32le(8) if self.endian == "<" else o32be(8)
            head += b"\x00\x00\x00\x00"
        return head

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

        # The EXIF record consists of a TIFF file embedded in a JPEG
        # application marker (!).
        if data == self._loaded_exif:
            return
        self._loaded_exif = data
        self._data.clear()
        self._hidden_data.clear()
        self._ifds.clear()
        if data and data.startswith(b"Exif\x00\x00"):
            data = data[6:]
        if not data:
            self._info = None
            return

        self.fp = io.BytesIO(data)
        self.head = self.fp.read(8)
        # process dictionary
        from . import TiffImagePlugin

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

    def load_from_fp(self, fp, offset=None):
        self._loaded_exif = None
        self._data.clear()
        self._hidden_data.clear()
        self._ifds.clear()

        # process dictionary
        from . import TiffImagePlugin

        self.fp = fp
        if offset is not None:
            self.head = self._get_head()
        else:
            self.head = self.fp.read(8)
        self._info = TiffImagePlugin.ImageFileDirectory_v2(self.head)
        if self.endian is None:
            self.endian = self._info._endian
        if offset is None:
            offset = self._info.next
        self.fp.tell()
        self.fp.seek(offset)
        self._info.load(self.fp)

    def _get_merged_dict(self):
        merged_dict = dict(self)

        # get EXIF extension
        if ExifTags.IFD.Exif in self:
            ifd = self._get_ifd_dict(self[ExifTags.IFD.Exif], ExifTags.IFD.Exif)
            if ifd:
                merged_dict.update(ifd)

        # GPS
        if ExifTags.IFD.GPSInfo in self:
            merged_dict[ExifTags.IFD.GPSInfo] = self._get_ifd_dict(
                self[ExifTags.IFD.GPSInfo], ExifTags.IFD.GPSInfo
            )

        return merged_dict

    def tobytes(self, offset: int = 8) -> bytes:
        from . import TiffImagePlugin

        head = self._get_head()
        ifd = TiffImagePlugin.ImageFileDirectory_v2(ifh=head)
        for tag, value in self.items():
            if tag in [
                ExifTags.IFD.Exif,
                ExifTags.IFD.GPSInfo,
            ] and not isinstance(value, dict):
                value = self.get_ifd(tag)
                if (
                    tag == ExifTags.IFD.Exif
                    and ExifTags.IFD.Interop in value
                    and not isinstance(value[ExifTags.IFD.Interop], dict)
                ):
                    value = value.copy()
                    value[ExifTags.IFD.Interop] = self.get_ifd(ExifTags.IFD.Interop)
            ifd[tag] = value
        return b"Exif\x00\x00" + head + ifd.tobytes(offset)

    def get_ifd(self, tag):
        if tag not in self._ifds:
            if tag == ExifTags.IFD.IFD1:
                if self._info is not None and self._info.next != 0:
                    self._ifds[tag] = self._get_ifd_dict(self._info.next)
            elif tag in [ExifTags.IFD.Exif, ExifTags.IFD.GPSInfo]:
                offset = self._hidden_data.get(tag, self.get(tag))
                if offset is not None:
                    self._ifds[tag] = self._get_ifd_dict(offset, tag)
            elif tag in [ExifTags.IFD.Interop, ExifTags.IFD.Makernote]:
                if ExifTags.IFD.Exif not in self._ifds:
                    self.get_ifd(ExifTags.IFD.Exif)
                tag_data = self._ifds[ExifTags.IFD.Exif][tag]
                if tag == ExifTags.IFD.Makernote:
                    from .TiffImagePlugin import ImageFileDirectory_v2

                    if tag_data[:8] == b"FUJIFILM":
                        ifd_offset = i32le(tag_data, 8)
                        ifd_data = tag_data[ifd_offset:]

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

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

                            if not data:
                                continue

                            makernote[ifd_tag] = handler(
                                ImageFileDirectory_v2(), data, False
                            )
                        self._ifds[tag] = dict(self._fixup_dict(makernote))
                    elif self.get(0x010F) == "Nintendo":
                        makernote = {}
                        for i in range(0, struct.unpack(">H", tag_data[:2])[0]):
                            ifd_tag, typ, count, data = struct.unpack(
                                ">HHL4s", tag_data[i * 12 + 2 : (i + 1) * 12 + 2]
                            )
                            if ifd_tag == 0x1101:
                                # CameraInfo
                                (offset,) = struct.unpack(">L", data)
                                self.fp.seek(offset)

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

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

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

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

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

                                makernote = {0x1101: dict(self._fixup_dict(camerainfo))}
                        self._ifds[tag] = makernote
                else:
                    # Interop
                    self._ifds[tag] = self._get_ifd_dict(tag_data, tag)
        ifd = self._ifds.get(tag, {})
        if tag == ExifTags.IFD.Exif and self._hidden_data:
            ifd = {
                k: v
                for (k, v) in ifd.items()
                if k not in (ExifTags.IFD.Interop, ExifTags.IFD.Makernote)
            }
        return ifd

    def hide_offsets(self) -> None:
        for tag in (ExifTags.IFD.Exif, ExifTags.IFD.GPSInfo):
            if tag in self:
                self._hidden_data[tag] = self[tag]
                del self[tag]

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

        return str(self._data)

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

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

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

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

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

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

```
--- END FILE ---

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

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

Here is an example:

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

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
[ISSUE]
**Title:** AttributeError: 'PIL.Image' object has no attribute 'WARN_POSSIBLE_FORMATS' when enabling verbose format warnings

**Description:**
Attempting to enable verbose warnings for possible image formats results in an `AttributeError`. This prevents developers from receiving detailed warnings when opening images with unrecognized formats.

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

# Attempt to enable verbose format warnings
Image.WARN_POSSIBLE_FORMATS = True

# Try opening an invalid image to trigger a warning
im = io.BytesIO(b"")
with warnings.catch_warnings(record=True) as w:
    with Image.open(im):
        pass
```

**Expected Behavior:**
Setting `Image.WARN_POSSIBLE_FORMATS` to `True` should enable verbose warnings when attempting to open images with potentially unsupported or unrecognized formats. This should allow developers to receive `UserWarning` messages detailing the issues encountered during image opening.

**Actual Behavior:**
Assigning `True` to `Image.WARN_POSSIBLE_FORMATS` raises an `AttributeError`:
```
AttributeError: <module 'PIL.Image' from '.../PIL/Image.py'> has no attribute 'WARN_POSSIBLE_FORMATS'
```
This error occurs because the `WARN_POSSIBLE_FORMATS` attribute does not exist in the `PIL.Image` module, preventing the intended verbose warning functionality.

[/ISSUE]
{
    "\u001b[1mTestImage.test_image_modes_success[1]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_image_modes_success[CMYK]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_image_modes_success[F]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_image_modes_success[HSV]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_image_modes_success[I]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_image_modes_success[I;16]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_image_modes_success[I;16B]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_image_modes_success[I;16L]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_image_modes_success[I;16N]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_image_modes_success[L]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_image_modes_success[LA]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_image_modes_success[La]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_image_modes_success[LAB]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_image_modes_success[P]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_image_modes_success[PA]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_image_modes_success[RGB]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_image_modes_success[RGBA]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_image_modes_success[RGBa]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_image_modes_success[RGBX]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_image_modes_success[YCbCr]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_image_modes_success[BGR;15]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_image_modes_success[BGR;16]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_image_modes_success[BGR;24]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_image_modes_fail[]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_image_modes_fail[bad]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_image_modes_fail[very very long]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_exception_inheritance\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_sanity\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_repr_pretty\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_open_formats\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_open_verbose_failure\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_width_height\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_set_mode\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_invalid_image\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_bad_mode\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_stringio\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_fp_name\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_tempfile\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_unknown_extension\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_internals\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_readonly_save\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_dump\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_comparison_with_other_type\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_expand_x\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_expand_xy\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_getbands\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_getchannel_wrong_params\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_getchannel\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_getbbox\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_ne\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_alpha_composite\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_alpha_inplace\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_register_open_duplicates\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_registered_extensions_uninitialized\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_registered_extensions\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_effect_mandelbrot\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_effect_mandelbrot_bad_arguments\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_effect_noise\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_effect_spread\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_effect_spread_zero\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_check_size\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_empty_image[size0]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_empty_image[size1]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_storage_neg\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_one_item_tuple\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_linear_gradient_wrong_mode\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_linear_gradient[L]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_linear_gradient[P]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_linear_gradient[I]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_linear_gradient[F]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_radial_gradient_wrong_mode\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_radial_gradient[L]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_radial_gradient[P]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_radial_gradient[I]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_radial_gradient[F]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_register_extensions\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_remap_palette\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_remap_palette_transparency\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test__new\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_p_from_rgb_rgba[RGB-#DDEEFF]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_p_from_rgb_rgba[RGB-color1]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_p_from_rgb_rgba[RGBA-color2]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_no_resource_warning_on_save\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_no_new_file_on_error\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_load_on_nonexclusive_multiframe\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_empty_exif\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_exif_jpeg\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_exif_webp\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_exif_png\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_exif_interop\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_exif_ifd1\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_exif_ifd\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_exif_load_from_fp\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_exif_hide_offsets\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_empty_xmp\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_getxmp_padded\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_zero_tobytes[size0]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_zero_tobytes[size1]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_zero_tobytes[size2]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_zero_frombytes[size0]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_zero_frombytes[size1]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_zero_frombytes[size2]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_has_transparency_data\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_apply_transparency\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_constants\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_overrun[fli_overrun.bin]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_overrun[sgi_overrun.bin]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_overrun[sgi_overrun_expandrow.bin]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_overrun[sgi_overrun_expandrow2.bin]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_overrun[pcx_overrun.bin]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_overrun[pcx_overrun2.bin]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_overrun[ossfuzz-4836216264589312.pcx]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_overrun[01r_00.pcx]\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_fli_overrun2\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_exit_fp\u001b[0m": "PASSED",
    "\u001b[1mTestImage.test_close_graceful\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_constructor[1]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_constructor[CMYK]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_constructor[F]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_constructor[HSV]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_constructor[I]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_constructor[I;16]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_constructor[I;16B]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_constructor[I;16L]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_constructor[I;16N]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_constructor[L]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_constructor[LA]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_constructor[La]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_constructor[LAB]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_constructor[P]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_constructor[PA]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_constructor[RGB]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_constructor[RGBA]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_constructor[RGBa]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_constructor[RGBX]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_constructor[YCbCr]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_constructor[BGR;15]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_constructor[BGR;16]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_constructor[BGR;24]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_method[1]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_method[CMYK]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_method[F]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_method[HSV]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_method[I]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_method[I;16]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_method[I;16B]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_method[I;16L]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_method[I;16N]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_method[L]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_method[LA]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_method[La]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_method[LAB]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_method[P]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_method[PA]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_method[RGB]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_method[RGBA]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_method[RGBa]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_method[RGBX]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_method[YCbCr]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_method[BGR;15]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_method[BGR;16]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_roundtrip_bytes_method[BGR;24]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_getdata_putdata[1]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_getdata_putdata[CMYK]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_getdata_putdata[F]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_getdata_putdata[HSV]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_getdata_putdata[I]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_getdata_putdata[I;16]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_getdata_putdata[I;16B]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_getdata_putdata[I;16L]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_getdata_putdata[I;16N]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_getdata_putdata[L]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_getdata_putdata[LA]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_getdata_putdata[La]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_getdata_putdata[LAB]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_getdata_putdata[P]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_getdata_putdata[PA]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_getdata_putdata[RGB]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_getdata_putdata[RGBA]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_getdata_putdata[RGBa]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_getdata_putdata[RGBX]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_getdata_putdata[YCbCr]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_getdata_putdata[BGR;15]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_getdata_putdata[BGR;16]\u001b[0m": "PASSED",
    "\u001b[1mTestImageBytes.test_getdata_putdata[BGR;24]\u001b[0m": "PASSED",
    "\u001b[1mTestRegistry.test_encode_registry\u001b[0m": "PASSED",
    "\u001b[1mTestRegistry.test_encode_registry_fail\u001b[0m": "PASSED"
}
diff --git a/src/PIL/Image.py b/src/PIL/Image.py
index 970437e9a..d41c06523 100644
--- a/src/PIL/Image.py
+++ b/src/PIL/Image.py
@@ -85,6 +85,8 @@ class DecompressionBombError(Exception):
     pass
 
 
+WARN_POSSIBLE_FORMATS: bool = False
+
 # Limit to around a quarter gigabyte for a 24-bit (3 bpp) image
 MAX_IMAGE_PIXELS: int | None = int(1024 * 1024 * 1024 // 4 // 3)
 
@@ -3441,7 +3443,7 @@ def open(
 
     preinit()
 
-    accept_warnings: list[str] = []
+    warning_messages: list[str] = []
 
     def _open_core(
         fp: IO[bytes],
@@ -3457,17 +3459,15 @@ def open(
                 factory, accept = OPEN[i]
                 result = not accept or accept(prefix)
                 if isinstance(result, str):
-                    accept_warnings.append(result)
+                    warning_messages.append(result)
                 elif result:
                     fp.seek(0)
                     im = factory(fp, filename)
                     _decompression_bomb_check(im.size)
                     return im
-            except (SyntaxError, IndexError, TypeError, struct.error):
-                # Leave disabled by default, spams the logs with image
-                # opening failures that are entirely expected.
-                # logger.debug("", exc_info=True)
-                continue
+            except (SyntaxError, IndexError, TypeError, struct.error) as e:
+                if WARN_POSSIBLE_FORMATS:
+                    warning_messages.append(i + " opening failed. " + str(e))
             except BaseException:
                 if exclusive_fp:
                     fp.close()
@@ -3492,7 +3492,7 @@ def open(
 
     if exclusive_fp:
         fp.close()
-    for message in accept_warnings:
+    for message in warning_messages:
         warnings.warn(message)
     msg = "cannot identify image file %r" % (filename if filename else fp)
     raise UnidentifiedImageError(msg)
 

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

Your response format must follow the template below:
<think>
Your thoughts or/and draft, like working through an exercise on scratch paper. Be as casual and as long as you want until you are confident to generate a correct solution.
</think>
<solution>
Final solution presented to the user.
</solution>
system
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** AttributeError: 'PIL.Image' object has no attribute 'WARN_POSSIBLE_FORMATS' when enabling verbose format warnings

**Description:**
Attempting to enable verbose warnings for possible image formats results in an `AttributeError`. This prevents developers from receiving detailed warnings when opening images with unrecognized formats.

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

# Attempt to enable verbose format warnings
Image.WARN_POSSIBLE_FORMATS = True

# Try opening an invalid image to trigger a warning
im = io.BytesIO(b"")
with warnings.catch_warnings(record=True) as w:
    with Image.open(im):
        pass
```

**Expected Behavior:**
Setting `Image.WARN_POSSIBLE_FORMATS` to `True` should enable verbose warnings when attempting to open images with potentially unsupported or unrecognized formats. This should allow developers to receive `UserWarning` messages detailing the issues encountered during image opening.

**Actual Behavior:**
Assigning `True` to `Image.WARN_POSSIBLE_FORMATS` raises an `AttributeError`:
```
AttributeError: <module 'PIL.Image' from '.../PIL/Image.py'> has no attribute 'WARN_POSSIBLE_FORMATS'
```
This error occurs because the `WARN_POSSIBLE_FORMATS` attribute does not exist in the `PIL.Image` module, preventing the intended verbose warning functionality.

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

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

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

from __future__ import annotations

import abc
import atexit
import builtins
import io
import logging
import math
import os
import re
import struct
import sys
import tempfile
import warnings
from collections.abc import Callable, MutableMapping
from enum import IntEnum
from types import ModuleType
from typing import (
    IO,
    TYPE_CHECKING,
    Any,
    Literal,
    Protocol,
    Sequence,
    Tuple,
    cast,
)

# VERSION was removed in Pillow 6.0.0.
# PILLOW_VERSION was removed in Pillow 9.0.0.
# Use __version__ instead.
from . import (
    ExifTags,
    ImageMode,
    TiffTags,
    UnidentifiedImageError,
    __version__,
    _plugins,
)
from ._binary import i32le, o32be, o32le
from ._deprecate import deprecate
from ._typing import StrOrBytesPath, TypeGuard
from ._util import DeferredError, is_path

ElementTree: ModuleType | None
try:
    from defusedxml import ElementTree
except ImportError:
    ElementTree = None

logger = logging.getLogger(__name__)


class DecompressionBombWarning(RuntimeWarning):
    pass


class DecompressionBombError(Exception):
    pass


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


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

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

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


USE_CFFI_ACCESS = False
cffi: ModuleType | None
try:
    import cffi
except ImportError:
    cffi = None


def isImageType(t: Any) -> TypeGuard[Image]:
    """
    Checks if an object is an image object.

    .. warning::

       This function is for internal use only.

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


#
# Constants


# transpose
class Transpose(IntEnum):
    FLIP_LEFT_RIGHT = 0
    FLIP_TOP_BOTTOM = 1
    ROTATE_90 = 2
    ROTATE_180 = 3
    ROTATE_270 = 4
    TRANSPOSE = 5
    TRANSVERSE = 6


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


# resampling filters (also defined in Imaging.h)
class Resampling(IntEnum):
    NEAREST = 0
    BOX = 4
    BILINEAR = 2
    HAMMING = 5
    BICUBIC = 3
    LANCZOS = 1


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


# dithers
class Dither(IntEnum):
    NONE = 0
    ORDERED = 1  # Not yet implemented
    RASTERIZE = 2  # Not yet implemented
    FLOYDSTEINBERG = 3  # default


# palettes/quantizers
class Palette(IntEnum):
    WEB = 0
    ADAPTIVE = 1


class Quantize(IntEnum):
    MEDIANCUT = 0
    MAXCOVERAGE = 1
    FASTOCTREE = 2
    LIBIMAGEQUANT = 3


module = sys.modules[__name__]
for enum in (Transpose, Transform, Resampling, Dither, Palette, Quantize):
    for item in enum:
        setattr(module, item.name, item.value)


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


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

if TYPE_CHECKING:
    from . import ImageFile, PyAccess
ID: list[str] = []
OPEN: dict[
    str,
    tuple[
        Callable[[IO[bytes], str | bytes], ImageFile.ImageFile],
        Callable[[bytes], bool | str] | None,
    ],
] = {}
MIME: dict[str, str] = {}
SAVE: dict[str, Callable[[Image, IO[bytes], str | bytes], None]] = {}
SAVE_ALL: dict[str, Callable[[Image, IO[bytes], str | bytes], None]] = {}
EXTENSION: dict[str, str] = {}
DECODERS: dict[str, type[ImageFile.PyDecoder]] = {}
ENCODERS: dict[str, type[ImageFile.PyEncoder]] = {}

# --------------------------------------------------------------------
# Modes

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


def _conv_type_shape(im):
    m = ImageMode.getmode(im.mode)
    shape = (im.height, im.width)
    extra = len(m.bands)
    if extra != 1:
        shape += (extra,)
    return shape, m.typestr


MODES = [
    "1",
    "CMYK",
    "F",
    "HSV",
    "I",
    "I;16",
    "I;16B",
    "I;16L",
    "I;16N",
    "L",
    "LA",
    "La",
    "LAB",
    "P",
    "PA",
    "RGB",
    "RGBA",
    "RGBa",
    "RGBX",
    "YCbCr",
]

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


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

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


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

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


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

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


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

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


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

_initialized = 0


def preinit() -> None:
    """
    Explicitly loads BMP, GIF, JPEG, PPM and PPM file format drivers.

    It is called when opening or saving images.
    """

    global _initialized
    if _initialized >= 1:
        return

    try:
        from . import BmpImagePlugin

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

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

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

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

        assert PngImagePlugin
    except ImportError:
        pass

    _initialized = 1


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

    It is called when opening or saving images if :py:meth:`~preinit()` is
    insufficient, and by :py:meth:`~PIL.features.pilinfo`.
    """

    global _initialized
    if _initialized >= 2:
        return False

    parent_name = __name__.rpartition(".")[0]
    for plugin in _plugins:
        try:
            logger.debug("Importing %s", plugin)
            __import__(f"{parent_name}.{plugin}", globals(), locals(), [])
        except ImportError as e:
            logger.debug("Image: failed to import %s: %s", plugin, e)

    if OPEN or SAVE:
        _initialized = 2
        return True
    return False


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


def _getdecoder(
    mode: str, decoder_name: str, args: Any, extra: tuple[Any, ...] = ()
) -> core.ImagingDecoder | ImageFile.PyDecoder:
    # tweak arguments
    if args is None:
        args = ()
    elif not isinstance(args, tuple):
        args = (args,)

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

    try:
        # get decoder
        decoder = getattr(core, f"{decoder_name}_decoder")
    except AttributeError as e:
        msg = f"decoder {decoder_name} not available"
        raise OSError(msg) from e
    return decoder(mode, *args + extra)


def _getencoder(
    mode: str, encoder_name: str, args: Any, extra: tuple[Any, ...] = ()
) -> core.ImagingEncoder | ImageFile.PyEncoder:
    # tweak arguments
    if args is None:
        args = ()
    elif not isinstance(args, tuple):
        args = (args,)

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

    try:
        # get encoder
        encoder = getattr(core, f"{encoder_name}_encoder")
    except AttributeError as e:
        msg = f"encoder {encoder_name} not available"
        raise OSError(msg) from e
    return encoder(mode, *args + extra)


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


class _E:
    def __init__(self, scale, offset) -> None:
        self.scale = scale
        self.offset = offset

    def __neg__(self):
        return _E(-self.scale, -self.offset)

    def __add__(self, other):
        if isinstance(other, _E):
            return _E(self.scale + other.scale, self.offset + other.offset)
        return _E(self.scale, self.offset + other)

    __radd__ = __add__

    def __sub__(self, other):
        return self + -other

    def __rsub__(self, other):
        return other + -self

    def __mul__(self, other):
        if isinstance(other, _E):
            return NotImplemented
        return _E(self.scale * other, self.offset * other)

    __rmul__ = __mul__

    def __truediv__(self, other):
        if isinstance(other, _E):
            return NotImplemented
        return _E(self.scale / other, self.offset / other)


def _getscaleoffset(expr):
    a = expr(_E(1, 0))
    return (a.scale, a.offset) if isinstance(a, _E) else (0, a)


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


class SupportsGetData(Protocol):
    def getdata(
        self,
    ) -> tuple[Transform, Sequence[int]]: ...


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

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

    format: str | None = None
    format_description: str | None = None
    _close_exclusive_fp_after_loading = True

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

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

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

    @property
    def size(self) -> tuple[int, int]:
        return self._size

    @property
    def mode(self) -> str:
        return self._mode

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

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

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

    def _close_fp(self):
        if getattr(self, "_fp", False):
            if self._fp != self.fp:
                self._fp.close()
            self._fp = DeferredError(ValueError("Operation on closed image"))
        if self.fp:
            self.fp.close()

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

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

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

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

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

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

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

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

    def _dump(
        self, file: str | None = None, format: str | None = None, **options: Any
    ) -> str:
        suffix = ""
        if format:
            suffix = f".{format}"

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

        self.load()

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

        return filename

    def __eq__(self, other: object) -> bool:
        if self.__class__ is not other.__class__:
            return False
        assert isinstance(other, Image)
        return (
            self.mode == other.mode
            and self.size == other.size
            and self.info == other.info
            and self.getpalette() == other.getpalette()
            and self.tobytes() == other.tobytes()
        )

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

    def _repr_pretty_(self, p, cycle) -> None:
        """IPython plain text display support"""

        # Same as __repr__ but without unpredictable id(self),
        # to keep Jupyter notebook `text/plain` output stable.
        p.text(
            "<%s.%s image mode=%s size=%dx%d>"
            % (
                self.__class__.__module__,
                self.__class__.__name__,
                self.mode,
                self.size[0],
                self.size[1],
            )
        )

    def _repr_image(self, image_format: str, **kwargs: Any) -> bytes | None:
        """Helper function for iPython display hook.

        :param image_format: Image format.
        :returns: image as bytes, saved into the given format.
        """
        b = io.BytesIO()
        try:
            self.save(b, image_format, **kwargs)
        except Exception:
            return None
        return b.getvalue()

    def _repr_png_(self) -> bytes | None:
        """iPython display hook support for PNG format.

        :returns: PNG version of the image as bytes
        """
        return self._repr_image("PNG", compress_level=1)

    def _repr_jpeg_(self) -> bytes | None:
        """iPython display hook support for JPEG format.

        :returns: JPEG version of the image as bytes
        """
        return self._repr_image("JPEG")

    @property
    def __array_interface__(self):
        # numpy array interface support
        new = {"version": 3}
        try:
            if self.mode == "1":
                # Binary images need to be extended from bits to bytes
                # See: https://github.com/python-pillow/Pillow/issues/350
                new["data"] = self.tobytes("raw", "L")
            else:
                new["data"] = self.tobytes()
        except Exception as e:
            if not isinstance(e, (MemoryError, RecursionError)):
                try:
                    import numpy
                    from packaging.version import parse as parse_version
                except ImportError:
                    pass
                else:
                    if parse_version(numpy.__version__) < parse_version("1.23"):
                        warnings.warn(str(e))
            raise
        new["shape"], new["typestr"] = _conv_type_shape(self)
        return new

    def __getstate__(self):
        im_data = self.tobytes()  # load image first
        return [self.info, self.mode, self.size, self.getpalette(), im_data]

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

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

        .. warning::

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

        :param encoder_name: What encoder to use.  The default is to
                             use the standard "raw" encoder.

                             A list of C encoders can be seen under
                             codecs section of the function array in
                             :file:`_imaging.c`. Python encoders are
                             registered within the relevant plugins.
        :param args: Extra arguments to the encoder.
        :returns: A :py:class:`bytes` object.
        """

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

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

        self.load()

        if self.width == 0 or self.height == 0:
            return b""

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

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

        output = []
        while True:
            bytes_consumed, errcode, data = e.encode(bufsize)
            output.append(data)
            if errcode:
                break
        if errcode < 0:
            msg = f"encoder error {errcode} in tobytes"
            raise RuntimeError(msg)

        return b"".join(output)

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

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

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

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

    def frombytes(
        self, data: bytes | bytearray, decoder_name: str = "raw", *args: Any
    ) -> None:
        """
        Loads this image with pixel data from a bytes object.

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

        if self.width == 0 or self.height == 0:
            return

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

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

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

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

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

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

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

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

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

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

    def convert(
        self,
        mode: str | None = None,
        matrix: tuple[float, ...] | None = None,
        dither: Dither | None = None,
        palette: Palette = Palette.WEB,
        colors: int = 256,
    ) -> Image:
        """
        Returns a converted copy of this image. For the "P" mode, this
        method translates pixels through the palette.  If mode is
        omitted, a mode is chosen so that all information in the image
        and the palette can be represented without a palette.

        This supports all possible conversions between "L", "RGB" and "CMYK". The
        ``matrix`` argument only supports "L" and "RGB".

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

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

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

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

        When converting from "PA", if an "RGBA" palette is present, the alpha
        channel from the image will be used instead of the values from the palette.

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

        if mode in ("BGR;15", "BGR;16", "BGR;24"):
            deprecate(mode, 12)

        self.load()

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

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

                def convert_transparency(
                    m: tuple[float, ...], v: tuple[int, int, int]
                ) -> int:
                    value = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * 0.5
                    return max(0, min(255, int(value)))

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

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

        trns = None
        delete_trns = False
        # transparency handling
        if has_transparency:
            if (self.mode in ("1", "L", "I", "I;16") and mode in ("LA", "RGBA")) or (
                self.mode == "RGB" and mode in ("La", "LA", "RGBa", "RGBA")
            ):
                # Use transparent conversion to promote from transparent
                # color to an alpha channel.
                new_im = self._new(
                    self.im.convert_transparent(mode, self.info["transparency"])
                )
                del new_im.info["transparency"]
                return new_im
            elif self.mode in ("L", "RGB", "P") and mode in ("L", "RGB", "P"):
                t = self.info["transparency"]
                if isinstance(t, bytes):
                    # Dragons. This can't be represented by a single color
                    warnings.warn(
                        "Palette images with Transparency expressed in bytes should be "
                        "converted to RGBA images"
                    )
                    delete_trns = True
                else:
                    # get the new transparency color.
                    # use existing conversions
                    trns_im = new(self.mode, (1, 1))
                    if self.mode == "P":
                        trns_im.putpalette(self.palette)
                        if isinstance(t, tuple):
                            err = "Couldn't allocate a palette color for transparency"
                            try:
                                t = trns_im.palette.getcolor(t, self)
                            except ValueError as e:
                                if str(e) == "cannot allocate more than 256 colors":
                                    # If all 256 colors are in use,
                                    # then there is no need for transparency
                                    t = None
                                else:
                                    raise ValueError(err) from e
                    if t is None:
                        trns = None
                    else:
                        trns_im.putpixel((0, 0), t)

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

            elif self.mode == "P" and mode in ("LA", "PA", "RGBA"):
                t = self.info["transparency"]
                delete_trns = True

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

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

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

        if "LAB" in (self.mode, mode):
            other_mode = mode if self.mode == "LAB" else self.mode
            if other_mode in ("RGB", "RGBA", "RGBX"):
                from . import ImageCms

                srgb = ImageCms.createProfile("sRGB")
                lab = ImageCms.createProfile("LAB")
                profiles = [lab, srgb] if self.mode == "LAB" else [srgb, lab]
                transform = ImageCms.buildTransform(
                    profiles[0], profiles[1], self.mode, mode
                )
                return transform.apply(self)

        # colorspace conversion
        if dither is None:
            dither = Dither.FLOYDSTEINBERG

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

        new_im = self._new(im)
        if mode == "P" and palette != Palette.ADAPTIVE:
            from . import ImagePalette

            new_im.palette = ImagePalette.ImagePalette("RGB", im.getpalette("RGB"))
        if delete_trns:
            # crash fail if we leave a bytes transparency in an rgb/l mode.
            del new_im.info["transparency"]
        if trns is not None:
            if new_im.mode == "P" and new_im.palette:
                try:
                    new_im.info["transparency"] = new_im.palette.getcolor(trns, new_im)
                except ValueError as e:
                    del new_im.info["transparency"]
                    if str(e) != "cannot allocate more than 256 colors":
                        # If all 256 colors are in use,
                        # then there is no need for transparency
                        warnings.warn(
                            "Couldn't allocate palette entry for transparency"
                        )
            else:
                new_im.info["transparency"] = trns
        return new_im

    def quantize(
        self,
        colors: int = 256,
        method: int | None = None,
        kmeans: int = 0,
        palette=None,
        dither: Dither = Dither.FLOYDSTEINBERG,
    ) -> Image:
        """
        Convert the image to 'P' mode with the specified number
        of colors.

        :param colors: The desired number of colors, <= 256
        :param method: :data:`Quantize.MEDIANCUT` (median cut),
                       :data:`Quantize.MAXCOVERAGE` (maximum coverage),
                       :data:`Quantize.FASTOCTREE` (fast octree),
                       :data:`Quantize.LIBIMAGEQUANT` (libimagequant; check support
                       using :py:func:`PIL.features.check_feature` with
                       ``feature="libimagequant"``).

                       By default, :data:`Quantize.MEDIANCUT` will be used.

                       The exception to this is RGBA images. :data:`Quantize.MEDIANCUT`
                       and :data:`Quantize.MAXCOVERAGE` do not support RGBA images, so
                       :data:`Quantize.FASTOCTREE` is used by default instead.
        :param kmeans: Integer greater than or equal to zero.
        :param palette: Quantize to the palette of given
                        :py:class:`PIL.Image.Image`.
        :param dither: Dithering method, used when converting from
           mode "RGB" to "P" or from "RGB" or "L" to "1".
           Available methods are :data:`Dither.NONE` or :data:`Dither.FLOYDSTEINBERG`
           (default).
        :returns: A new image
        """

        self.load()

        if method is None:
            # defaults:
            method = Quantize.MEDIANCUT
            if self.mode == "RGBA":
                method = Quantize.FASTOCTREE

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

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

        if kmeans < 0:
            msg = "kmeans must not be negative"
            raise ValueError(msg)

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

        from . import ImagePalette

        mode = im.im.getpalettemode()
        palette = im.im.getpalette(mode, mode)[: colors * len(mode)]
        im.palette = ImagePalette.ImagePalette(mode, palette)

        return im

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

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

    __copy__ = copy

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

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

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

        if box is None:
            return self.copy()

        if box[2] < box[0]:
            msg = "Coordinate 'right' is less than 'left'"
            raise ValueError(msg)
        elif box[3] < box[1]:
            msg = "Coordinate 'lower' is less than 'upper'"
            raise ValueError(msg)

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

    def _crop(
        self, im: core.ImagingCore, box: tuple[float, float, float, float]
    ) -> core.ImagingCore:
        """
        Returns a rectangular region from the core image object im.

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

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

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

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

        _decompression_bomb_check(absolute_values)

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

    def draft(
        self, mode: str | None, size: tuple[int, int] | None
    ) -> tuple[str, tuple[int, int, float, float]] | None:
        """
        Configures the image file loader so it returns a version of the
        image that as closely as possible matches the given mode and
        size. For example, you can use this method to convert a color
        JPEG to grayscale while loading it.

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

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

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

        :param mode: The requested mode.
        :param size: The requested size in pixels, as a 2-tuple:
           (width, height).
        """
        pass

    def _expand(self, xmargin: int, ymargin: int | None = None) -> Image:
        if ymargin is None:
            ymargin = xmargin
        self.load()
        return self._new(self.im.expand(xmargin, ymargin))

    if TYPE_CHECKING:
        from . import ImageFilter

    def filter(self, filter: ImageFilter.Filter | type[ImageFilter.Filter]) -> Image:
        """
        Filters this image using the given filter.  For a list of
        available filters, see the :py:mod:`~PIL.ImageFilter` module.

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

        from . import ImageFilter

        self.load()

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

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

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

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

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

    def getbbox(self, *, alpha_only: bool = True) -> tuple[int, int, int, int] | None:
        """
        Calculates the bounding box of the non-zero regions in the
        image.

        :param alpha_only: Optional flag, defaulting to ``True``.
           If ``True`` and the image has an alpha channel, trim transparent pixels.
           Otherwise, trim pixels when all channels are zero.
           Keyword-only argument.
        :returns: The bounding box is returned as a 4-tuple defining the
           left, upper, right, and lower pixel coordinate. See
           :ref:`coordinate-system`. If the image is completely empty, this
           method returns None.

        """

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

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

        The colors will be in the image's mode. For example, an RGB image will
        return a tuple of (red, green, blue) color values, and a P image will
        return the index of the color in the palette.

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

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

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

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

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

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

    def getextrema(self) -> tuple[float, float] | tuple[tuple[int, int], ...]:
        """
        Gets the minimum and maximum pixel values for each band in
        the image.

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

        self.load()
        if self.im.bands > 1:
            return tuple(self.im.getband(i).getextrema() for i in range(self.im.bands))
        return self.im.getextrema()

    def getxmp(self):
        """
        Returns a dictionary containing the XMP tags.
        Requires defusedxml to be installed.

        :returns: XMP tags in a dictionary.
        """

        def get_name(tag: str) -> str:
            return re.sub("^{[^}]+}", "", tag)

        def get_value(element):
            value = {get_name(k): v for k, v in element.attrib.items()}
            children = list(element)
            if children:
                for child in children:
                    name = get_name(child.tag)
                    child_value = get_value(child)
                    if name in value:
                        if not isinstance(value[name], list):
                            value[name] = [value[name]]
                        value[name].append(child_value)
                    else:
                        value[name] = child_value
            elif value:
                if element.text:
                    value["text"] = element.text
            else:
                return element.text
            return value

        if ElementTree is None:
            warnings.warn("XMP data cannot be read without defusedxml dependency")
            return {}
        if "xmp" not in self.info:
            return {}
        root = ElementTree.fromstring(self.info["xmp"].rstrip(b"\x00"))
        return {get_name(root.tag): get_value(root)}

    def getexif(self) -> Exif:
        """
        Gets EXIF data from the image.

        :returns: an :py:class:`~PIL.Image.Exif` object.
        """
        if self._exif is None:
            self._exif = Exif()
        elif self._exif._loaded:
            return self._exif
        self._exif._loaded = True

        exif_info = self.info.get("exif")
        if exif_info is None:
            if "Raw profile type exif" in self.info:
                exif_info = bytes.fromhex(
                    "".join(self.info["Raw profile type exif"].split("\n")[3:])
                )
            elif hasattr(self, "tag_v2"):
                self._exif.bigtiff = self.tag_v2._bigtiff
                self._exif.endian = self.tag_v2._endian
                self._exif.load_from_fp(self.fp, self.tag_v2._offset)
        if exif_info is not None:
            self._exif.load(exif_info)

        # XMP tags
        if ExifTags.Base.Orientation not in self._exif:
            xmp_tags = self.info.get("XML:com.adobe.xmp")
            if xmp_tags:
                match = re.search(r'tiff:Orientation(="|>)([0-9])', xmp_tags)
                if match:
                    self._exif[ExifTags.Base.Orientation] = int(match[2])

        return self._exif

    def _reload_exif(self) -> None:
        if self._exif is None or not self._exif._loaded:
            return
        self._exif._loaded = False
        self.getexif()

    def get_child_images(self) -> list[ImageFile.ImageFile]:
        child_images = []
        exif = self.getexif()
        ifds = []
        if ExifTags.Base.SubIFDs in exif:
            subifd_offsets = exif[ExifTags.Base.SubIFDs]
            if subifd_offsets:
                if not isinstance(subifd_offsets, tuple):
                    subifd_offsets = (subifd_offsets,)
                for subifd_offset in subifd_offsets:
                    ifds.append((exif._get_ifd_dict(subifd_offset), subifd_offset))
        ifd1 = exif.get_ifd(ExifTags.IFD.IFD1)
        if ifd1 and ifd1.get(513):
            ifds.append((ifd1, exif._info.next))

        offset = None
        for ifd, ifd_offset in ifds:
            current_offset = self.fp.tell()
            if offset is None:
                offset = current_offset

            fp = self.fp
            thumbnail_offset = ifd.get(513)
            if thumbnail_offset is not None:
                thumbnail_offset += getattr(self, "_exif_offset", 0)
                self.fp.seek(thumbnail_offset)
                data = self.fp.read(ifd.get(514))
                fp = io.BytesIO(data)

            with open(fp) as im:
                from . import TiffImagePlugin

                if thumbnail_offset is None and isinstance(
                    im, TiffImagePlugin.TiffImageFile
                ):
                    im._frame_pos = [ifd_offset]
                    im._seek(0)
                im.load()
                child_images.append(im)

        if offset is not None:
            self.fp.seek(offset)
        return child_images

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

        :returns: A capsule object.
        """

        self.load()
        return self.im.ptr

    def getpalette(self, rawmode: str | None = "RGB") -> list[int] | None:
        """
        Returns the image palette as a list.

        :param rawmode: The mode in which to return the palette. ``None`` will
           return the palette in its current mode.

           .. versionadded:: 9.1.0

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

        self.load()
        try:
            mode = self.im.getpalettemode()
        except ValueError:
            return None  # no palette
        if rawmode is None:
            rawmode = mode
        return list(self.im.getpalette(mode, rawmode))

    @property
    def has_transparency_data(self) -> bool:
        """
        Determine if an image has transparency data, whether in the form of an
        alpha channel, a palette with an alpha channel, or a "transparency" key
        in the info dictionary.

        Note the image might still appear solid, if all of the values shown
        within are opaque.

        :returns: A boolean.
        """
        return (
            self.mode in ("LA", "La", "PA", "RGBA", "RGBa")
            or (self.mode == "P" and self.palette.mode.endswith("A"))
            or "transparency" in self.info
        )

    def apply_transparency(self) -> None:
        """
        If a P mode image has a "transparency" key in the info dictionary,
        remove the key and instead apply the transparency to the palette.
        Otherwise, the image is unchanged.
        """
        if self.mode != "P" or "transparency" not in self.info:
            return

        from . import ImagePalette

        palette = self.getpalette("RGBA")
        assert palette is not None
        transparency = self.info["transparency"]
        if isinstance(transparency, bytes):
            for i, alpha in enumerate(transparency):
                palette[i * 4 + 3] = alpha
        else:
            palette[transparency * 4 + 3] = 0
        self.palette = ImagePalette.ImagePalette("RGBA", bytes(palette))
        self.palette.dirty = 1

        del self.info["transparency"]

    def getpixel(
        self, xy: tuple[int, int] | list[int]
    ) -> float | tuple[int, ...] | None:
        """
        Returns the pixel value at a given position.

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

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

    def getprojection(self) -> tuple[list[int], list[int]]:
        """
        Get projection to x and y axes

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

        self.load()
        x, y = self.im.getprojection()
        return list(x), list(y)

    def histogram(self, mask: Image | None = None, extrema=None) -> list[int]:
        """
        Returns a histogram for the image. The histogram is returned as a
        list of pixel counts, one for each pixel value in the source
        image. Counts are grouped into 256 bins for each band, even if
        the image has more than 8 bits per band. If the image has more
        than one band, the histograms for all bands are concatenated (for
        example, the histogram for an "RGB" image contains 768 values).

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        if isImageType(box):
            if mask is not None:
                msg = "If using second argument as mask, third argument must be None"
                raise ValueError(msg)
            # abbreviated paste(im, mask) syntax
            mask = box
            box = None
        assert not isinstance(box, Image)

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

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

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

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

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

        self._ensure_mutable()

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

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

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

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

        if not isinstance(source, (list, tuple)):
            msg = "Source must be a list or tuple"
            raise ValueError(msg)
        if not isinstance(dest, (list, tuple)):
            msg = "Destination must be a list or tuple"
            raise ValueError(msg)

        if len(source) == 4:
            overlay_crop_box = tuple(source)
        elif len(source) == 2:
            overlay_crop_box = tuple(source) + im.size
        else:
            msg = "Source must be a sequence of length 2 or 4"
            raise ValueError(msg)

        if not len(dest) == 2:
            msg = "Destination must be a sequence of length 2"
            raise ValueError(msg)
        if min(source) < 0:
            msg = "Source must be non-negative"
            raise ValueError(msg)

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

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

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

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

    def point(
        self,
        lut: Sequence[float] | Callable[[int], float] | ImagePointHandler,
        mode: str | None = None,
    ) -> Image:
        """
        Maps this image through a lookup table or function.

        :param lut: A lookup table, containing 256 (or 65536 if
           self.mode=="I" and mode == "L") values per band in the
           image.  A function can be used instead, it should take a
           single argument. The function is called once for each
           possible pixel value, and the resulting table is applied to
           all bands of the image.

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

               class Example(Image.ImagePointHandler):
                 def point(self, data):
                   # Return result
        :param mode: Output mode (default is same as input). This can only be used if
           the source image has mode "L" or "P", and the output has mode "1" or the
           source image mode is "I" and the output mode is "L".
        :returns: An :py:class:`~PIL.Image.Image` object.
        """

        self.load()

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

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

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

        if mode != "F":
            flatLut = [round(i) for i in flatLut]
        return self._new(self.im.point(flatLut, mode))

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

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

        self._ensure_mutable()

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

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

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

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

    def putdata(
        self,
        data: Sequence[float] | Sequence[Sequence[int]],
        scale: float = 1.0,
        offset: float = 0.0,
    ) -> None:
        """
        Copies pixel data from a flattened sequence object into the image. The
        values should start at the upper left corner (0, 0), continue to the
        end of the line, followed directly by the first value of the second
        line, and so on. Data will be read until either the image or the
        sequence ends. The scale and offset values are used to adjust the
        sequence values: **pixel = value*scale + offset**.

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

        self._ensure_mutable()

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

    def putpalette(self, data, rawmode="RGB") -> None:
        """
        Attaches a palette to this image.  The image must be a "P", "PA", "L"
        or "LA" image.

        The palette sequence must contain at most 256 colors, made up of one
        integer value for each channel in the raw mode.
        For example, if the raw mode is "RGB", then it can contain at most 768
        values, made up of red, green and blue values for the corresponding pixel
        index in the 256 colors.
        If the raw mode is "RGBA", then it can contain at most 1024 values,
        containing red, green, blue and alpha values.

        Alternatively, an 8-bit string may be used instead of an integer sequence.

        :param data: A palette sequence (either a list or a string).
        :param rawmode: The raw mode of the palette. Either "RGB", "RGBA", or a mode
           that can be transformed to "RGB" or "RGBA" (e.g. "R", "BGR;15", "RGBA;L").
        """
        from . import ImagePalette

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

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

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

        See:

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

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

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

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

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

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

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

        """
        from . import ImagePalette

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

        bands = 3
        palette_mode = "RGB"
        if source_palette is None:
            if self.mode == "P":
                self.load()
                palette_mode = self.im.getpalettemode()
                if palette_mode == "RGBA":
                    bands = 4
                source_palette = self.im.getpalette(palette_mode, palette_mode)
            else:  # L-mode
                source_palette = bytearray(i // 3 for i in range(768))

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

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

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

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

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

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

        mapping_palette = bytearray(new_positions)

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

        m_im.palette = ImagePalette.ImagePalette(
            palette_mode, palette=mapping_palette * bands
        )
        # possibly set palette dirty, then
        # m_im.putpalette(mapping_palette, 'L')  # converts to 'P'
        # or just force it.
        # UNDONE -- this is part of the general issue with palettes
        m_im.im.putpalette(palette_mode, palette_mode + ";L", m_im.palette.tobytes())

        m_im = m_im.convert("L")

        m_im.putpalette(palette_bytes, palette_mode)
        m_im.palette = ImagePalette.ImagePalette(palette_mode, palette=palette_bytes)

        if "transparency" in self.info:
            try:
                m_im.info["transparency"] = dest_map.index(self.info["transparency"])
            except ValueError:
                if "transparency" in m_im.info:
                    del m_im.info["transparency"]

        return m_im

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

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

    def resize(
        self,
        size: tuple[int, int],
        resample: int | None = None,
        box: tuple[float, float, float, float] | None = None,
        reducing_gap: float | None = None,
    ) -> Image:
        """
        Returns a resized copy of this image.

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

        if resample is None:
            type_special = ";" in self.mode
            resample = Resampling.NEAREST if type_special else Resampling.BICUBIC
        elif resample not in (
            Resampling.NEAREST,
            Resampling.BILINEAR,
            Resampling.BICUBIC,
            Resampling.LANCZOS,
            Resampling.BOX,
            Resampling.HAMMING,
        ):
            msg = f"Unknown resampling filter ({resample})."

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

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

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

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

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

        if self.mode in ["LA", "RGBA"] and resample != Resampling.NEAREST:
            im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode])
            im = im.resize(size, resample, box)
            return im.convert(self.mode)

        self.load()

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

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

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

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

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

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

        if self.mode in ["LA", "RGBA"]:
            im = self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode])
            im = im.reduce(factor, box)
            return im.convert(self.mode)

        self.load()

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

    def rotate(
        self,
        angle: float,
        resample: Resampling = Resampling.NEAREST,
        expand: int | bool = False,
        center: tuple[float, float] | None = None,
        translate: tuple[int, int] | None = None,
        fillcolor: float | tuple[float, ...] | str | None = None,
    ) -> Image:
        """
        Returns a rotated copy of this image.  This method returns a
        copy of this image, rotated the given number of degrees counter
        clockwise around its centre.

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

        angle = angle % 360.0

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

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

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

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

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

        w, h = self.size

        if translate is None:
            post_trans = (0, 0)
        else:
            post_trans = translate
        if center is None:
            center = (w / 2, h / 2)

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

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

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

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

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

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

    def save(
        self, fp: StrOrBytesPath | IO[bytes], format: str | None = None, **params: Any
    ) -> None:
        """
        Saves this image under the given filename.  If no format is
        specified, the format to use is determined from the filename
        extension, if possible.

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

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

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

        filename: str | bytes = ""
        open_fp = False
        if is_path(fp):
            filename = os.path.realpath(os.fspath(fp))
            open_fp = True
        elif fp == sys.stdout:
            try:
                fp = sys.stdout.buffer
            except AttributeError:
                pass
        if not filename and hasattr(fp, "name") and is_path(fp.name):
            # only set the name for metadata purposes
            filename = os.path.realpath(os.fspath(fp.name))

        # may mutate self!
        self._ensure_mutable()

        save_all = params.pop("save_all", False)
        self.encoderinfo = params
        self.encoderconfig: tuple[Any, ...] = ()

        preinit()

        filename_ext = os.path.splitext(filename)[1].lower()
        ext = filename_ext.decode() if isinstance(filename_ext, bytes) else filename_ext

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

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

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

        try:
            save_handler(self, fp, filename)
        except Exception:
            if open_fp:
                fp.close()
            if created:
                try:
                    os.remove(filename)
                except PermissionError:
                    pass
            raise
        if open_fp:
            fp.close()

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

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

        If defined, :attr:`~PIL.Image.Image.n_frames` refers to the
        number of available frames.

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

        # overridden by file handlers
        if frame != 0:
            msg = "no more images in file"
            raise EOFError(msg)

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

        This method calls :py:func:`PIL.ImageShow.show` internally. You can use
        :py:func:`PIL.ImageShow.register` to override its default behaviour.

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

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

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

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

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

        _show(self, title=title)

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

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

        :returns: A tuple containing bands.
        """

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

    def getchannel(self, channel: int | str) -> Image:
        """
        Returns an image containing a single channel of the source image.

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

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

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

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

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

        If defined, :attr:`~PIL.Image.Image.n_frames` refers to the
        number of available frames.

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

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

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

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

        provided_size = tuple(map(math.floor, size))

        def preserve_aspect_ratio() -> tuple[int, int] | None:
            def round_aspect(number, key):
                return max(min(math.floor(number), math.ceil(number), key=key), 1)

            x, y = provided_size
            if x >= self.width and y >= self.height:
                return None

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

        box = None
        final_size: tuple[int, int]
        if reducing_gap is not None:
            preserved_size = preserve_aspect_ratio()
            if preserved_size is None:
                return
            final_size = preserved_size

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

            # load() may have changed the size of the image
            preserved_size = preserve_aspect_ratio()
            if preserved_size is None:
                return
            final_size = preserved_size

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

            self.im = im.im
            self._size = final_size
            self._mode = self.im.mode

        self.readonly = 0
        self.pyaccess = None

    # FIXME: the different transform methods need further explanation
    # instead of bloating the method docs, add a separate chapter.
    def transform(
        self,
        size: tuple[int, int],
        method: Transform | ImageTransformHandler | SupportsGetData,
        data: Sequence[Any] | None = None,
        resample: int = Resampling.NEAREST,
        fill: int = 1,
        fillcolor: float | tuple[float, ...] | str | None = None,
    ) -> Image:
        """
        Transforms this image.  This method creates a new image with the
        given size, and the same mode as the original, and copies data
        to the new image using the given transform.

        :param size: The output size in pixels, as a 2-tuple:
           (width, height).
        :param method: The transformation method.  This is one of
          :py:data:`Transform.EXTENT` (cut out a rectangular subregion),
          :py:data:`Transform.AFFINE` (affine transform),
          :py:data:`Transform.PERSPECTIVE` (perspective transform),
          :py:data:`Transform.QUAD` (map a quadrilateral to a rectangle), or
          :py:data:`Transform.MESH` (map a number of source quadrilaterals
          in one operation).

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

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

          Implementations of :py:class:`~PIL.Image.ImageTransformHandler`
          for some of the :py:class:`Transform` methods are provided
          in :py:mod:`~PIL.ImageTransform`.

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

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

        if self.mode in ("LA", "RGBA") and resample != Resampling.NEAREST:
            return (
                self.convert({"LA": "La", "RGBA": "RGBa"}[self.mode])
                .transform(size, method, data, resample, fill, fillcolor)
                .convert(self.mode)
            )

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

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

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

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

        return im

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

        if method == Transform.AFFINE:
            data = data[:6]

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

        elif method == Transform.PERSPECTIVE:
            data = data[:8]

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

        else:
            msg = "unknown transformation method"
            raise ValueError(msg)

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

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

        image.load()

        self.load()

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

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

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

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

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

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

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

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

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

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

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


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


class ImagePointHandler:
    """
    Used as a mixin by point transforms
    (for use with :py:meth:`~PIL.Image.Image.point`)
    """

    @abc.abstractmethod
    def point(self, im: Image) -> Image:
        pass


class ImageTransformHandler:
    """
    Used as a mixin by geometry transforms
    (for use with :py:meth:`~PIL.Image.Image.transform`)
    """

    @abc.abstractmethod
    def transform(
        self,
        size: tuple[int, int],
        image: Image,
        **options: Any,
    ) -> Image:
        pass


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

#
# Debugging


def _wedge() -> Image:
    """Create grayscale wedge (for debugging only)"""

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


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

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

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


def new(
    mode: str,
    size: tuple[int, int] | list[int],
    color: float | tuple[float, ...] | str | None = 0,
) -> Image:
    """
    Creates a new image with the given mode and size.

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

    if mode in ("BGR;15", "BGR;16", "BGR;24"):
        deprecate(mode, 12)

    _check_size(size)

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

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

        from . import ImageColor

        color = ImageColor.getcolor(color, mode)

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

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


def frombytes(
    mode: str,
    size: tuple[int, int],
    data: bytes | bytearray,
    decoder_name: str = "raw",
    *args: Any,
) -> Image:
    """
    Creates a copy of an image memory from pixel data in a buffer.

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

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

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

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

    _check_size(size)

    im = new(mode, size)
    if im.width != 0 and im.height != 0:
        decoder_args: Any = args
        if len(decoder_args) == 1 and isinstance(decoder_args[0], tuple):
            # may pass tuple instead of argument list
            decoder_args = decoder_args[0]

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

        im.frombytes(data, decoder_name, decoder_args)
    return im


def frombuffer(
    mode: str, size: tuple[int, int], data, decoder_name: str = "raw", *args: Any
) -> Image:
    """
    Creates an image memory referencing pixel data in a byte buffer.

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

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

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

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

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

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

    .. versionadded:: 1.1.4
    """

    _check_size(size)

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

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

                im.palette = ImagePalette.ImagePalette("RGB", im.im.getpalette("RGB"))
            im.readonly = 1
            return im

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


class SupportsArrayInterface(Protocol):
    """
    An object that has an ``__array_interface__`` dictionary.
    """

    @property
    def __array_interface__(self) -> dict[str, Any]:
        raise NotImplementedError()


def fromarray(obj: SupportsArrayInterface, mode: str | None = None) -> Image:
    """
    Creates an image memory from an object exporting the array interface
    (using the buffer protocol)::

      from PIL import Image
      import numpy as np
      a = np.zeros((5, 5))
      im = Image.fromarray(a)

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

    In the case of NumPy, be aware that Pillow modes do not always correspond
    to NumPy dtypes. Pillow modes only offer 1-bit pixels, 8-bit pixels,
    32-bit signed integer pixels, and 32-bit floating point pixels.

    Pillow images can also be converted to arrays::

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

    When converting Pillow images to arrays however, only pixel values are
    transferred. This means that P and PA mode images will lose their palette.

    :param obj: Object with array interface
    :param mode: Optional mode to use when reading ``obj``. Will be determined from
      type if ``None``.

      This will not be used to convert the data after reading, but will be used to
      change how the data is read::

        from PIL import Image
        import numpy as np
        a = np.full((1, 1), 300)
        im = Image.fromarray(a, mode="L")
        im.getpixel((0, 0))  # 44
        im = Image.fromarray(a, mode="RGB")
        im.getpixel((0, 0))  # (44, 1, 0)

      See: :ref:`concept-modes` for general information about modes.
    :returns: An image object.

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

    size = 1 if ndim == 1 else shape[1], shape[0]
    if strides is not None:
        if hasattr(obj, "tobytes"):
            obj = obj.tobytes()
        elif hasattr(obj, "tostring"):
            obj = obj.tostring()
        else:
            msg = "'strides' requires either tobytes() or tostring()"
            raise ValueError(msg)

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


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

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


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

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


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


def _decompression_bomb_check(size: tuple[int, int]) -> None:
    if MAX_IMAGE_PIXELS is None:
        return

    pixels = max(1, size[0]) * max(1, size[1])

    if pixels > 2 * MAX_IMAGE_PIXELS:
        msg = (
            f"Image size ({pixels} pixels) exceeds limit of {2 * MAX_IMAGE_PIXELS} "
            "pixels, could be decompression bomb DOS attack."
        )
        raise DecompressionBombError(msg)

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


def open(
    fp: StrOrBytesPath | IO[bytes],
    mode: Literal["r"] = "r",
    formats: list[str] | tuple[str, ...] | None = None,
) -> ImageFile.ImageFile:
    """
    Opens and identifies the given image file.

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

    :param fp: A filename (string), os.PathLike object or a file object.
       The file object must implement ``file.read``,
       ``file.seek``, and ``file.tell`` methods,
       and be opened in binary mode. The file object will also seek to zero
       before reading.
    :param mode: The mode.  If given, this argument must be "r".
    :param formats: A list or tuple of formats to attempt to load the file in.
       This can be used to restrict the set of formats checked.
       Pass ``None`` to try all supported formats. You can print the set of
       available formats by running ``python3 -m PIL`` or using
       the :py:func:`PIL.features.pilinfo` function.
    :returns: An :py:class:`~PIL.Image.Image` object.
    :exception FileNotFoundError: If the file cannot be found.
    :exception PIL.UnidentifiedImageError: If the image cannot be opened and
       identified.
    :exception ValueError: If the ``mode`` is not "r", or if a ``StringIO``
       instance is used for ``fp``.
    :exception TypeError: If ``formats`` is not ``None``, a list or a tuple.
    """

    if mode != "r":
        msg = f"bad mode {repr(mode)}"  # type: ignore[unreachable]
        raise ValueError(msg)
    elif isinstance(fp, io.StringIO):
        msg = (  # type: ignore[unreachable]
            "StringIO cannot be used to open an image. "
            "Binary data must be used instead."
        )
        raise ValueError(msg)

    if formats is None:
        formats = ID
    elif not isinstance(formats, (list, tuple)):
        msg = "formats must be a list or tuple"  # type: ignore[unreachable]
        raise TypeError(msg)

    exclusive_fp = False
    filename: str | bytes = ""
    if is_path(fp):
        filename = os.path.realpath(os.fspath(fp))

    if filename:
        fp = builtins.open(filename, "rb")
        exclusive_fp = True
    else:
        fp = cast(IO[bytes], fp)

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

    prefix = fp.read(16)

    preinit()

    accept_warnings: list[str] = []

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

    im = _open_core(fp, filename, prefix, formats)

    if im is None and formats is ID:
        checked_formats = ID.copy()
        if init():
            im = _open_core(
                fp,
                filename,
                prefix,
                tuple(format for format in formats if format not in checked_formats),
            )

    if im:
        im._exclusive_fp = exclusive_fp
        return im

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


#
# Image processing.


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

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

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


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

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

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

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


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

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

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


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

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

    return image.point(args[0])


def merge(mode: str, bands: Sequence[Image]) -> Image:
    """
    Merge a set of single band images into a new multiband image.

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

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


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


def register_open(
    id: str,
    factory: Callable[[IO[bytes], str | bytes], ImageFile.ImageFile],
    accept: Callable[[bytes], bool | str] | None = None,
) -> None:
    """
    Register an image file plugin.  This function should not be used
    in application code.

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


def register_mime(id: str, mimetype: str) -> None:
    """
    Registers an image MIME type by populating ``Image.MIME``. This function
    should not be used in application code.

    ``Image.MIME`` provides a mapping from image format identifiers to mime
    formats, but :py:meth:`~PIL.ImageFile.ImageFile.get_format_mimetype` can
    provide a different result for specific images.

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


def register_save(
    id: str, driver: Callable[[Image, IO[bytes], str | bytes], None]
) -> None:
    """
    Registers an image save function.  This function should not be
    used in application code.

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


def register_save_all(
    id: str, driver: Callable[[Image, IO[bytes], str | bytes], None]
) -> None:
    """
    Registers an image function to save all the frames
    of a multiframe format.  This function should not be
    used in application code.

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


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

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


def register_extensions(id: str, extensions: list[str]) -> None:
    """
    Registers image extensions.  This function should not be
    used in application code.

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


def registered_extensions() -> dict[str, str]:
    """
    Returns a dictionary containing all file extensions belonging
    to registered plugins
    """
    init()
    return EXTENSION


def register_decoder(name: str, decoder: type[ImageFile.PyDecoder]) -> None:
    """
    Registers an image decoder.  This function should not be
    used in application code.

    :param name: The name of the decoder
    :param decoder: An ImageFile.PyDecoder object

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


def register_encoder(name: str, encoder: type[ImageFile.PyEncoder]) -> None:
    """
    Registers an image encoder.  This function should not be
    used in application code.

    :param name: The name of the encoder
    :param encoder: An ImageFile.PyEncoder object

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


# --------------------------------------------------------------------
# Simple display support.


def _show(image: Image, **options: Any) -> None:
    from . import ImageShow

    ImageShow.show(image, **options)


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


def effect_mandelbrot(
    size: tuple[int, int], extent: tuple[float, float, float, float], quality: int
) -> Image:
    """
    Generate a Mandelbrot set covering the given extent.

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


def effect_noise(size: tuple[int, int], sigma: float) -> Image:
    """
    Generate Gaussian noise centered around 128.

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


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

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


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

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


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


def _apply_env_variables(env: dict[str, str] | None = None) -> None:
    env_dict = env if env is not None else os.environ

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

        var = env_dict[var_name].lower()

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

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

        try:
            setter(var_int)
        except ValueError as e:
            warnings.warn(f"{var_name}: {e}")


_apply_env_variables()
atexit.register(core.clear_cache)


if TYPE_CHECKING:
    _ExifBase = MutableMapping[int, Any]
else:
    _ExifBase = MutableMapping


class Exif(_ExifBase):
    """
    This class provides read and write access to EXIF image data::

      from PIL import Image
      im = Image.open("exif.png")
      exif = im.getexif()  # Returns an instance of this class

    Information can be read and written, iterated over or deleted::

      print(exif[274])  # 1
      exif[274] = 2
      for k, v in exif.items():
        print("Tag", k, "Value", v)  # Tag 274 Value 2
      del exif[274]

    To access information beyond IFD0, :py:meth:`~PIL.Image.Exif.get_ifd`
    returns a dictionary::

      from PIL import ExifTags
      im = Image.open("exif_gps.jpg")
      exif = im.getexif()
      gps_ifd = exif.get_ifd(ExifTags.IFD.GPSInfo)
      print(gps_ifd)

    Other IFDs include ``ExifTags.IFD.Exif``, ``ExifTags.IFD.Makernote``,
    ``ExifTags.IFD.Interop`` and ``ExifTags.IFD.IFD1``.

    :py:mod:`~PIL.ExifTags` also has enum classes to provide names for data::

      print(exif[ExifTags.Base.Software])  # PIL
      print(gps_ifd[ExifTags.GPS.GPSDateStamp])  # 1999:99:99 99:99:99
    """

    endian = None
    bigtiff = False
    _loaded = False

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

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

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

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

            info = TiffImagePlugin.ImageFileDirectory_v2(self.head, group=group)
            info.load(self.fp)
            return self._fixup_dict(info)

    def _get_head(self):
        version = b"\x2B" if self.bigtiff else b"\x2A"
        if self.endian == "<":
            head = b"II" + version + b"\x00" + o32le(8)
        else:
            head = b"MM\x00" + version + o32be(8)
        if self.bigtiff:
            head += o32le(8) if self.endian == "<" else o32be(8)
            head += b"\x00\x00\x00\x00"
        return head

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

        # The EXIF record consists of a TIFF file embedded in a JPEG
        # application marker (!).
        if data == self._loaded_exif:
            return
        self._loaded_exif = data
        self._data.clear()
        self._hidden_data.clear()
        self._ifds.clear()
        if data and data.startswith(b"Exif\x00\x00"):
            data = data[6:]
        if not data:
            self._info = None
            return

        self.fp = io.BytesIO(data)
        self.head = self.fp.read(8)
        # process dictionary
        from . import TiffImagePlugin

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

    def load_from_fp(self, fp, offset=None):
        self._loaded_exif = None
        self._data.clear()
        self._hidden_data.clear()
        self._ifds.clear()

        # process dictionary
        from . import TiffImagePlugin

        self.fp = fp
        if offset is not None:
            self.head = self._get_head()
        else:
            self.head = self.fp.read(8)
        self._info = TiffImagePlugin.ImageFileDirectory_v2(self.head)
        if self.endian is None:
            self.endian = self._info._endian
        if offset is None:
            offset = self._info.next
        self.fp.tell()
        self.fp.seek(offset)
        self._info.load(self.fp)

    def _get_merged_dict(self):
        merged_dict = dict(self)

        # get EXIF extension
        if ExifTags.IFD.Exif in self:
            ifd = self._get_ifd_dict(self[ExifTags.IFD.Exif], ExifTags.IFD.Exif)
            if ifd:
                merged_dict.update(ifd)

        # GPS
        if ExifTags.IFD.GPSInfo in self:
            merged_dict[ExifTags.IFD.GPSInfo] = self._get_ifd_dict(
                self[ExifTags.IFD.GPSInfo], ExifTags.IFD.GPSInfo
            )

        return merged_dict

    def tobytes(self, offset: int = 8) -> bytes:
        from . import TiffImagePlugin

        head = self._get_head()
        ifd = TiffImagePlugin.ImageFileDirectory_v2(ifh=head)
        for tag, value in self.items():
            if tag in [
                ExifTags.IFD.Exif,
                ExifTags.IFD.GPSInfo,
            ] and not isinstance(value, dict):
                value = self.get_ifd(tag)
                if (
                    tag == ExifTags.IFD.Exif
                    and ExifTags.IFD.Interop in value
                    and not isinstance(value[ExifTags.IFD.Interop], dict)
                ):
                    value = value.copy()
                    value[ExifTags.IFD.Interop] = self.get_ifd(ExifTags.IFD.Interop)
            ifd[tag] = value
        return b"Exif\x00\x00" + head + ifd.tobytes(offset)

    def get_ifd(self, tag):
        if tag not in self._ifds:
            if tag == ExifTags.IFD.IFD1:
                if self._info is not None and self._info.next != 0:
                    self._ifds[tag] = self._get_ifd_dict(self._info.next)
            elif tag in [ExifTags.IFD.Exif, ExifTags.IFD.GPSInfo]:
                offset = self._hidden_data.get(tag, self.get(tag))
                if offset is not None:
                    self._ifds[tag] = self._get_ifd_dict(offset, tag)
            elif tag in [ExifTags.IFD.Interop, ExifTags.IFD.Makernote]:
                if ExifTags.IFD.Exif not in self._ifds:
                    self.get_ifd(ExifTags.IFD.Exif)
                tag_data = self._ifds[ExifTags.IFD.Exif][tag]
                if tag == ExifTags.IFD.Makernote:
                    from .TiffImagePlugin import ImageFileDirectory_v2

                    if tag_data[:8] == b"FUJIFILM":
                        ifd_offset = i32le(tag_data, 8)
                        ifd_data = tag_data[ifd_offset:]

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

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

                            if not data:
                                continue

                            makernote[ifd_tag] = handler(
                                ImageFileDirectory_v2(), data, False
                            )
                        self._ifds[tag] = dict(self._fixup_dict(makernote))
                    elif self.get(0x010F) == "Nintendo":
                        makernote = {}
                        for i in range(0, struct.unpack(">H", tag_data[:2])[0]):
                            ifd_tag, typ, count, data = struct.unpack(
                                ">HHL4s", tag_data[i * 12 + 2 : (i + 1) * 12 + 2]
                            )
                            if ifd_tag == 0x1101:
                                # CameraInfo
                                (offset,) = struct.unpack(">L", data)
                                self.fp.seek(offset)

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

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

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

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

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

                                makernote = {0x1101: dict(self._fixup_dict(camerainfo))}
                        self._ifds[tag] = makernote
                else:
                    # Interop
                    self._ifds[tag] = self._get_ifd_dict(tag_data, tag)
        ifd = self._ifds.get(tag, {})
        if tag == ExifTags.IFD.Exif and self._hidden_data:
            ifd = {
                k: v
                for (k, v) in ifd.items()
                if k not in (ExifTags.IFD.Interop, ExifTags.IFD.Makernote)
            }
        return ifd

    def hide_offsets(self) -> None:
        for tag in (ExifTags.IFD.Exif, ExifTags.IFD.GPSInfo):
            if tag in self:
                self._hidden_data[tag] = self[tag]
                del self[tag]

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

        return str(self._data)

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

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

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

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

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

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

```
--- END FILE ---

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

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

Here is an example:

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

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