{
    "file_diffs": [
        {
            "old_file_content": "from PIL import Image, ImageSequence, PngImagePlugin\n\nimport pytest\n\nfrom .helper import PillowTestCase\n\n\nclass TestFilePng(PillowTestCase):\n\n    # APNG browser support tests and fixtures via:\n    # https://philip.html5.org/tests/apng/tests.html\n    # (referenced from https://wiki.mozilla.org/APNG_Specification)\n    def test_apng_basic(self):\n        with Image.open(\"Tests/images/apng/single_frame.png\") as im:\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertIsNone(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/single_frame_default.png\") as im:\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertTrue(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (255, 0, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (255, 0, 0, 255))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n            # test out of bounds seek\n            with self.assertRaises(EOFError):\n                im.seek(2)\n\n            # test rewind support\n            im.seek(0)\n            self.assertEqual(im.getpixel((0, 0)), (255, 0, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (255, 0, 0, 255))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_fdat(self):\n        with Image.open(\"Tests/images/apng/split_fdat.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/split_fdat_zero_chunk.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_dispose(self):\n        with Image.open(\"Tests/images/apng/dispose_op_none.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background_final.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_final.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_first.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n    def test_apng_dispose_region(self):\n        with Image.open(\"Tests/images/apng/dispose_op_none_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\n            \"Tests/images/apng/dispose_op_background_before_region.png\"\n        ) as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 255, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_blend(self):\n        with Image.open(\"Tests/images/apng/blend_op_source_solid.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/blend_op_source_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/blend_op_source_near_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 2))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 2))\n\n        with Image.open(\"Tests/images/apng/blend_op_over.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/blend_op_over_near_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 97))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_chunk_order(self):\n        with Image.open(\"Tests/images/apng/fctl_actl.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_delay(self):\n        with Image.open(\"Tests/images/apng/delay.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_round.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_short_max.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_zero_denom.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_zero_numer.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 0.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 0.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n    def test_apng_num_plays(self):\n        with Image.open(\"Tests/images/apng/num_plays.png\") as im:\n            self.assertEqual(im.info.get(\"loop\"), 0)\n\n        with Image.open(\"Tests/images/apng/num_plays_1.png\") as im:\n            self.assertEqual(im.info.get(\"loop\"), 1)\n\n    def test_apng_mode(self):\n        with Image.open(\"Tests/images/apng/mode_16bit.png\") as im:\n            self.assertEqual(im.mode, \"RGBA\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 128, 191))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 128, 191))\n\n        with Image.open(\"Tests/images/apng/mode_greyscale.png\") as im:\n            self.assertEqual(im.mode, \"L\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), 128)\n            self.assertEqual(im.getpixel((64, 32)), 255)\n\n        with Image.open(\"Tests/images/apng/mode_greyscale_alpha.png\") as im:\n            self.assertEqual(im.mode, \"LA\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (128, 191))\n            self.assertEqual(im.getpixel((64, 32)), (128, 191))\n\n        with Image.open(\"Tests/images/apng/mode_palette.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGB\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0))\n\n        with Image.open(\"Tests/images/apng/mode_palette_alpha.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGBA\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/mode_palette_1bit_alpha.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGBA\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 255, 128))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 255, 128))\n\n    def test_apng_chunk_errors(self):\n        with Image.open(\"Tests/images/apng/chunk_no_actl.png\") as im:\n            self.assertFalse(im.is_animated)\n\n        def open():\n            with Image.open(\"Tests/images/apng/chunk_multi_actl.png\") as im:\n                im.load()\n            self.assertFalse(im.is_animated)\n\n        pytest.warns(UserWarning, open)\n\n        with Image.open(\"Tests/images/apng/chunk_actl_after_idat.png\") as im:\n            self.assertFalse(im.is_animated)\n\n        with Image.open(\"Tests/images/apng/chunk_no_fctl.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n        with Image.open(\"Tests/images/apng/chunk_repeat_fctl.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n        with Image.open(\"Tests/images/apng/chunk_no_fdat.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n    def test_apng_syntax_errors(self):\n        def open_frames_zero():\n            with Image.open(\"Tests/images/apng/syntax_num_frames_zero.png\") as im:\n                self.assertFalse(im.is_animated)\n                with self.assertRaises(OSError):\n                    im.load()\n\n        pytest.warns(UserWarning, open_frames_zero)\n\n        def open_frames_zero_default():\n            with Image.open(\n                \"Tests/images/apng/syntax_num_frames_zero_default.png\"\n            ) as im:\n                self.assertFalse(im.is_animated)\n                im.load()\n\n        pytest.warns(UserWarning, open_frames_zero_default)\n\n        # we can handle this case gracefully\n        exception = None\n        with Image.open(\"Tests/images/apng/syntax_num_frames_low.png\") as im:\n            try:\n                im.seek(im.n_frames - 1)\n            except Exception as e:\n                exception = e\n            self.assertIsNone(exception)\n\n        with self.assertRaises(SyntaxError):\n            with Image.open(\"Tests/images/apng/syntax_num_frames_high.png\") as im:\n                im.seek(im.n_frames - 1)\n                im.load()\n\n        def open():\n            with Image.open(\"Tests/images/apng/syntax_num_frames_invalid.png\") as im:\n                self.assertFalse(im.is_animated)\n                im.load()\n\n        pytest.warns(UserWarning, open)\n\n    def test_apng_sequence_errors(self):\n        test_files = [\n            \"sequence_start.png\",\n            \"sequence_gap.png\",\n            \"sequence_repeat.png\",\n            \"sequence_repeat_chunk.png\",\n            \"sequence_reorder.png\",\n            \"sequence_reorder_chunk.png\",\n            \"sequence_fdat_fctl.png\",\n        ]\n        for f in test_files:\n            with self.assertRaises(SyntaxError):\n                with Image.open(\"Tests/images/apng/{0}\".format(f)) as im:\n                    im.seek(im.n_frames - 1)\n                    im.load()\n\n    def test_apng_save(self):\n        with Image.open(\"Tests/images/apng/single_frame.png\") as im:\n            test_file = self.tempfile(\"temp.png\")\n            im.save(test_file, save_all=True)\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertIsNone(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/single_frame_default.png\") as im:\n            frames = []\n            for frame_im in ImageSequence.Iterator(im):\n                frames.append(frame_im.copy())\n            frames[0].save(\n                test_file, save_all=True, default_image=True, append_images=frames[1:]\n            )\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertTrue(im.info.get(\"default_image\"))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_save_split_fdat(self):\n        # test to make sure we do not generate sequence errors when writing\n        # frames with image data spanning multiple fdAT chunks (in this case\n        # both the default image and first animation frame will span multiple\n        # data chunks)\n        test_file = self.tempfile(\"temp.png\")\n        with Image.open(\"Tests/images/old-style-jpeg-compression.png\") as im:\n            frames = [im.copy(), Image.new(\"RGBA\", im.size, (255, 0, 0, 255))]\n            im.save(\n                test_file, save_all=True, default_image=True, append_images=frames,\n            )\n        with Image.open(test_file) as im:\n            exception = None\n            try:\n                im.seek(im.n_frames - 1)\n                im.load()\n            except Exception as e:\n                exception = e\n            self.assertIsNone(exception)\n\n    def test_apng_save_duration_loop(self):\n        test_file = self.tempfile(\"temp.png\")\n        with Image.open(\"Tests/images/apng/delay.png\") as im:\n            frames = []\n            durations = []\n            loop = im.info.get(\"loop\")\n            default_image = im.info.get(\"default_image\")\n            for i, frame_im in enumerate(ImageSequence.Iterator(im)):\n                frames.append(frame_im.copy())\n                if i != 0 or not default_image:\n                    durations.append(frame_im.info.get(\"duration\", 0))\n            frames[0].save(\n                test_file,\n                save_all=True,\n                default_image=default_image,\n                append_images=frames[1:],\n                duration=durations,\n                loop=loop,\n            )\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertEqual(im.info.get(\"loop\"), loop)\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        # test removal of duplicated frames\n        frame = Image.new(\"RGBA\", (128, 64), (255, 0, 0, 255))\n        frame.save(test_file, save_all=True, append_images=[frame], duration=[500, 250])\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertEqual(im.n_frames, 1)\n            self.assertEqual(im.info.get(\"duration\"), 750)\n\n    def test_apng_save_disposal(self):\n        test_file = self.tempfile(\"temp.png\")\n        size = (128, 64)\n        red = Image.new(\"RGBA\", size, (255, 0, 0, 255))\n        green = Image.new(\"RGBA\", size, (0, 255, 0, 255))\n        transparent = Image.new(\"RGBA\", size, (0, 0, 0, 0))\n\n        # test APNG_DISPOSE_OP_NONE\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, transparent],\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_DISPOSE_OP_BACKGROUND\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_BACKGROUND,\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, transparent],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_BACKGROUND,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_DISPOSE_OP_PREVIOUS\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_PREVIOUS,\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, red, transparent],\n            default_image=True,\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(3)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_PREVIOUS,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_save_blend(self):\n        test_file = self.tempfile(\"temp.png\")\n        size = (128, 64)\n        red = Image.new(\"RGBA\", size, (255, 0, 0, 255))\n        green = Image.new(\"RGBA\", size, (0, 255, 0, 255))\n        transparent = Image.new(\"RGBA\", size, (0, 0, 0, 0))\n\n        # test APNG_BLEND_OP_SOURCE on solid color\n        blend = [\n            PngImagePlugin.APNG_BLEND_OP_OVER,\n            PngImagePlugin.APNG_BLEND_OP_SOURCE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, green],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=blend,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_BLEND_OP_SOURCE on transparent color\n        blend = [\n            PngImagePlugin.APNG_BLEND_OP_OVER,\n            PngImagePlugin.APNG_BLEND_OP_SOURCE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, transparent],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=blend,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        # test APNG_BLEND_OP_OVER\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, transparent],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n",
            "new_file_content": "from PIL import Image, ImageSequence, PngImagePlugin\n\nimport pytest\n\nfrom .helper import PillowTestCase\n\n\nclass TestFilePng(PillowTestCase):\n\n    # APNG browser support tests and fixtures via:\n    # https://philip.html5.org/tests/apng/tests.html\n    # (referenced from https://wiki.mozilla.org/APNG_Specification)\n    def test_apng_basic(self):\n        with Image.open(\"Tests/images/apng/single_frame.png\") as im:\n            self.assertFalse(im.is_animated)\n            self.assertEqual(im.n_frames, 1)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertIsNone(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/single_frame_default.png\") as im:\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.n_frames, 2)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertTrue(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (255, 0, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (255, 0, 0, 255))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n            # test out of bounds seek\n            with self.assertRaises(EOFError):\n                im.seek(2)\n\n            # test rewind support\n            im.seek(0)\n            self.assertEqual(im.getpixel((0, 0)), (255, 0, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (255, 0, 0, 255))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_fdat(self):\n        with Image.open(\"Tests/images/apng/split_fdat.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/split_fdat_zero_chunk.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_dispose(self):\n        with Image.open(\"Tests/images/apng/dispose_op_none.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background_final.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_final.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_first.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n    def test_apng_dispose_region(self):\n        with Image.open(\"Tests/images/apng/dispose_op_none_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\n            \"Tests/images/apng/dispose_op_background_before_region.png\"\n        ) as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 255, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_blend(self):\n        with Image.open(\"Tests/images/apng/blend_op_source_solid.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/blend_op_source_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/blend_op_source_near_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 2))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 2))\n\n        with Image.open(\"Tests/images/apng/blend_op_over.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/blend_op_over_near_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 97))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_chunk_order(self):\n        with Image.open(\"Tests/images/apng/fctl_actl.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_delay(self):\n        with Image.open(\"Tests/images/apng/delay.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_round.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_short_max.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_zero_denom.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_zero_numer.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 0.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 0.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n    def test_apng_num_plays(self):\n        with Image.open(\"Tests/images/apng/num_plays.png\") as im:\n            self.assertEqual(im.info.get(\"loop\"), 0)\n\n        with Image.open(\"Tests/images/apng/num_plays_1.png\") as im:\n            self.assertEqual(im.info.get(\"loop\"), 1)\n\n    def test_apng_mode(self):\n        with Image.open(\"Tests/images/apng/mode_16bit.png\") as im:\n            self.assertEqual(im.mode, \"RGBA\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 128, 191))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 128, 191))\n\n        with Image.open(\"Tests/images/apng/mode_greyscale.png\") as im:\n            self.assertEqual(im.mode, \"L\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), 128)\n            self.assertEqual(im.getpixel((64, 32)), 255)\n\n        with Image.open(\"Tests/images/apng/mode_greyscale_alpha.png\") as im:\n            self.assertEqual(im.mode, \"LA\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (128, 191))\n            self.assertEqual(im.getpixel((64, 32)), (128, 191))\n\n        with Image.open(\"Tests/images/apng/mode_palette.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGB\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0))\n\n        with Image.open(\"Tests/images/apng/mode_palette_alpha.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGBA\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/mode_palette_1bit_alpha.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGBA\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 255, 128))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 255, 128))\n\n    def test_apng_chunk_errors(self):\n        with Image.open(\"Tests/images/apng/chunk_no_actl.png\") as im:\n            self.assertFalse(im.is_animated)\n\n        def open():\n            with Image.open(\"Tests/images/apng/chunk_multi_actl.png\") as im:\n                im.load()\n            self.assertFalse(im.is_animated)\n\n        pytest.warns(UserWarning, open)\n\n        with Image.open(\"Tests/images/apng/chunk_actl_after_idat.png\") as im:\n            self.assertFalse(im.is_animated)\n\n        with Image.open(\"Tests/images/apng/chunk_no_fctl.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n        with Image.open(\"Tests/images/apng/chunk_repeat_fctl.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n        with Image.open(\"Tests/images/apng/chunk_no_fdat.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n    def test_apng_syntax_errors(self):\n        def open_frames_zero():\n            with Image.open(\"Tests/images/apng/syntax_num_frames_zero.png\") as im:\n                self.assertFalse(im.is_animated)\n                with self.assertRaises(OSError):\n                    im.load()\n\n        pytest.warns(UserWarning, open_frames_zero)\n\n        def open_frames_zero_default():\n            with Image.open(\n                \"Tests/images/apng/syntax_num_frames_zero_default.png\"\n            ) as im:\n                self.assertFalse(im.is_animated)\n                im.load()\n\n        pytest.warns(UserWarning, open_frames_zero_default)\n\n        # we can handle this case gracefully\n        exception = None\n        with Image.open(\"Tests/images/apng/syntax_num_frames_low.png\") as im:\n            try:\n                im.seek(im.n_frames - 1)\n            except Exception as e:\n                exception = e\n            self.assertIsNone(exception)\n\n        with self.assertRaises(SyntaxError):\n            with Image.open(\"Tests/images/apng/syntax_num_frames_high.png\") as im:\n                im.seek(im.n_frames - 1)\n                im.load()\n\n        def open():\n            with Image.open(\"Tests/images/apng/syntax_num_frames_invalid.png\") as im:\n                self.assertFalse(im.is_animated)\n                im.load()\n\n        pytest.warns(UserWarning, open)\n\n    def test_apng_sequence_errors(self):\n        test_files = [\n            \"sequence_start.png\",\n            \"sequence_gap.png\",\n            \"sequence_repeat.png\",\n            \"sequence_repeat_chunk.png\",\n            \"sequence_reorder.png\",\n            \"sequence_reorder_chunk.png\",\n            \"sequence_fdat_fctl.png\",\n        ]\n        for f in test_files:\n            with self.assertRaises(SyntaxError):\n                with Image.open(\"Tests/images/apng/{0}\".format(f)) as im:\n                    im.seek(im.n_frames - 1)\n                    im.load()\n\n    def test_apng_save(self):\n        with Image.open(\"Tests/images/apng/single_frame.png\") as im:\n            test_file = self.tempfile(\"temp.png\")\n            im.save(test_file, save_all=True)\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertFalse(im.is_animated)\n            self.assertEqual(im.n_frames, 1)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertIsNone(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/single_frame_default.png\") as im:\n            frames = []\n            for frame_im in ImageSequence.Iterator(im):\n                frames.append(frame_im.copy())\n            frames[0].save(\n                test_file, save_all=True, default_image=True, append_images=frames[1:]\n            )\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.n_frames, 2)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertTrue(im.info.get(\"default_image\"))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_save_split_fdat(self):\n        # test to make sure we do not generate sequence errors when writing\n        # frames with image data spanning multiple fdAT chunks (in this case\n        # both the default image and first animation frame will span multiple\n        # data chunks)\n        test_file = self.tempfile(\"temp.png\")\n        with Image.open(\"Tests/images/old-style-jpeg-compression.png\") as im:\n            frames = [im.copy(), Image.new(\"RGBA\", im.size, (255, 0, 0, 255))]\n            im.save(\n                test_file, save_all=True, default_image=True, append_images=frames,\n            )\n        with Image.open(test_file) as im:\n            exception = None\n            try:\n                im.seek(im.n_frames - 1)\n                im.load()\n            except Exception as e:\n                exception = e\n            self.assertIsNone(exception)\n\n    def test_apng_save_duration_loop(self):\n        test_file = self.tempfile(\"temp.png\")\n        with Image.open(\"Tests/images/apng/delay.png\") as im:\n            frames = []\n            durations = []\n            loop = im.info.get(\"loop\")\n            default_image = im.info.get(\"default_image\")\n            for i, frame_im in enumerate(ImageSequence.Iterator(im)):\n                frames.append(frame_im.copy())\n                if i != 0 or not default_image:\n                    durations.append(frame_im.info.get(\"duration\", 0))\n            frames[0].save(\n                test_file,\n                save_all=True,\n                default_image=default_image,\n                append_images=frames[1:],\n                duration=durations,\n                loop=loop,\n            )\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertEqual(im.info.get(\"loop\"), loop)\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        # test removal of duplicated frames\n        frame = Image.new(\"RGBA\", (128, 64), (255, 0, 0, 255))\n        frame.save(test_file, save_all=True, append_images=[frame], duration=[500, 250])\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertEqual(im.n_frames, 1)\n            self.assertEqual(im.info.get(\"duration\"), 750)\n\n    def test_apng_save_disposal(self):\n        test_file = self.tempfile(\"temp.png\")\n        size = (128, 64)\n        red = Image.new(\"RGBA\", size, (255, 0, 0, 255))\n        green = Image.new(\"RGBA\", size, (0, 255, 0, 255))\n        transparent = Image.new(\"RGBA\", size, (0, 0, 0, 0))\n\n        # test APNG_DISPOSE_OP_NONE\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, transparent],\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_DISPOSE_OP_BACKGROUND\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_BACKGROUND,\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, transparent],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_BACKGROUND,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_DISPOSE_OP_PREVIOUS\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_PREVIOUS,\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, red, transparent],\n            default_image=True,\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(3)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_PREVIOUS,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_save_blend(self):\n        test_file = self.tempfile(\"temp.png\")\n        size = (128, 64)\n        red = Image.new(\"RGBA\", size, (255, 0, 0, 255))\n        green = Image.new(\"RGBA\", size, (0, 255, 0, 255))\n        transparent = Image.new(\"RGBA\", size, (0, 0, 0, 0))\n\n        # test APNG_BLEND_OP_SOURCE on solid color\n        blend = [\n            PngImagePlugin.APNG_BLEND_OP_OVER,\n            PngImagePlugin.APNG_BLEND_OP_SOURCE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, green],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=blend,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_BLEND_OP_SOURCE on transparent color\n        blend = [\n            PngImagePlugin.APNG_BLEND_OP_OVER,\n            PngImagePlugin.APNG_BLEND_OP_SOURCE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, transparent],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=blend,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        # test APNG_BLEND_OP_OVER\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, transparent],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n",
            "header": {
                "file": {
                    "path": "Tests/test_file_apng.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "36110e891",
                "new_commit_hash": "b48995ab6",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/Tests/test_file_apng.py"
            },
            "plus_file": {
                "path": "b/Tests/test_file_apng.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 12,
                            "length": 7
                        },
                        "new_range": {
                            "start": 12,
                            "length": 8
                        },
                        "section": "class TestFilePng(PillowTestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "    # (referenced from https://wiki.mozilla.org/APNG_Specification)",
                                "type": "context"
                            },
                            {
                                "content": "    def test_apng_basic(self):",
                                "type": "context"
                            },
                            {
                                "content": "        with Image.open(\"Tests/images/apng/single_frame.png\") as im:",
                                "type": "context"
                            },
                            {
                                "content": "            self.assertTrue(im.is_animated)",
                                "type": "deleted"
                            },
                            {
                                "content": "            self.assertFalse(im.is_animated)",
                                "type": "added"
                            },
                            {
                                "content": "            self.assertEqual(im.n_frames, 1)",
                                "type": "added"
                            },
                            {
                                "content": "            self.assertEqual(im.get_format_mimetype(), \"image/apng\")",
                                "type": "context"
                            },
                            {
                                "content": "            self.assertIsNone(im.info.get(\"default_image\"))",
                                "type": "context"
                            },
                            {
                                "content": "            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Tests/test_file_apng.py",
                            "type": "method",
                            "name": "TestFilePng.test_apng_basic",
                            "content": "class TestFilePng(PillowTestCase):\n\n    # APNG browser support tests and fixtures via:\n    # https://philip.html5.org/tests/apng/tests.html\n    # (referenced from https://wiki.mozilla.org/APNG_Specification)\n    def test_apng_basic(self):\n        with Image.open(\"Tests/images/apng/single_frame.png\") as im:\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertIsNone(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/single_frame_default.png\") as im:\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertTrue(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (255, 0, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (255, 0, 0, 255))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n            # test out of bounds seek\n            with self.assertRaises(EOFError):\n                im.seek(2)\n\n            # test rewind support\n            im.seek(0)\n            self.assertEqual(im.getpixel((0, 0)), (255, 0, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (255, 0, 0, 255))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_fdat(self):\n        with Image.open(\"Tests/images/apng/split_fdat.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/split_fdat_zero_chunk.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_dispose(self):\n        with Image.open(\"Tests/images/apng/dispose_op_none.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background_final.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_final.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_first.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n    def test_apng_dispose_region(self):\n        with Image.open(\"Tests/images/apng/dispose_op_none_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\n            \"Tests/images/apng/dispose_op_background_before_region.png\"\n        ) as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 255, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_blend(self):\n        with Image.open(\"Tests/images/apng/blend_op_source_solid.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/blend_op_source_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/blend_op_source_near_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 2))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 2))\n\n        with Image.open(\"Tests/images/apng/blend_op_over.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/blend_op_over_near_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 97))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_chunk_order(self):\n        with Image.open(\"Tests/images/apng/fctl_actl.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_delay(self):\n        with Image.open(\"Tests/images/apng/delay.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_round.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_short_max.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_zero_denom.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_zero_numer.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 0.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 0.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n    def test_apng_num_plays(self):\n        with Image.open(\"Tests/images/apng/num_plays.png\") as im:\n            self.assertEqual(im.info.get(\"loop\"), 0)\n\n        with Image.open(\"Tests/images/apng/num_plays_1.png\") as im:\n            self.assertEqual(im.info.get(\"loop\"), 1)\n\n    def test_apng_mode(self):\n        with Image.open(\"Tests/images/apng/mode_16bit.png\") as im:\n            self.assertEqual(im.mode, \"RGBA\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 128, 191))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 128, 191))\n\n        with Image.open(\"Tests/images/apng/mode_greyscale.png\") as im:\n            self.assertEqual(im.mode, \"L\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), 128)\n            self.assertEqual(im.getpixel((64, 32)), 255)\n\n        with Image.open(\"Tests/images/apng/mode_greyscale_alpha.png\") as im:\n            self.assertEqual(im.mode, \"LA\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (128, 191))\n            self.assertEqual(im.getpixel((64, 32)), (128, 191))\n\n        with Image.open(\"Tests/images/apng/mode_palette.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGB\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0))\n\n        with Image.open(\"Tests/images/apng/mode_palette_alpha.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGBA\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/mode_palette_1bit_alpha.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGBA\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 255, 128))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 255, 128))\n\n    def test_apng_chunk_errors(self):\n        with Image.open(\"Tests/images/apng/chunk_no_actl.png\") as im:\n            self.assertFalse(im.is_animated)\n\n        def open():\n            with Image.open(\"Tests/images/apng/chunk_multi_actl.png\") as im:\n                im.load()\n            self.assertFalse(im.is_animated)\n\n        pytest.warns(UserWarning, open)\n\n        with Image.open(\"Tests/images/apng/chunk_actl_after_idat.png\") as im:\n            self.assertFalse(im.is_animated)\n\n        with Image.open(\"Tests/images/apng/chunk_no_fctl.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n        with Image.open(\"Tests/images/apng/chunk_repeat_fctl.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n        with Image.open(\"Tests/images/apng/chunk_no_fdat.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n    def test_apng_syntax_errors(self):\n        def open_frames_zero():\n            with Image.open(\"Tests/images/apng/syntax_num_frames_zero.png\") as im:\n                self.assertFalse(im.is_animated)\n                with self.assertRaises(OSError):\n                    im.load()\n\n        pytest.warns(UserWarning, open_frames_zero)\n\n        def open_frames_zero_default():\n            with Image.open(\n                \"Tests/images/apng/syntax_num_frames_zero_default.png\"\n            ) as im:\n                self.assertFalse(im.is_animated)\n                im.load()\n\n        pytest.warns(UserWarning, open_frames_zero_default)\n\n        # we can handle this case gracefully\n        exception = None\n        with Image.open(\"Tests/images/apng/syntax_num_frames_low.png\") as im:\n            try:\n                im.seek(im.n_frames - 1)\n            except Exception as e:\n                exception = e\n            self.assertIsNone(exception)\n\n        with self.assertRaises(SyntaxError):\n            with Image.open(\"Tests/images/apng/syntax_num_frames_high.png\") as im:\n                im.seek(im.n_frames - 1)\n                im.load()\n\n        def open():\n            with Image.open(\"Tests/images/apng/syntax_num_frames_invalid.png\") as im:\n                self.assertFalse(im.is_animated)\n                im.load()\n\n        pytest.warns(UserWarning, open)\n\n    def test_apng_sequence_errors(self):\n        test_files = [\n            \"sequence_start.png\",\n            \"sequence_gap.png\",\n            \"sequence_repeat.png\",\n            \"sequence_repeat_chunk.png\",\n            \"sequence_reorder.png\",\n            \"sequence_reorder_chunk.png\",\n            \"sequence_fdat_fctl.png\",\n        ]\n        for f in test_files:\n            with self.assertRaises(SyntaxError):\n                with Image.open(\"Tests/images/apng/{0}\".format(f)) as im:\n                    im.seek(im.n_frames - 1)\n                    im.load()\n\n    def test_apng_save(self):\n        with Image.open(\"Tests/images/apng/single_frame.png\") as im:\n            test_file = self.tempfile(\"temp.png\")\n            im.save(test_file, save_all=True)\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertIsNone(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/single_frame_default.png\") as im:\n            frames = []\n            for frame_im in ImageSequence.Iterator(im):\n                frames.append(frame_im.copy())\n            frames[0].save(\n                test_file, save_all=True, default_image=True, append_images=frames[1:]\n            )\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertTrue(im.info.get(\"default_image\"))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_save_split_fdat(self):\n        # test to make sure we do not generate sequence errors when writing\n        # frames with image data spanning multiple fdAT chunks (in this case\n        # both the default image and first animation frame will span multiple\n        # data chunks)\n        test_file = self.tempfile(\"temp.png\")\n        with Image.open(\"Tests/images/old-style-jpeg-compression.png\") as im:\n            frames = [im.copy(), Image.new(\"RGBA\", im.size, (255, 0, 0, 255))]\n            im.save(\n                test_file, save_all=True, default_image=True, append_images=frames,\n            )\n        with Image.open(test_file) as im:\n            exception = None\n            try:\n                im.seek(im.n_frames - 1)\n                im.load()\n            except Exception as e:\n                exception = e\n            self.assertIsNone(exception)\n\n    def test_apng_save_duration_loop(self):\n        test_file = self.tempfile(\"temp.png\")\n        with Image.open(\"Tests/images/apng/delay.png\") as im:\n            frames = []\n            durations = []\n            loop = im.info.get(\"loop\")\n            default_image = im.info.get(\"default_image\")\n            for i, frame_im in enumerate(ImageSequence.Iterator(im)):\n                frames.append(frame_im.copy())\n                if i != 0 or not default_image:\n                    durations.append(frame_im.info.get(\"duration\", 0))\n            frames[0].save(\n                test_file,\n                save_all=True,\n                default_image=default_image,\n                append_images=frames[1:],\n                duration=durations,\n                loop=loop,\n            )\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertEqual(im.info.get(\"loop\"), loop)\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        # test removal of duplicated frames\n        frame = Image.new(\"RGBA\", (128, 64), (255, 0, 0, 255))\n        frame.save(test_file, save_all=True, append_images=[frame], duration=[500, 250])\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertEqual(im.n_frames, 1)\n            self.assertEqual(im.info.get(\"duration\"), 750)\n\n    def test_apng_save_disposal(self):\n        test_file = self.tempfile(\"temp.png\")\n        size = (128, 64)\n        red = Image.new(\"RGBA\", size, (255, 0, 0, 255))\n        green = Image.new(\"RGBA\", size, (0, 255, 0, 255))\n        transparent = Image.new(\"RGBA\", size, (0, 0, 0, 0))\n\n        # test APNG_DISPOSE_OP_NONE\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, transparent],\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_DISPOSE_OP_BACKGROUND\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_BACKGROUND,\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, transparent],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_BACKGROUND,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_DISPOSE_OP_PREVIOUS\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_PREVIOUS,\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, red, transparent],\n            default_image=True,\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(3)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_PREVIOUS,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_save_blend(self):\n        test_file = self.tempfile(\"temp.png\")\n        size = (128, 64)\n        red = Image.new(\"RGBA\", size, (255, 0, 0, 255))\n        green = Image.new(\"RGBA\", size, (0, 255, 0, 255))\n        transparent = Image.new(\"RGBA\", size, (0, 0, 0, 0))\n\n        # test APNG_BLEND_OP_SOURCE on solid color\n        blend = [\n            PngImagePlugin.APNG_BLEND_OP_OVER,\n            PngImagePlugin.APNG_BLEND_OP_SOURCE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, green],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=blend,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_BLEND_OP_SOURCE on transparent color\n        blend = [\n            PngImagePlugin.APNG_BLEND_OP_OVER,\n            PngImagePlugin.APNG_BLEND_OP_SOURCE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, transparent],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=blend,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        # test APNG_BLEND_OP_OVER\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, transparent],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 13,
                            "end_lineno": 41,
                            "parent": {
                                "file_name": "Tests/test_file_apng.py",
                                "type": "class",
                                "name": "TestFilePng",
                                "content": "class TestFilePng(PillowTestCase):\n\n    # APNG browser support tests and fixtures via:\n    # https://philip.html5.org/tests/apng/tests.html\n    # (referenced from https://wiki.mozilla.org/APNG_Specification)\n    def test_apng_basic(self):\n        with Image.open(\"Tests/images/apng/single_frame.png\") as im:\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertIsNone(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/single_frame_default.png\") as im:\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertTrue(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (255, 0, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (255, 0, 0, 255))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n            # test out of bounds seek\n            with self.assertRaises(EOFError):\n                im.seek(2)\n\n            # test rewind support\n            im.seek(0)\n            self.assertEqual(im.getpixel((0, 0)), (255, 0, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (255, 0, 0, 255))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_fdat(self):\n        with Image.open(\"Tests/images/apng/split_fdat.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/split_fdat_zero_chunk.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_dispose(self):\n        with Image.open(\"Tests/images/apng/dispose_op_none.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background_final.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_final.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_first.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n    def test_apng_dispose_region(self):\n        with Image.open(\"Tests/images/apng/dispose_op_none_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\n            \"Tests/images/apng/dispose_op_background_before_region.png\"\n        ) as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 255, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_blend(self):\n        with Image.open(\"Tests/images/apng/blend_op_source_solid.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/blend_op_source_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/blend_op_source_near_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 2))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 2))\n\n        with Image.open(\"Tests/images/apng/blend_op_over.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/blend_op_over_near_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 97))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_chunk_order(self):\n        with Image.open(\"Tests/images/apng/fctl_actl.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_delay(self):\n        with Image.open(\"Tests/images/apng/delay.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_round.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_short_max.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_zero_denom.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_zero_numer.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 0.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 0.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n    def test_apng_num_plays(self):\n        with Image.open(\"Tests/images/apng/num_plays.png\") as im:\n            self.assertEqual(im.info.get(\"loop\"), 0)\n\n        with Image.open(\"Tests/images/apng/num_plays_1.png\") as im:\n            self.assertEqual(im.info.get(\"loop\"), 1)\n\n    def test_apng_mode(self):\n        with Image.open(\"Tests/images/apng/mode_16bit.png\") as im:\n            self.assertEqual(im.mode, \"RGBA\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 128, 191))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 128, 191))\n\n        with Image.open(\"Tests/images/apng/mode_greyscale.png\") as im:\n            self.assertEqual(im.mode, \"L\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), 128)\n            self.assertEqual(im.getpixel((64, 32)), 255)\n\n        with Image.open(\"Tests/images/apng/mode_greyscale_alpha.png\") as im:\n            self.assertEqual(im.mode, \"LA\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (128, 191))\n            self.assertEqual(im.getpixel((64, 32)), (128, 191))\n\n        with Image.open(\"Tests/images/apng/mode_palette.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGB\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0))\n\n        with Image.open(\"Tests/images/apng/mode_palette_alpha.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGBA\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/mode_palette_1bit_alpha.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGBA\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 255, 128))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 255, 128))\n\n    def test_apng_chunk_errors(self):\n        with Image.open(\"Tests/images/apng/chunk_no_actl.png\") as im:\n            self.assertFalse(im.is_animated)\n\n        def open():\n            with Image.open(\"Tests/images/apng/chunk_multi_actl.png\") as im:\n                im.load()\n            self.assertFalse(im.is_animated)\n\n        pytest.warns(UserWarning, open)\n\n        with Image.open(\"Tests/images/apng/chunk_actl_after_idat.png\") as im:\n            self.assertFalse(im.is_animated)\n\n        with Image.open(\"Tests/images/apng/chunk_no_fctl.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n        with Image.open(\"Tests/images/apng/chunk_repeat_fctl.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n        with Image.open(\"Tests/images/apng/chunk_no_fdat.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n    def test_apng_syntax_errors(self):\n        def open_frames_zero():\n            with Image.open(\"Tests/images/apng/syntax_num_frames_zero.png\") as im:\n                self.assertFalse(im.is_animated)\n                with self.assertRaises(OSError):\n                    im.load()\n\n        pytest.warns(UserWarning, open_frames_zero)\n\n        def open_frames_zero_default():\n            with Image.open(\n                \"Tests/images/apng/syntax_num_frames_zero_default.png\"\n            ) as im:\n                self.assertFalse(im.is_animated)\n                im.load()\n\n        pytest.warns(UserWarning, open_frames_zero_default)\n\n        # we can handle this case gracefully\n        exception = None\n        with Image.open(\"Tests/images/apng/syntax_num_frames_low.png\") as im:\n            try:\n                im.seek(im.n_frames - 1)\n            except Exception as e:\n                exception = e\n            self.assertIsNone(exception)\n\n        with self.assertRaises(SyntaxError):\n            with Image.open(\"Tests/images/apng/syntax_num_frames_high.png\") as im:\n                im.seek(im.n_frames - 1)\n                im.load()\n\n        def open():\n            with Image.open(\"Tests/images/apng/syntax_num_frames_invalid.png\") as im:\n                self.assertFalse(im.is_animated)\n                im.load()\n\n        pytest.warns(UserWarning, open)\n\n    def test_apng_sequence_errors(self):\n        test_files = [\n            \"sequence_start.png\",\n            \"sequence_gap.png\",\n            \"sequence_repeat.png\",\n            \"sequence_repeat_chunk.png\",\n            \"sequence_reorder.png\",\n            \"sequence_reorder_chunk.png\",\n            \"sequence_fdat_fctl.png\",\n        ]\n        for f in test_files:\n            with self.assertRaises(SyntaxError):\n                with Image.open(\"Tests/images/apng/{0}\".format(f)) as im:\n                    im.seek(im.n_frames - 1)\n                    im.load()\n\n    def test_apng_save(self):\n        with Image.open(\"Tests/images/apng/single_frame.png\") as im:\n            test_file = self.tempfile(\"temp.png\")\n            im.save(test_file, save_all=True)\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertIsNone(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/single_frame_default.png\") as im:\n            frames = []\n            for frame_im in ImageSequence.Iterator(im):\n                frames.append(frame_im.copy())\n            frames[0].save(\n                test_file, save_all=True, default_image=True, append_images=frames[1:]\n            )\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertTrue(im.info.get(\"default_image\"))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_save_split_fdat(self):\n        # test to make sure we do not generate sequence errors when writing\n        # frames with image data spanning multiple fdAT chunks (in this case\n        # both the default image and first animation frame will span multiple\n        # data chunks)\n        test_file = self.tempfile(\"temp.png\")\n        with Image.open(\"Tests/images/old-style-jpeg-compression.png\") as im:\n            frames = [im.copy(), Image.new(\"RGBA\", im.size, (255, 0, 0, 255))]\n            im.save(\n                test_file, save_all=True, default_image=True, append_images=frames,\n            )\n        with Image.open(test_file) as im:\n            exception = None\n            try:\n                im.seek(im.n_frames - 1)\n                im.load()\n            except Exception as e:\n                exception = e\n            self.assertIsNone(exception)\n\n    def test_apng_save_duration_loop(self):\n        test_file = self.tempfile(\"temp.png\")\n        with Image.open(\"Tests/images/apng/delay.png\") as im:\n            frames = []\n            durations = []\n            loop = im.info.get(\"loop\")\n            default_image = im.info.get(\"default_image\")\n            for i, frame_im in enumerate(ImageSequence.Iterator(im)):\n                frames.append(frame_im.copy())\n                if i != 0 or not default_image:\n                    durations.append(frame_im.info.get(\"duration\", 0))\n            frames[0].save(\n                test_file,\n                save_all=True,\n                default_image=default_image,\n                append_images=frames[1:],\n                duration=durations,\n                loop=loop,\n            )\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertEqual(im.info.get(\"loop\"), loop)\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        # test removal of duplicated frames\n        frame = Image.new(\"RGBA\", (128, 64), (255, 0, 0, 255))\n        frame.save(test_file, save_all=True, append_images=[frame], duration=[500, 250])\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertEqual(im.n_frames, 1)\n            self.assertEqual(im.info.get(\"duration\"), 750)\n\n    def test_apng_save_disposal(self):\n        test_file = self.tempfile(\"temp.png\")\n        size = (128, 64)\n        red = Image.new(\"RGBA\", size, (255, 0, 0, 255))\n        green = Image.new(\"RGBA\", size, (0, 255, 0, 255))\n        transparent = Image.new(\"RGBA\", size, (0, 0, 0, 0))\n\n        # test APNG_DISPOSE_OP_NONE\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, transparent],\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_DISPOSE_OP_BACKGROUND\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_BACKGROUND,\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, transparent],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_BACKGROUND,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_DISPOSE_OP_PREVIOUS\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_PREVIOUS,\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, red, transparent],\n            default_image=True,\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(3)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_PREVIOUS,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_save_blend(self):\n        test_file = self.tempfile(\"temp.png\")\n        size = (128, 64)\n        red = Image.new(\"RGBA\", size, (255, 0, 0, 255))\n        green = Image.new(\"RGBA\", size, (0, 255, 0, 255))\n        transparent = Image.new(\"RGBA\", size, (0, 0, 0, 0))\n\n        # test APNG_BLEND_OP_SOURCE on solid color\n        blend = [\n            PngImagePlugin.APNG_BLEND_OP_OVER,\n            PngImagePlugin.APNG_BLEND_OP_SOURCE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, green],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=blend,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_BLEND_OP_SOURCE on transparent color\n        blend = [\n            PngImagePlugin.APNG_BLEND_OP_OVER,\n            PngImagePlugin.APNG_BLEND_OP_SOURCE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, transparent],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=blend,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        # test APNG_BLEND_OP_OVER\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, transparent],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 8,
                                "end_lineno": 544,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "Tests/test_file_apng.py",
                            "type": "class",
                            "name": "TestFilePng",
                            "content": "class TestFilePng(PillowTestCase):\n\n    # APNG browser support tests and fixtures via:\n    # https://philip.html5.org/tests/apng/tests.html\n    # (referenced from https://wiki.mozilla.org/APNG_Specification)\n    def test_apng_basic(self):\n        with Image.open(\"Tests/images/apng/single_frame.png\") as im:\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertIsNone(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/single_frame_default.png\") as im:\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertTrue(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (255, 0, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (255, 0, 0, 255))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n            # test out of bounds seek\n            with self.assertRaises(EOFError):\n                im.seek(2)\n\n            # test rewind support\n            im.seek(0)\n            self.assertEqual(im.getpixel((0, 0)), (255, 0, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (255, 0, 0, 255))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_fdat(self):\n        with Image.open(\"Tests/images/apng/split_fdat.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/split_fdat_zero_chunk.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_dispose(self):\n        with Image.open(\"Tests/images/apng/dispose_op_none.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background_final.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_final.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_first.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n    def test_apng_dispose_region(self):\n        with Image.open(\"Tests/images/apng/dispose_op_none_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\n            \"Tests/images/apng/dispose_op_background_before_region.png\"\n        ) as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 255, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_blend(self):\n        with Image.open(\"Tests/images/apng/blend_op_source_solid.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/blend_op_source_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/blend_op_source_near_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 2))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 2))\n\n        with Image.open(\"Tests/images/apng/blend_op_over.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/blend_op_over_near_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 97))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_chunk_order(self):\n        with Image.open(\"Tests/images/apng/fctl_actl.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_delay(self):\n        with Image.open(\"Tests/images/apng/delay.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_round.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_short_max.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_zero_denom.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_zero_numer.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 0.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 0.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n    def test_apng_num_plays(self):\n        with Image.open(\"Tests/images/apng/num_plays.png\") as im:\n            self.assertEqual(im.info.get(\"loop\"), 0)\n\n        with Image.open(\"Tests/images/apng/num_plays_1.png\") as im:\n            self.assertEqual(im.info.get(\"loop\"), 1)\n\n    def test_apng_mode(self):\n        with Image.open(\"Tests/images/apng/mode_16bit.png\") as im:\n            self.assertEqual(im.mode, \"RGBA\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 128, 191))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 128, 191))\n\n        with Image.open(\"Tests/images/apng/mode_greyscale.png\") as im:\n            self.assertEqual(im.mode, \"L\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), 128)\n            self.assertEqual(im.getpixel((64, 32)), 255)\n\n        with Image.open(\"Tests/images/apng/mode_greyscale_alpha.png\") as im:\n            self.assertEqual(im.mode, \"LA\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (128, 191))\n            self.assertEqual(im.getpixel((64, 32)), (128, 191))\n\n        with Image.open(\"Tests/images/apng/mode_palette.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGB\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0))\n\n        with Image.open(\"Tests/images/apng/mode_palette_alpha.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGBA\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/mode_palette_1bit_alpha.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGBA\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 255, 128))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 255, 128))\n\n    def test_apng_chunk_errors(self):\n        with Image.open(\"Tests/images/apng/chunk_no_actl.png\") as im:\n            self.assertFalse(im.is_animated)\n\n        def open():\n            with Image.open(\"Tests/images/apng/chunk_multi_actl.png\") as im:\n                im.load()\n            self.assertFalse(im.is_animated)\n\n        pytest.warns(UserWarning, open)\n\n        with Image.open(\"Tests/images/apng/chunk_actl_after_idat.png\") as im:\n            self.assertFalse(im.is_animated)\n\n        with Image.open(\"Tests/images/apng/chunk_no_fctl.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n        with Image.open(\"Tests/images/apng/chunk_repeat_fctl.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n        with Image.open(\"Tests/images/apng/chunk_no_fdat.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n    def test_apng_syntax_errors(self):\n        def open_frames_zero():\n            with Image.open(\"Tests/images/apng/syntax_num_frames_zero.png\") as im:\n                self.assertFalse(im.is_animated)\n                with self.assertRaises(OSError):\n                    im.load()\n\n        pytest.warns(UserWarning, open_frames_zero)\n\n        def open_frames_zero_default():\n            with Image.open(\n                \"Tests/images/apng/syntax_num_frames_zero_default.png\"\n            ) as im:\n                self.assertFalse(im.is_animated)\n                im.load()\n\n        pytest.warns(UserWarning, open_frames_zero_default)\n\n        # we can handle this case gracefully\n        exception = None\n        with Image.open(\"Tests/images/apng/syntax_num_frames_low.png\") as im:\n            try:\n                im.seek(im.n_frames - 1)\n            except Exception as e:\n                exception = e\n            self.assertIsNone(exception)\n\n        with self.assertRaises(SyntaxError):\n            with Image.open(\"Tests/images/apng/syntax_num_frames_high.png\") as im:\n                im.seek(im.n_frames - 1)\n                im.load()\n\n        def open():\n            with Image.open(\"Tests/images/apng/syntax_num_frames_invalid.png\") as im:\n                self.assertFalse(im.is_animated)\n                im.load()\n\n        pytest.warns(UserWarning, open)\n\n    def test_apng_sequence_errors(self):\n        test_files = [\n            \"sequence_start.png\",\n            \"sequence_gap.png\",\n            \"sequence_repeat.png\",\n            \"sequence_repeat_chunk.png\",\n            \"sequence_reorder.png\",\n            \"sequence_reorder_chunk.png\",\n            \"sequence_fdat_fctl.png\",\n        ]\n        for f in test_files:\n            with self.assertRaises(SyntaxError):\n                with Image.open(\"Tests/images/apng/{0}\".format(f)) as im:\n                    im.seek(im.n_frames - 1)\n                    im.load()\n\n    def test_apng_save(self):\n        with Image.open(\"Tests/images/apng/single_frame.png\") as im:\n            test_file = self.tempfile(\"temp.png\")\n            im.save(test_file, save_all=True)\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertIsNone(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/single_frame_default.png\") as im:\n            frames = []\n            for frame_im in ImageSequence.Iterator(im):\n                frames.append(frame_im.copy())\n            frames[0].save(\n                test_file, save_all=True, default_image=True, append_images=frames[1:]\n            )\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertTrue(im.info.get(\"default_image\"))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_save_split_fdat(self):\n        # test to make sure we do not generate sequence errors when writing\n        # frames with image data spanning multiple fdAT chunks (in this case\n        # both the default image and first animation frame will span multiple\n        # data chunks)\n        test_file = self.tempfile(\"temp.png\")\n        with Image.open(\"Tests/images/old-style-jpeg-compression.png\") as im:\n            frames = [im.copy(), Image.new(\"RGBA\", im.size, (255, 0, 0, 255))]\n            im.save(\n                test_file, save_all=True, default_image=True, append_images=frames,\n            )\n        with Image.open(test_file) as im:\n            exception = None\n            try:\n                im.seek(im.n_frames - 1)\n                im.load()\n            except Exception as e:\n                exception = e\n            self.assertIsNone(exception)\n\n    def test_apng_save_duration_loop(self):\n        test_file = self.tempfile(\"temp.png\")\n        with Image.open(\"Tests/images/apng/delay.png\") as im:\n            frames = []\n            durations = []\n            loop = im.info.get(\"loop\")\n            default_image = im.info.get(\"default_image\")\n            for i, frame_im in enumerate(ImageSequence.Iterator(im)):\n                frames.append(frame_im.copy())\n                if i != 0 or not default_image:\n                    durations.append(frame_im.info.get(\"duration\", 0))\n            frames[0].save(\n                test_file,\n                save_all=True,\n                default_image=default_image,\n                append_images=frames[1:],\n                duration=durations,\n                loop=loop,\n            )\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertEqual(im.info.get(\"loop\"), loop)\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        # test removal of duplicated frames\n        frame = Image.new(\"RGBA\", (128, 64), (255, 0, 0, 255))\n        frame.save(test_file, save_all=True, append_images=[frame], duration=[500, 250])\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertEqual(im.n_frames, 1)\n            self.assertEqual(im.info.get(\"duration\"), 750)\n\n    def test_apng_save_disposal(self):\n        test_file = self.tempfile(\"temp.png\")\n        size = (128, 64)\n        red = Image.new(\"RGBA\", size, (255, 0, 0, 255))\n        green = Image.new(\"RGBA\", size, (0, 255, 0, 255))\n        transparent = Image.new(\"RGBA\", size, (0, 0, 0, 0))\n\n        # test APNG_DISPOSE_OP_NONE\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, transparent],\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_DISPOSE_OP_BACKGROUND\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_BACKGROUND,\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, transparent],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_BACKGROUND,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_DISPOSE_OP_PREVIOUS\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_PREVIOUS,\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, red, transparent],\n            default_image=True,\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(3)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_PREVIOUS,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_save_blend(self):\n        test_file = self.tempfile(\"temp.png\")\n        size = (128, 64)\n        red = Image.new(\"RGBA\", size, (255, 0, 0, 255))\n        green = Image.new(\"RGBA\", size, (0, 255, 0, 255))\n        transparent = Image.new(\"RGBA\", size, (0, 0, 0, 0))\n\n        # test APNG_BLEND_OP_SOURCE on solid color\n        blend = [\n            PngImagePlugin.APNG_BLEND_OP_OVER,\n            PngImagePlugin.APNG_BLEND_OP_SOURCE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, green],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=blend,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_BLEND_OP_SOURCE on transparent color\n        blend = [\n            PngImagePlugin.APNG_BLEND_OP_OVER,\n            PngImagePlugin.APNG_BLEND_OP_SOURCE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, transparent],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=blend,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        # test APNG_BLEND_OP_OVER\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, transparent],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 8,
                            "end_lineno": 544,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 20,
                            "length": 6
                        },
                        "new_range": {
                            "start": 21,
                            "length": 7
                        },
                        "section": "class TestFilePng(PillowTestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        with Image.open(\"Tests/images/apng/single_frame_default.png\") as im:",
                                "type": "context"
                            },
                            {
                                "content": "            self.assertTrue(im.is_animated)",
                                "type": "context"
                            },
                            {
                                "content": "            self.assertEqual(im.n_frames, 2)",
                                "type": "added"
                            },
                            {
                                "content": "            self.assertEqual(im.get_format_mimetype(), \"image/apng\")",
                                "type": "context"
                            },
                            {
                                "content": "            self.assertTrue(im.info.get(\"default_image\"))",
                                "type": "context"
                            },
                            {
                                "content": "            self.assertEqual(im.getpixel((0, 0)), (255, 0, 0, 255))",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Tests/test_file_apng.py",
                            "type": "method",
                            "name": "TestFilePng.test_apng_basic",
                            "content": "class TestFilePng(PillowTestCase):\n\n    # APNG browser support tests and fixtures via:\n    # https://philip.html5.org/tests/apng/tests.html\n    # (referenced from https://wiki.mozilla.org/APNG_Specification)\n    def test_apng_basic(self):\n        with Image.open(\"Tests/images/apng/single_frame.png\") as im:\n            self.assertFalse(im.is_animated)\n            self.assertEqual(im.n_frames, 1)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertIsNone(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/single_frame_default.png\") as im:\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.n_frames, 2)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertTrue(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (255, 0, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (255, 0, 0, 255))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n            # test out of bounds seek\n            with self.assertRaises(EOFError):\n                im.seek(2)\n\n            # test rewind support\n            im.seek(0)\n            self.assertEqual(im.getpixel((0, 0)), (255, 0, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (255, 0, 0, 255))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_fdat(self):\n        with Image.open(\"Tests/images/apng/split_fdat.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/split_fdat_zero_chunk.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_dispose(self):\n        with Image.open(\"Tests/images/apng/dispose_op_none.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background_final.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_final.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_first.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n    def test_apng_dispose_region(self):\n        with Image.open(\"Tests/images/apng/dispose_op_none_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\n            \"Tests/images/apng/dispose_op_background_before_region.png\"\n        ) as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 255, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_blend(self):\n        with Image.open(\"Tests/images/apng/blend_op_source_solid.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/blend_op_source_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/blend_op_source_near_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 2))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 2))\n\n        with Image.open(\"Tests/images/apng/blend_op_over.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/blend_op_over_near_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 97))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_chunk_order(self):\n        with Image.open(\"Tests/images/apng/fctl_actl.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_delay(self):\n        with Image.open(\"Tests/images/apng/delay.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_round.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_short_max.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_zero_denom.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_zero_numer.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 0.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 0.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n    def test_apng_num_plays(self):\n        with Image.open(\"Tests/images/apng/num_plays.png\") as im:\n            self.assertEqual(im.info.get(\"loop\"), 0)\n\n        with Image.open(\"Tests/images/apng/num_plays_1.png\") as im:\n            self.assertEqual(im.info.get(\"loop\"), 1)\n\n    def test_apng_mode(self):\n        with Image.open(\"Tests/images/apng/mode_16bit.png\") as im:\n            self.assertEqual(im.mode, \"RGBA\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 128, 191))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 128, 191))\n\n        with Image.open(\"Tests/images/apng/mode_greyscale.png\") as im:\n            self.assertEqual(im.mode, \"L\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), 128)\n            self.assertEqual(im.getpixel((64, 32)), 255)\n\n        with Image.open(\"Tests/images/apng/mode_greyscale_alpha.png\") as im:\n            self.assertEqual(im.mode, \"LA\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (128, 191))\n            self.assertEqual(im.getpixel((64, 32)), (128, 191))\n\n        with Image.open(\"Tests/images/apng/mode_palette.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGB\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0))\n\n        with Image.open(\"Tests/images/apng/mode_palette_alpha.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGBA\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/mode_palette_1bit_alpha.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGBA\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 255, 128))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 255, 128))\n\n    def test_apng_chunk_errors(self):\n        with Image.open(\"Tests/images/apng/chunk_no_actl.png\") as im:\n            self.assertFalse(im.is_animated)\n\n        def open():\n            with Image.open(\"Tests/images/apng/chunk_multi_actl.png\") as im:\n                im.load()\n            self.assertFalse(im.is_animated)\n\n        pytest.warns(UserWarning, open)\n\n        with Image.open(\"Tests/images/apng/chunk_actl_after_idat.png\") as im:\n            self.assertFalse(im.is_animated)\n\n        with Image.open(\"Tests/images/apng/chunk_no_fctl.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n        with Image.open(\"Tests/images/apng/chunk_repeat_fctl.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n        with Image.open(\"Tests/images/apng/chunk_no_fdat.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n    def test_apng_syntax_errors(self):\n        def open_frames_zero():\n            with Image.open(\"Tests/images/apng/syntax_num_frames_zero.png\") as im:\n                self.assertFalse(im.is_animated)\n                with self.assertRaises(OSError):\n                    im.load()\n\n        pytest.warns(UserWarning, open_frames_zero)\n\n        def open_frames_zero_default():\n            with Image.open(\n                \"Tests/images/apng/syntax_num_frames_zero_default.png\"\n            ) as im:\n                self.assertFalse(im.is_animated)\n                im.load()\n\n        pytest.warns(UserWarning, open_frames_zero_default)\n\n        # we can handle this case gracefully\n        exception = None\n        with Image.open(\"Tests/images/apng/syntax_num_frames_low.png\") as im:\n            try:\n                im.seek(im.n_frames - 1)\n            except Exception as e:\n                exception = e\n            self.assertIsNone(exception)\n\n        with self.assertRaises(SyntaxError):\n            with Image.open(\"Tests/images/apng/syntax_num_frames_high.png\") as im:\n                im.seek(im.n_frames - 1)\n                im.load()\n\n        def open():\n            with Image.open(\"Tests/images/apng/syntax_num_frames_invalid.png\") as im:\n                self.assertFalse(im.is_animated)\n                im.load()\n\n        pytest.warns(UserWarning, open)\n\n    def test_apng_sequence_errors(self):\n        test_files = [\n            \"sequence_start.png\",\n            \"sequence_gap.png\",\n            \"sequence_repeat.png\",\n            \"sequence_repeat_chunk.png\",\n            \"sequence_reorder.png\",\n            \"sequence_reorder_chunk.png\",\n            \"sequence_fdat_fctl.png\",\n        ]\n        for f in test_files:\n            with self.assertRaises(SyntaxError):\n                with Image.open(\"Tests/images/apng/{0}\".format(f)) as im:\n                    im.seek(im.n_frames - 1)\n                    im.load()\n\n    def test_apng_save(self):\n        with Image.open(\"Tests/images/apng/single_frame.png\") as im:\n            test_file = self.tempfile(\"temp.png\")\n            im.save(test_file, save_all=True)\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertFalse(im.is_animated)\n            self.assertEqual(im.n_frames, 1)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertIsNone(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/single_frame_default.png\") as im:\n            frames = []\n            for frame_im in ImageSequence.Iterator(im):\n                frames.append(frame_im.copy())\n            frames[0].save(\n                test_file, save_all=True, default_image=True, append_images=frames[1:]\n            )\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.n_frames, 2)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertTrue(im.info.get(\"default_image\"))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_save_split_fdat(self):\n        # test to make sure we do not generate sequence errors when writing\n        # frames with image data spanning multiple fdAT chunks (in this case\n        # both the default image and first animation frame will span multiple\n        # data chunks)\n        test_file = self.tempfile(\"temp.png\")\n        with Image.open(\"Tests/images/old-style-jpeg-compression.png\") as im:\n            frames = [im.copy(), Image.new(\"RGBA\", im.size, (255, 0, 0, 255))]\n            im.save(\n                test_file, save_all=True, default_image=True, append_images=frames,\n            )\n        with Image.open(test_file) as im:\n            exception = None\n            try:\n                im.seek(im.n_frames - 1)\n                im.load()\n            except Exception as e:\n                exception = e\n            self.assertIsNone(exception)\n\n    def test_apng_save_duration_loop(self):\n        test_file = self.tempfile(\"temp.png\")\n        with Image.open(\"Tests/images/apng/delay.png\") as im:\n            frames = []\n            durations = []\n            loop = im.info.get(\"loop\")\n            default_image = im.info.get(\"default_image\")\n            for i, frame_im in enumerate(ImageSequence.Iterator(im)):\n                frames.append(frame_im.copy())\n                if i != 0 or not default_image:\n                    durations.append(frame_im.info.get(\"duration\", 0))\n            frames[0].save(\n                test_file,\n                save_all=True,\n                default_image=default_image,\n                append_images=frames[1:],\n                duration=durations,\n                loop=loop,\n            )\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertEqual(im.info.get(\"loop\"), loop)\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        # test removal of duplicated frames\n        frame = Image.new(\"RGBA\", (128, 64), (255, 0, 0, 255))\n        frame.save(test_file, save_all=True, append_images=[frame], duration=[500, 250])\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertEqual(im.n_frames, 1)\n            self.assertEqual(im.info.get(\"duration\"), 750)\n\n    def test_apng_save_disposal(self):\n        test_file = self.tempfile(\"temp.png\")\n        size = (128, 64)\n        red = Image.new(\"RGBA\", size, (255, 0, 0, 255))\n        green = Image.new(\"RGBA\", size, (0, 255, 0, 255))\n        transparent = Image.new(\"RGBA\", size, (0, 0, 0, 0))\n\n        # test APNG_DISPOSE_OP_NONE\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, transparent],\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_DISPOSE_OP_BACKGROUND\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_BACKGROUND,\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, transparent],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_BACKGROUND,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_DISPOSE_OP_PREVIOUS\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_PREVIOUS,\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, red, transparent],\n            default_image=True,\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(3)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_PREVIOUS,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_save_blend(self):\n        test_file = self.tempfile(\"temp.png\")\n        size = (128, 64)\n        red = Image.new(\"RGBA\", size, (255, 0, 0, 255))\n        green = Image.new(\"RGBA\", size, (0, 255, 0, 255))\n        transparent = Image.new(\"RGBA\", size, (0, 0, 0, 0))\n\n        # test APNG_BLEND_OP_SOURCE on solid color\n        blend = [\n            PngImagePlugin.APNG_BLEND_OP_OVER,\n            PngImagePlugin.APNG_BLEND_OP_SOURCE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, green],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=blend,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_BLEND_OP_SOURCE on transparent color\n        blend = [\n            PngImagePlugin.APNG_BLEND_OP_OVER,\n            PngImagePlugin.APNG_BLEND_OP_SOURCE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, transparent],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=blend,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        # test APNG_BLEND_OP_OVER\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, transparent],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 13,
                            "end_lineno": 43,
                            "parent": {
                                "file_name": "Tests/test_file_apng.py",
                                "type": "class",
                                "name": "TestFilePng",
                                "content": "class TestFilePng(PillowTestCase):\n\n    # APNG browser support tests and fixtures via:\n    # https://philip.html5.org/tests/apng/tests.html\n    # (referenced from https://wiki.mozilla.org/APNG_Specification)\n    def test_apng_basic(self):\n        with Image.open(\"Tests/images/apng/single_frame.png\") as im:\n            self.assertFalse(im.is_animated)\n            self.assertEqual(im.n_frames, 1)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertIsNone(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/single_frame_default.png\") as im:\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.n_frames, 2)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertTrue(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (255, 0, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (255, 0, 0, 255))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n            # test out of bounds seek\n            with self.assertRaises(EOFError):\n                im.seek(2)\n\n            # test rewind support\n            im.seek(0)\n            self.assertEqual(im.getpixel((0, 0)), (255, 0, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (255, 0, 0, 255))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_fdat(self):\n        with Image.open(\"Tests/images/apng/split_fdat.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/split_fdat_zero_chunk.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_dispose(self):\n        with Image.open(\"Tests/images/apng/dispose_op_none.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background_final.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_final.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_first.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n    def test_apng_dispose_region(self):\n        with Image.open(\"Tests/images/apng/dispose_op_none_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\n            \"Tests/images/apng/dispose_op_background_before_region.png\"\n        ) as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 255, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_blend(self):\n        with Image.open(\"Tests/images/apng/blend_op_source_solid.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/blend_op_source_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/blend_op_source_near_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 2))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 2))\n\n        with Image.open(\"Tests/images/apng/blend_op_over.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/blend_op_over_near_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 97))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_chunk_order(self):\n        with Image.open(\"Tests/images/apng/fctl_actl.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_delay(self):\n        with Image.open(\"Tests/images/apng/delay.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_round.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_short_max.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_zero_denom.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_zero_numer.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 0.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 0.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n    def test_apng_num_plays(self):\n        with Image.open(\"Tests/images/apng/num_plays.png\") as im:\n            self.assertEqual(im.info.get(\"loop\"), 0)\n\n        with Image.open(\"Tests/images/apng/num_plays_1.png\") as im:\n            self.assertEqual(im.info.get(\"loop\"), 1)\n\n    def test_apng_mode(self):\n        with Image.open(\"Tests/images/apng/mode_16bit.png\") as im:\n            self.assertEqual(im.mode, \"RGBA\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 128, 191))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 128, 191))\n\n        with Image.open(\"Tests/images/apng/mode_greyscale.png\") as im:\n            self.assertEqual(im.mode, \"L\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), 128)\n            self.assertEqual(im.getpixel((64, 32)), 255)\n\n        with Image.open(\"Tests/images/apng/mode_greyscale_alpha.png\") as im:\n            self.assertEqual(im.mode, \"LA\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (128, 191))\n            self.assertEqual(im.getpixel((64, 32)), (128, 191))\n\n        with Image.open(\"Tests/images/apng/mode_palette.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGB\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0))\n\n        with Image.open(\"Tests/images/apng/mode_palette_alpha.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGBA\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/mode_palette_1bit_alpha.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGBA\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 255, 128))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 255, 128))\n\n    def test_apng_chunk_errors(self):\n        with Image.open(\"Tests/images/apng/chunk_no_actl.png\") as im:\n            self.assertFalse(im.is_animated)\n\n        def open():\n            with Image.open(\"Tests/images/apng/chunk_multi_actl.png\") as im:\n                im.load()\n            self.assertFalse(im.is_animated)\n\n        pytest.warns(UserWarning, open)\n\n        with Image.open(\"Tests/images/apng/chunk_actl_after_idat.png\") as im:\n            self.assertFalse(im.is_animated)\n\n        with Image.open(\"Tests/images/apng/chunk_no_fctl.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n        with Image.open(\"Tests/images/apng/chunk_repeat_fctl.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n        with Image.open(\"Tests/images/apng/chunk_no_fdat.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n    def test_apng_syntax_errors(self):\n        def open_frames_zero():\n            with Image.open(\"Tests/images/apng/syntax_num_frames_zero.png\") as im:\n                self.assertFalse(im.is_animated)\n                with self.assertRaises(OSError):\n                    im.load()\n\n        pytest.warns(UserWarning, open_frames_zero)\n\n        def open_frames_zero_default():\n            with Image.open(\n                \"Tests/images/apng/syntax_num_frames_zero_default.png\"\n            ) as im:\n                self.assertFalse(im.is_animated)\n                im.load()\n\n        pytest.warns(UserWarning, open_frames_zero_default)\n\n        # we can handle this case gracefully\n        exception = None\n        with Image.open(\"Tests/images/apng/syntax_num_frames_low.png\") as im:\n            try:\n                im.seek(im.n_frames - 1)\n            except Exception as e:\n                exception = e\n            self.assertIsNone(exception)\n\n        with self.assertRaises(SyntaxError):\n            with Image.open(\"Tests/images/apng/syntax_num_frames_high.png\") as im:\n                im.seek(im.n_frames - 1)\n                im.load()\n\n        def open():\n            with Image.open(\"Tests/images/apng/syntax_num_frames_invalid.png\") as im:\n                self.assertFalse(im.is_animated)\n                im.load()\n\n        pytest.warns(UserWarning, open)\n\n    def test_apng_sequence_errors(self):\n        test_files = [\n            \"sequence_start.png\",\n            \"sequence_gap.png\",\n            \"sequence_repeat.png\",\n            \"sequence_repeat_chunk.png\",\n            \"sequence_reorder.png\",\n            \"sequence_reorder_chunk.png\",\n            \"sequence_fdat_fctl.png\",\n        ]\n        for f in test_files:\n            with self.assertRaises(SyntaxError):\n                with Image.open(\"Tests/images/apng/{0}\".format(f)) as im:\n                    im.seek(im.n_frames - 1)\n                    im.load()\n\n    def test_apng_save(self):\n        with Image.open(\"Tests/images/apng/single_frame.png\") as im:\n            test_file = self.tempfile(\"temp.png\")\n            im.save(test_file, save_all=True)\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertFalse(im.is_animated)\n            self.assertEqual(im.n_frames, 1)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertIsNone(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/single_frame_default.png\") as im:\n            frames = []\n            for frame_im in ImageSequence.Iterator(im):\n                frames.append(frame_im.copy())\n            frames[0].save(\n                test_file, save_all=True, default_image=True, append_images=frames[1:]\n            )\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.n_frames, 2)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertTrue(im.info.get(\"default_image\"))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_save_split_fdat(self):\n        # test to make sure we do not generate sequence errors when writing\n        # frames with image data spanning multiple fdAT chunks (in this case\n        # both the default image and first animation frame will span multiple\n        # data chunks)\n        test_file = self.tempfile(\"temp.png\")\n        with Image.open(\"Tests/images/old-style-jpeg-compression.png\") as im:\n            frames = [im.copy(), Image.new(\"RGBA\", im.size, (255, 0, 0, 255))]\n            im.save(\n                test_file, save_all=True, default_image=True, append_images=frames,\n            )\n        with Image.open(test_file) as im:\n            exception = None\n            try:\n                im.seek(im.n_frames - 1)\n                im.load()\n            except Exception as e:\n                exception = e\n            self.assertIsNone(exception)\n\n    def test_apng_save_duration_loop(self):\n        test_file = self.tempfile(\"temp.png\")\n        with Image.open(\"Tests/images/apng/delay.png\") as im:\n            frames = []\n            durations = []\n            loop = im.info.get(\"loop\")\n            default_image = im.info.get(\"default_image\")\n            for i, frame_im in enumerate(ImageSequence.Iterator(im)):\n                frames.append(frame_im.copy())\n                if i != 0 or not default_image:\n                    durations.append(frame_im.info.get(\"duration\", 0))\n            frames[0].save(\n                test_file,\n                save_all=True,\n                default_image=default_image,\n                append_images=frames[1:],\n                duration=durations,\n                loop=loop,\n            )\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertEqual(im.info.get(\"loop\"), loop)\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        # test removal of duplicated frames\n        frame = Image.new(\"RGBA\", (128, 64), (255, 0, 0, 255))\n        frame.save(test_file, save_all=True, append_images=[frame], duration=[500, 250])\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertEqual(im.n_frames, 1)\n            self.assertEqual(im.info.get(\"duration\"), 750)\n\n    def test_apng_save_disposal(self):\n        test_file = self.tempfile(\"temp.png\")\n        size = (128, 64)\n        red = Image.new(\"RGBA\", size, (255, 0, 0, 255))\n        green = Image.new(\"RGBA\", size, (0, 255, 0, 255))\n        transparent = Image.new(\"RGBA\", size, (0, 0, 0, 0))\n\n        # test APNG_DISPOSE_OP_NONE\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, transparent],\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_DISPOSE_OP_BACKGROUND\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_BACKGROUND,\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, transparent],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_BACKGROUND,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_DISPOSE_OP_PREVIOUS\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_PREVIOUS,\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, red, transparent],\n            default_image=True,\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(3)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_PREVIOUS,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_save_blend(self):\n        test_file = self.tempfile(\"temp.png\")\n        size = (128, 64)\n        red = Image.new(\"RGBA\", size, (255, 0, 0, 255))\n        green = Image.new(\"RGBA\", size, (0, 255, 0, 255))\n        transparent = Image.new(\"RGBA\", size, (0, 0, 0, 0))\n\n        # test APNG_BLEND_OP_SOURCE on solid color\n        blend = [\n            PngImagePlugin.APNG_BLEND_OP_OVER,\n            PngImagePlugin.APNG_BLEND_OP_SOURCE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, green],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=blend,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_BLEND_OP_SOURCE on transparent color\n        blend = [\n            PngImagePlugin.APNG_BLEND_OP_OVER,\n            PngImagePlugin.APNG_BLEND_OP_SOURCE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, transparent],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=blend,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        # test APNG_BLEND_OP_OVER\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, transparent],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 8,
                                "end_lineno": 548,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "Tests/test_file_apng.py",
                            "type": "class",
                            "name": "TestFilePng",
                            "content": "class TestFilePng(PillowTestCase):\n\n    # APNG browser support tests and fixtures via:\n    # https://philip.html5.org/tests/apng/tests.html\n    # (referenced from https://wiki.mozilla.org/APNG_Specification)\n    def test_apng_basic(self):\n        with Image.open(\"Tests/images/apng/single_frame.png\") as im:\n            self.assertFalse(im.is_animated)\n            self.assertEqual(im.n_frames, 1)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertIsNone(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/single_frame_default.png\") as im:\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.n_frames, 2)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertTrue(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (255, 0, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (255, 0, 0, 255))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n            # test out of bounds seek\n            with self.assertRaises(EOFError):\n                im.seek(2)\n\n            # test rewind support\n            im.seek(0)\n            self.assertEqual(im.getpixel((0, 0)), (255, 0, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (255, 0, 0, 255))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_fdat(self):\n        with Image.open(\"Tests/images/apng/split_fdat.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/split_fdat_zero_chunk.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_dispose(self):\n        with Image.open(\"Tests/images/apng/dispose_op_none.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background_final.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_final.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_first.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n    def test_apng_dispose_region(self):\n        with Image.open(\"Tests/images/apng/dispose_op_none_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\n            \"Tests/images/apng/dispose_op_background_before_region.png\"\n        ) as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 255, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_blend(self):\n        with Image.open(\"Tests/images/apng/blend_op_source_solid.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/blend_op_source_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/blend_op_source_near_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 2))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 2))\n\n        with Image.open(\"Tests/images/apng/blend_op_over.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/blend_op_over_near_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 97))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_chunk_order(self):\n        with Image.open(\"Tests/images/apng/fctl_actl.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_delay(self):\n        with Image.open(\"Tests/images/apng/delay.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_round.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_short_max.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_zero_denom.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_zero_numer.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 0.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 0.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n    def test_apng_num_plays(self):\n        with Image.open(\"Tests/images/apng/num_plays.png\") as im:\n            self.assertEqual(im.info.get(\"loop\"), 0)\n\n        with Image.open(\"Tests/images/apng/num_plays_1.png\") as im:\n            self.assertEqual(im.info.get(\"loop\"), 1)\n\n    def test_apng_mode(self):\n        with Image.open(\"Tests/images/apng/mode_16bit.png\") as im:\n            self.assertEqual(im.mode, \"RGBA\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 128, 191))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 128, 191))\n\n        with Image.open(\"Tests/images/apng/mode_greyscale.png\") as im:\n            self.assertEqual(im.mode, \"L\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), 128)\n            self.assertEqual(im.getpixel((64, 32)), 255)\n\n        with Image.open(\"Tests/images/apng/mode_greyscale_alpha.png\") as im:\n            self.assertEqual(im.mode, \"LA\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (128, 191))\n            self.assertEqual(im.getpixel((64, 32)), (128, 191))\n\n        with Image.open(\"Tests/images/apng/mode_palette.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGB\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0))\n\n        with Image.open(\"Tests/images/apng/mode_palette_alpha.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGBA\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/mode_palette_1bit_alpha.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGBA\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 255, 128))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 255, 128))\n\n    def test_apng_chunk_errors(self):\n        with Image.open(\"Tests/images/apng/chunk_no_actl.png\") as im:\n            self.assertFalse(im.is_animated)\n\n        def open():\n            with Image.open(\"Tests/images/apng/chunk_multi_actl.png\") as im:\n                im.load()\n            self.assertFalse(im.is_animated)\n\n        pytest.warns(UserWarning, open)\n\n        with Image.open(\"Tests/images/apng/chunk_actl_after_idat.png\") as im:\n            self.assertFalse(im.is_animated)\n\n        with Image.open(\"Tests/images/apng/chunk_no_fctl.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n        with Image.open(\"Tests/images/apng/chunk_repeat_fctl.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n        with Image.open(\"Tests/images/apng/chunk_no_fdat.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n    def test_apng_syntax_errors(self):\n        def open_frames_zero():\n            with Image.open(\"Tests/images/apng/syntax_num_frames_zero.png\") as im:\n                self.assertFalse(im.is_animated)\n                with self.assertRaises(OSError):\n                    im.load()\n\n        pytest.warns(UserWarning, open_frames_zero)\n\n        def open_frames_zero_default():\n            with Image.open(\n                \"Tests/images/apng/syntax_num_frames_zero_default.png\"\n            ) as im:\n                self.assertFalse(im.is_animated)\n                im.load()\n\n        pytest.warns(UserWarning, open_frames_zero_default)\n\n        # we can handle this case gracefully\n        exception = None\n        with Image.open(\"Tests/images/apng/syntax_num_frames_low.png\") as im:\n            try:\n                im.seek(im.n_frames - 1)\n            except Exception as e:\n                exception = e\n            self.assertIsNone(exception)\n\n        with self.assertRaises(SyntaxError):\n            with Image.open(\"Tests/images/apng/syntax_num_frames_high.png\") as im:\n                im.seek(im.n_frames - 1)\n                im.load()\n\n        def open():\n            with Image.open(\"Tests/images/apng/syntax_num_frames_invalid.png\") as im:\n                self.assertFalse(im.is_animated)\n                im.load()\n\n        pytest.warns(UserWarning, open)\n\n    def test_apng_sequence_errors(self):\n        test_files = [\n            \"sequence_start.png\",\n            \"sequence_gap.png\",\n            \"sequence_repeat.png\",\n            \"sequence_repeat_chunk.png\",\n            \"sequence_reorder.png\",\n            \"sequence_reorder_chunk.png\",\n            \"sequence_fdat_fctl.png\",\n        ]\n        for f in test_files:\n            with self.assertRaises(SyntaxError):\n                with Image.open(\"Tests/images/apng/{0}\".format(f)) as im:\n                    im.seek(im.n_frames - 1)\n                    im.load()\n\n    def test_apng_save(self):\n        with Image.open(\"Tests/images/apng/single_frame.png\") as im:\n            test_file = self.tempfile(\"temp.png\")\n            im.save(test_file, save_all=True)\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertFalse(im.is_animated)\n            self.assertEqual(im.n_frames, 1)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertIsNone(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/single_frame_default.png\") as im:\n            frames = []\n            for frame_im in ImageSequence.Iterator(im):\n                frames.append(frame_im.copy())\n            frames[0].save(\n                test_file, save_all=True, default_image=True, append_images=frames[1:]\n            )\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.n_frames, 2)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertTrue(im.info.get(\"default_image\"))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_save_split_fdat(self):\n        # test to make sure we do not generate sequence errors when writing\n        # frames with image data spanning multiple fdAT chunks (in this case\n        # both the default image and first animation frame will span multiple\n        # data chunks)\n        test_file = self.tempfile(\"temp.png\")\n        with Image.open(\"Tests/images/old-style-jpeg-compression.png\") as im:\n            frames = [im.copy(), Image.new(\"RGBA\", im.size, (255, 0, 0, 255))]\n            im.save(\n                test_file, save_all=True, default_image=True, append_images=frames,\n            )\n        with Image.open(test_file) as im:\n            exception = None\n            try:\n                im.seek(im.n_frames - 1)\n                im.load()\n            except Exception as e:\n                exception = e\n            self.assertIsNone(exception)\n\n    def test_apng_save_duration_loop(self):\n        test_file = self.tempfile(\"temp.png\")\n        with Image.open(\"Tests/images/apng/delay.png\") as im:\n            frames = []\n            durations = []\n            loop = im.info.get(\"loop\")\n            default_image = im.info.get(\"default_image\")\n            for i, frame_im in enumerate(ImageSequence.Iterator(im)):\n                frames.append(frame_im.copy())\n                if i != 0 or not default_image:\n                    durations.append(frame_im.info.get(\"duration\", 0))\n            frames[0].save(\n                test_file,\n                save_all=True,\n                default_image=default_image,\n                append_images=frames[1:],\n                duration=durations,\n                loop=loop,\n            )\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertEqual(im.info.get(\"loop\"), loop)\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        # test removal of duplicated frames\n        frame = Image.new(\"RGBA\", (128, 64), (255, 0, 0, 255))\n        frame.save(test_file, save_all=True, append_images=[frame], duration=[500, 250])\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertEqual(im.n_frames, 1)\n            self.assertEqual(im.info.get(\"duration\"), 750)\n\n    def test_apng_save_disposal(self):\n        test_file = self.tempfile(\"temp.png\")\n        size = (128, 64)\n        red = Image.new(\"RGBA\", size, (255, 0, 0, 255))\n        green = Image.new(\"RGBA\", size, (0, 255, 0, 255))\n        transparent = Image.new(\"RGBA\", size, (0, 0, 0, 0))\n\n        # test APNG_DISPOSE_OP_NONE\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, transparent],\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_DISPOSE_OP_BACKGROUND\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_BACKGROUND,\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, transparent],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_BACKGROUND,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_DISPOSE_OP_PREVIOUS\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_PREVIOUS,\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, red, transparent],\n            default_image=True,\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(3)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_PREVIOUS,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_save_blend(self):\n        test_file = self.tempfile(\"temp.png\")\n        size = (128, 64)\n        red = Image.new(\"RGBA\", size, (255, 0, 0, 255))\n        green = Image.new(\"RGBA\", size, (0, 255, 0, 255))\n        transparent = Image.new(\"RGBA\", size, (0, 0, 0, 0))\n\n        # test APNG_BLEND_OP_SOURCE on solid color\n        blend = [\n            PngImagePlugin.APNG_BLEND_OP_OVER,\n            PngImagePlugin.APNG_BLEND_OP_SOURCE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, green],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=blend,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_BLEND_OP_SOURCE on transparent color\n        blend = [\n            PngImagePlugin.APNG_BLEND_OP_OVER,\n            PngImagePlugin.APNG_BLEND_OP_SOURCE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, transparent],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=blend,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        # test APNG_BLEND_OP_OVER\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, transparent],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 8,
                            "end_lineno": 548,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 311,
                            "length": 7
                        },
                        "new_range": {
                            "start": 313,
                            "length": 8
                        },
                        "section": "class TestFilePng(PillowTestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        with Image.open(test_file) as im:",
                                "type": "context"
                            },
                            {
                                "content": "            im.load()",
                                "type": "context"
                            },
                            {
                                "content": "            self.assertTrue(im.is_animated)",
                                "type": "deleted"
                            },
                            {
                                "content": "            self.assertFalse(im.is_animated)",
                                "type": "added"
                            },
                            {
                                "content": "            self.assertEqual(im.n_frames, 1)",
                                "type": "added"
                            },
                            {
                                "content": "            self.assertEqual(im.get_format_mimetype(), \"image/apng\")",
                                "type": "context"
                            },
                            {
                                "content": "            self.assertIsNone(im.info.get(\"default_image\"))",
                                "type": "context"
                            },
                            {
                                "content": "            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Tests/test_file_apng.py",
                            "type": "method",
                            "name": "TestFilePng.test_apng_save",
                            "content": "class TestFilePng(PillowTestCase):\n\n    # APNG browser support tests and fixtures via:\n    # https://philip.html5.org/tests/apng/tests.html\n    # (referenced from https://wiki.mozilla.org/APNG_Specification)\n    def test_apng_basic(self):\n        with Image.open(\"Tests/images/apng/single_frame.png\") as im:\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertIsNone(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/single_frame_default.png\") as im:\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertTrue(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (255, 0, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (255, 0, 0, 255))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n            # test out of bounds seek\n            with self.assertRaises(EOFError):\n                im.seek(2)\n\n            # test rewind support\n            im.seek(0)\n            self.assertEqual(im.getpixel((0, 0)), (255, 0, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (255, 0, 0, 255))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_fdat(self):\n        with Image.open(\"Tests/images/apng/split_fdat.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/split_fdat_zero_chunk.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_dispose(self):\n        with Image.open(\"Tests/images/apng/dispose_op_none.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background_final.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_final.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_first.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n    def test_apng_dispose_region(self):\n        with Image.open(\"Tests/images/apng/dispose_op_none_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\n            \"Tests/images/apng/dispose_op_background_before_region.png\"\n        ) as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 255, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_blend(self):\n        with Image.open(\"Tests/images/apng/blend_op_source_solid.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/blend_op_source_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/blend_op_source_near_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 2))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 2))\n\n        with Image.open(\"Tests/images/apng/blend_op_over.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/blend_op_over_near_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 97))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_chunk_order(self):\n        with Image.open(\"Tests/images/apng/fctl_actl.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_delay(self):\n        with Image.open(\"Tests/images/apng/delay.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_round.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_short_max.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_zero_denom.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_zero_numer.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 0.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 0.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n    def test_apng_num_plays(self):\n        with Image.open(\"Tests/images/apng/num_plays.png\") as im:\n            self.assertEqual(im.info.get(\"loop\"), 0)\n\n        with Image.open(\"Tests/images/apng/num_plays_1.png\") as im:\n            self.assertEqual(im.info.get(\"loop\"), 1)\n\n    def test_apng_mode(self):\n        with Image.open(\"Tests/images/apng/mode_16bit.png\") as im:\n            self.assertEqual(im.mode, \"RGBA\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 128, 191))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 128, 191))\n\n        with Image.open(\"Tests/images/apng/mode_greyscale.png\") as im:\n            self.assertEqual(im.mode, \"L\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), 128)\n            self.assertEqual(im.getpixel((64, 32)), 255)\n\n        with Image.open(\"Tests/images/apng/mode_greyscale_alpha.png\") as im:\n            self.assertEqual(im.mode, \"LA\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (128, 191))\n            self.assertEqual(im.getpixel((64, 32)), (128, 191))\n\n        with Image.open(\"Tests/images/apng/mode_palette.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGB\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0))\n\n        with Image.open(\"Tests/images/apng/mode_palette_alpha.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGBA\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/mode_palette_1bit_alpha.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGBA\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 255, 128))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 255, 128))\n\n    def test_apng_chunk_errors(self):\n        with Image.open(\"Tests/images/apng/chunk_no_actl.png\") as im:\n            self.assertFalse(im.is_animated)\n\n        def open():\n            with Image.open(\"Tests/images/apng/chunk_multi_actl.png\") as im:\n                im.load()\n            self.assertFalse(im.is_animated)\n\n        pytest.warns(UserWarning, open)\n\n        with Image.open(\"Tests/images/apng/chunk_actl_after_idat.png\") as im:\n            self.assertFalse(im.is_animated)\n\n        with Image.open(\"Tests/images/apng/chunk_no_fctl.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n        with Image.open(\"Tests/images/apng/chunk_repeat_fctl.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n        with Image.open(\"Tests/images/apng/chunk_no_fdat.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n    def test_apng_syntax_errors(self):\n        def open_frames_zero():\n            with Image.open(\"Tests/images/apng/syntax_num_frames_zero.png\") as im:\n                self.assertFalse(im.is_animated)\n                with self.assertRaises(OSError):\n                    im.load()\n\n        pytest.warns(UserWarning, open_frames_zero)\n\n        def open_frames_zero_default():\n            with Image.open(\n                \"Tests/images/apng/syntax_num_frames_zero_default.png\"\n            ) as im:\n                self.assertFalse(im.is_animated)\n                im.load()\n\n        pytest.warns(UserWarning, open_frames_zero_default)\n\n        # we can handle this case gracefully\n        exception = None\n        with Image.open(\"Tests/images/apng/syntax_num_frames_low.png\") as im:\n            try:\n                im.seek(im.n_frames - 1)\n            except Exception as e:\n                exception = e\n            self.assertIsNone(exception)\n\n        with self.assertRaises(SyntaxError):\n            with Image.open(\"Tests/images/apng/syntax_num_frames_high.png\") as im:\n                im.seek(im.n_frames - 1)\n                im.load()\n\n        def open():\n            with Image.open(\"Tests/images/apng/syntax_num_frames_invalid.png\") as im:\n                self.assertFalse(im.is_animated)\n                im.load()\n\n        pytest.warns(UserWarning, open)\n\n    def test_apng_sequence_errors(self):\n        test_files = [\n            \"sequence_start.png\",\n            \"sequence_gap.png\",\n            \"sequence_repeat.png\",\n            \"sequence_repeat_chunk.png\",\n            \"sequence_reorder.png\",\n            \"sequence_reorder_chunk.png\",\n            \"sequence_fdat_fctl.png\",\n        ]\n        for f in test_files:\n            with self.assertRaises(SyntaxError):\n                with Image.open(\"Tests/images/apng/{0}\".format(f)) as im:\n                    im.seek(im.n_frames - 1)\n                    im.load()\n\n    def test_apng_save(self):\n        with Image.open(\"Tests/images/apng/single_frame.png\") as im:\n            test_file = self.tempfile(\"temp.png\")\n            im.save(test_file, save_all=True)\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertIsNone(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/single_frame_default.png\") as im:\n            frames = []\n            for frame_im in ImageSequence.Iterator(im):\n                frames.append(frame_im.copy())\n            frames[0].save(\n                test_file, save_all=True, default_image=True, append_images=frames[1:]\n            )\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertTrue(im.info.get(\"default_image\"))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_save_split_fdat(self):\n        # test to make sure we do not generate sequence errors when writing\n        # frames with image data spanning multiple fdAT chunks (in this case\n        # both the default image and first animation frame will span multiple\n        # data chunks)\n        test_file = self.tempfile(\"temp.png\")\n        with Image.open(\"Tests/images/old-style-jpeg-compression.png\") as im:\n            frames = [im.copy(), Image.new(\"RGBA\", im.size, (255, 0, 0, 255))]\n            im.save(\n                test_file, save_all=True, default_image=True, append_images=frames,\n            )\n        with Image.open(test_file) as im:\n            exception = None\n            try:\n                im.seek(im.n_frames - 1)\n                im.load()\n            except Exception as e:\n                exception = e\n            self.assertIsNone(exception)\n\n    def test_apng_save_duration_loop(self):\n        test_file = self.tempfile(\"temp.png\")\n        with Image.open(\"Tests/images/apng/delay.png\") as im:\n            frames = []\n            durations = []\n            loop = im.info.get(\"loop\")\n            default_image = im.info.get(\"default_image\")\n            for i, frame_im in enumerate(ImageSequence.Iterator(im)):\n                frames.append(frame_im.copy())\n                if i != 0 or not default_image:\n                    durations.append(frame_im.info.get(\"duration\", 0))\n            frames[0].save(\n                test_file,\n                save_all=True,\n                default_image=default_image,\n                append_images=frames[1:],\n                duration=durations,\n                loop=loop,\n            )\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertEqual(im.info.get(\"loop\"), loop)\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        # test removal of duplicated frames\n        frame = Image.new(\"RGBA\", (128, 64), (255, 0, 0, 255))\n        frame.save(test_file, save_all=True, append_images=[frame], duration=[500, 250])\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertEqual(im.n_frames, 1)\n            self.assertEqual(im.info.get(\"duration\"), 750)\n\n    def test_apng_save_disposal(self):\n        test_file = self.tempfile(\"temp.png\")\n        size = (128, 64)\n        red = Image.new(\"RGBA\", size, (255, 0, 0, 255))\n        green = Image.new(\"RGBA\", size, (0, 255, 0, 255))\n        transparent = Image.new(\"RGBA\", size, (0, 0, 0, 0))\n\n        # test APNG_DISPOSE_OP_NONE\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, transparent],\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_DISPOSE_OP_BACKGROUND\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_BACKGROUND,\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, transparent],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_BACKGROUND,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_DISPOSE_OP_PREVIOUS\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_PREVIOUS,\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, red, transparent],\n            default_image=True,\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(3)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_PREVIOUS,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_save_blend(self):\n        test_file = self.tempfile(\"temp.png\")\n        size = (128, 64)\n        red = Image.new(\"RGBA\", size, (255, 0, 0, 255))\n        green = Image.new(\"RGBA\", size, (0, 255, 0, 255))\n        transparent = Image.new(\"RGBA\", size, (0, 0, 0, 0))\n\n        # test APNG_BLEND_OP_SOURCE on solid color\n        blend = [\n            PngImagePlugin.APNG_BLEND_OP_OVER,\n            PngImagePlugin.APNG_BLEND_OP_SOURCE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, green],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=blend,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_BLEND_OP_SOURCE on transparent color\n        blend = [\n            PngImagePlugin.APNG_BLEND_OP_OVER,\n            PngImagePlugin.APNG_BLEND_OP_SOURCE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, transparent],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=blend,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        # test APNG_BLEND_OP_OVER\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, transparent],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 307,
                            "end_lineno": 335,
                            "parent": {
                                "file_name": "Tests/test_file_apng.py",
                                "type": "class",
                                "name": "TestFilePng",
                                "content": "class TestFilePng(PillowTestCase):\n\n    # APNG browser support tests and fixtures via:\n    # https://philip.html5.org/tests/apng/tests.html\n    # (referenced from https://wiki.mozilla.org/APNG_Specification)\n    def test_apng_basic(self):\n        with Image.open(\"Tests/images/apng/single_frame.png\") as im:\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertIsNone(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/single_frame_default.png\") as im:\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertTrue(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (255, 0, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (255, 0, 0, 255))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n            # test out of bounds seek\n            with self.assertRaises(EOFError):\n                im.seek(2)\n\n            # test rewind support\n            im.seek(0)\n            self.assertEqual(im.getpixel((0, 0)), (255, 0, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (255, 0, 0, 255))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_fdat(self):\n        with Image.open(\"Tests/images/apng/split_fdat.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/split_fdat_zero_chunk.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_dispose(self):\n        with Image.open(\"Tests/images/apng/dispose_op_none.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background_final.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_final.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_first.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n    def test_apng_dispose_region(self):\n        with Image.open(\"Tests/images/apng/dispose_op_none_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\n            \"Tests/images/apng/dispose_op_background_before_region.png\"\n        ) as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 255, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_blend(self):\n        with Image.open(\"Tests/images/apng/blend_op_source_solid.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/blend_op_source_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/blend_op_source_near_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 2))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 2))\n\n        with Image.open(\"Tests/images/apng/blend_op_over.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/blend_op_over_near_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 97))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_chunk_order(self):\n        with Image.open(\"Tests/images/apng/fctl_actl.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_delay(self):\n        with Image.open(\"Tests/images/apng/delay.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_round.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_short_max.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_zero_denom.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_zero_numer.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 0.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 0.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n    def test_apng_num_plays(self):\n        with Image.open(\"Tests/images/apng/num_plays.png\") as im:\n            self.assertEqual(im.info.get(\"loop\"), 0)\n\n        with Image.open(\"Tests/images/apng/num_plays_1.png\") as im:\n            self.assertEqual(im.info.get(\"loop\"), 1)\n\n    def test_apng_mode(self):\n        with Image.open(\"Tests/images/apng/mode_16bit.png\") as im:\n            self.assertEqual(im.mode, \"RGBA\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 128, 191))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 128, 191))\n\n        with Image.open(\"Tests/images/apng/mode_greyscale.png\") as im:\n            self.assertEqual(im.mode, \"L\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), 128)\n            self.assertEqual(im.getpixel((64, 32)), 255)\n\n        with Image.open(\"Tests/images/apng/mode_greyscale_alpha.png\") as im:\n            self.assertEqual(im.mode, \"LA\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (128, 191))\n            self.assertEqual(im.getpixel((64, 32)), (128, 191))\n\n        with Image.open(\"Tests/images/apng/mode_palette.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGB\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0))\n\n        with Image.open(\"Tests/images/apng/mode_palette_alpha.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGBA\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/mode_palette_1bit_alpha.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGBA\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 255, 128))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 255, 128))\n\n    def test_apng_chunk_errors(self):\n        with Image.open(\"Tests/images/apng/chunk_no_actl.png\") as im:\n            self.assertFalse(im.is_animated)\n\n        def open():\n            with Image.open(\"Tests/images/apng/chunk_multi_actl.png\") as im:\n                im.load()\n            self.assertFalse(im.is_animated)\n\n        pytest.warns(UserWarning, open)\n\n        with Image.open(\"Tests/images/apng/chunk_actl_after_idat.png\") as im:\n            self.assertFalse(im.is_animated)\n\n        with Image.open(\"Tests/images/apng/chunk_no_fctl.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n        with Image.open(\"Tests/images/apng/chunk_repeat_fctl.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n        with Image.open(\"Tests/images/apng/chunk_no_fdat.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n    def test_apng_syntax_errors(self):\n        def open_frames_zero():\n            with Image.open(\"Tests/images/apng/syntax_num_frames_zero.png\") as im:\n                self.assertFalse(im.is_animated)\n                with self.assertRaises(OSError):\n                    im.load()\n\n        pytest.warns(UserWarning, open_frames_zero)\n\n        def open_frames_zero_default():\n            with Image.open(\n                \"Tests/images/apng/syntax_num_frames_zero_default.png\"\n            ) as im:\n                self.assertFalse(im.is_animated)\n                im.load()\n\n        pytest.warns(UserWarning, open_frames_zero_default)\n\n        # we can handle this case gracefully\n        exception = None\n        with Image.open(\"Tests/images/apng/syntax_num_frames_low.png\") as im:\n            try:\n                im.seek(im.n_frames - 1)\n            except Exception as e:\n                exception = e\n            self.assertIsNone(exception)\n\n        with self.assertRaises(SyntaxError):\n            with Image.open(\"Tests/images/apng/syntax_num_frames_high.png\") as im:\n                im.seek(im.n_frames - 1)\n                im.load()\n\n        def open():\n            with Image.open(\"Tests/images/apng/syntax_num_frames_invalid.png\") as im:\n                self.assertFalse(im.is_animated)\n                im.load()\n\n        pytest.warns(UserWarning, open)\n\n    def test_apng_sequence_errors(self):\n        test_files = [\n            \"sequence_start.png\",\n            \"sequence_gap.png\",\n            \"sequence_repeat.png\",\n            \"sequence_repeat_chunk.png\",\n            \"sequence_reorder.png\",\n            \"sequence_reorder_chunk.png\",\n            \"sequence_fdat_fctl.png\",\n        ]\n        for f in test_files:\n            with self.assertRaises(SyntaxError):\n                with Image.open(\"Tests/images/apng/{0}\".format(f)) as im:\n                    im.seek(im.n_frames - 1)\n                    im.load()\n\n    def test_apng_save(self):\n        with Image.open(\"Tests/images/apng/single_frame.png\") as im:\n            test_file = self.tempfile(\"temp.png\")\n            im.save(test_file, save_all=True)\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertIsNone(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/single_frame_default.png\") as im:\n            frames = []\n            for frame_im in ImageSequence.Iterator(im):\n                frames.append(frame_im.copy())\n            frames[0].save(\n                test_file, save_all=True, default_image=True, append_images=frames[1:]\n            )\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertTrue(im.info.get(\"default_image\"))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_save_split_fdat(self):\n        # test to make sure we do not generate sequence errors when writing\n        # frames with image data spanning multiple fdAT chunks (in this case\n        # both the default image and first animation frame will span multiple\n        # data chunks)\n        test_file = self.tempfile(\"temp.png\")\n        with Image.open(\"Tests/images/old-style-jpeg-compression.png\") as im:\n            frames = [im.copy(), Image.new(\"RGBA\", im.size, (255, 0, 0, 255))]\n            im.save(\n                test_file, save_all=True, default_image=True, append_images=frames,\n            )\n        with Image.open(test_file) as im:\n            exception = None\n            try:\n                im.seek(im.n_frames - 1)\n                im.load()\n            except Exception as e:\n                exception = e\n            self.assertIsNone(exception)\n\n    def test_apng_save_duration_loop(self):\n        test_file = self.tempfile(\"temp.png\")\n        with Image.open(\"Tests/images/apng/delay.png\") as im:\n            frames = []\n            durations = []\n            loop = im.info.get(\"loop\")\n            default_image = im.info.get(\"default_image\")\n            for i, frame_im in enumerate(ImageSequence.Iterator(im)):\n                frames.append(frame_im.copy())\n                if i != 0 or not default_image:\n                    durations.append(frame_im.info.get(\"duration\", 0))\n            frames[0].save(\n                test_file,\n                save_all=True,\n                default_image=default_image,\n                append_images=frames[1:],\n                duration=durations,\n                loop=loop,\n            )\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertEqual(im.info.get(\"loop\"), loop)\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        # test removal of duplicated frames\n        frame = Image.new(\"RGBA\", (128, 64), (255, 0, 0, 255))\n        frame.save(test_file, save_all=True, append_images=[frame], duration=[500, 250])\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertEqual(im.n_frames, 1)\n            self.assertEqual(im.info.get(\"duration\"), 750)\n\n    def test_apng_save_disposal(self):\n        test_file = self.tempfile(\"temp.png\")\n        size = (128, 64)\n        red = Image.new(\"RGBA\", size, (255, 0, 0, 255))\n        green = Image.new(\"RGBA\", size, (0, 255, 0, 255))\n        transparent = Image.new(\"RGBA\", size, (0, 0, 0, 0))\n\n        # test APNG_DISPOSE_OP_NONE\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, transparent],\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_DISPOSE_OP_BACKGROUND\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_BACKGROUND,\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, transparent],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_BACKGROUND,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_DISPOSE_OP_PREVIOUS\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_PREVIOUS,\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, red, transparent],\n            default_image=True,\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(3)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_PREVIOUS,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_save_blend(self):\n        test_file = self.tempfile(\"temp.png\")\n        size = (128, 64)\n        red = Image.new(\"RGBA\", size, (255, 0, 0, 255))\n        green = Image.new(\"RGBA\", size, (0, 255, 0, 255))\n        transparent = Image.new(\"RGBA\", size, (0, 0, 0, 0))\n\n        # test APNG_BLEND_OP_SOURCE on solid color\n        blend = [\n            PngImagePlugin.APNG_BLEND_OP_OVER,\n            PngImagePlugin.APNG_BLEND_OP_SOURCE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, green],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=blend,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_BLEND_OP_SOURCE on transparent color\n        blend = [\n            PngImagePlugin.APNG_BLEND_OP_OVER,\n            PngImagePlugin.APNG_BLEND_OP_SOURCE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, transparent],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=blend,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        # test APNG_BLEND_OP_OVER\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, transparent],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 8,
                                "end_lineno": 544,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "Tests/test_file_apng.py",
                            "type": "class",
                            "name": "TestFilePng",
                            "content": "class TestFilePng(PillowTestCase):\n\n    # APNG browser support tests and fixtures via:\n    # https://philip.html5.org/tests/apng/tests.html\n    # (referenced from https://wiki.mozilla.org/APNG_Specification)\n    def test_apng_basic(self):\n        with Image.open(\"Tests/images/apng/single_frame.png\") as im:\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertIsNone(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/single_frame_default.png\") as im:\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertTrue(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (255, 0, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (255, 0, 0, 255))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n            # test out of bounds seek\n            with self.assertRaises(EOFError):\n                im.seek(2)\n\n            # test rewind support\n            im.seek(0)\n            self.assertEqual(im.getpixel((0, 0)), (255, 0, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (255, 0, 0, 255))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_fdat(self):\n        with Image.open(\"Tests/images/apng/split_fdat.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/split_fdat_zero_chunk.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_dispose(self):\n        with Image.open(\"Tests/images/apng/dispose_op_none.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background_final.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_final.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_first.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n    def test_apng_dispose_region(self):\n        with Image.open(\"Tests/images/apng/dispose_op_none_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\n            \"Tests/images/apng/dispose_op_background_before_region.png\"\n        ) as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 255, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_blend(self):\n        with Image.open(\"Tests/images/apng/blend_op_source_solid.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/blend_op_source_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/blend_op_source_near_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 2))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 2))\n\n        with Image.open(\"Tests/images/apng/blend_op_over.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/blend_op_over_near_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 97))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_chunk_order(self):\n        with Image.open(\"Tests/images/apng/fctl_actl.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_delay(self):\n        with Image.open(\"Tests/images/apng/delay.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_round.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_short_max.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_zero_denom.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_zero_numer.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 0.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 0.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n    def test_apng_num_plays(self):\n        with Image.open(\"Tests/images/apng/num_plays.png\") as im:\n            self.assertEqual(im.info.get(\"loop\"), 0)\n\n        with Image.open(\"Tests/images/apng/num_plays_1.png\") as im:\n            self.assertEqual(im.info.get(\"loop\"), 1)\n\n    def test_apng_mode(self):\n        with Image.open(\"Tests/images/apng/mode_16bit.png\") as im:\n            self.assertEqual(im.mode, \"RGBA\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 128, 191))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 128, 191))\n\n        with Image.open(\"Tests/images/apng/mode_greyscale.png\") as im:\n            self.assertEqual(im.mode, \"L\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), 128)\n            self.assertEqual(im.getpixel((64, 32)), 255)\n\n        with Image.open(\"Tests/images/apng/mode_greyscale_alpha.png\") as im:\n            self.assertEqual(im.mode, \"LA\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (128, 191))\n            self.assertEqual(im.getpixel((64, 32)), (128, 191))\n\n        with Image.open(\"Tests/images/apng/mode_palette.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGB\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0))\n\n        with Image.open(\"Tests/images/apng/mode_palette_alpha.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGBA\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/mode_palette_1bit_alpha.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGBA\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 255, 128))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 255, 128))\n\n    def test_apng_chunk_errors(self):\n        with Image.open(\"Tests/images/apng/chunk_no_actl.png\") as im:\n            self.assertFalse(im.is_animated)\n\n        def open():\n            with Image.open(\"Tests/images/apng/chunk_multi_actl.png\") as im:\n                im.load()\n            self.assertFalse(im.is_animated)\n\n        pytest.warns(UserWarning, open)\n\n        with Image.open(\"Tests/images/apng/chunk_actl_after_idat.png\") as im:\n            self.assertFalse(im.is_animated)\n\n        with Image.open(\"Tests/images/apng/chunk_no_fctl.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n        with Image.open(\"Tests/images/apng/chunk_repeat_fctl.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n        with Image.open(\"Tests/images/apng/chunk_no_fdat.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n    def test_apng_syntax_errors(self):\n        def open_frames_zero():\n            with Image.open(\"Tests/images/apng/syntax_num_frames_zero.png\") as im:\n                self.assertFalse(im.is_animated)\n                with self.assertRaises(OSError):\n                    im.load()\n\n        pytest.warns(UserWarning, open_frames_zero)\n\n        def open_frames_zero_default():\n            with Image.open(\n                \"Tests/images/apng/syntax_num_frames_zero_default.png\"\n            ) as im:\n                self.assertFalse(im.is_animated)\n                im.load()\n\n        pytest.warns(UserWarning, open_frames_zero_default)\n\n        # we can handle this case gracefully\n        exception = None\n        with Image.open(\"Tests/images/apng/syntax_num_frames_low.png\") as im:\n            try:\n                im.seek(im.n_frames - 1)\n            except Exception as e:\n                exception = e\n            self.assertIsNone(exception)\n\n        with self.assertRaises(SyntaxError):\n            with Image.open(\"Tests/images/apng/syntax_num_frames_high.png\") as im:\n                im.seek(im.n_frames - 1)\n                im.load()\n\n        def open():\n            with Image.open(\"Tests/images/apng/syntax_num_frames_invalid.png\") as im:\n                self.assertFalse(im.is_animated)\n                im.load()\n\n        pytest.warns(UserWarning, open)\n\n    def test_apng_sequence_errors(self):\n        test_files = [\n            \"sequence_start.png\",\n            \"sequence_gap.png\",\n            \"sequence_repeat.png\",\n            \"sequence_repeat_chunk.png\",\n            \"sequence_reorder.png\",\n            \"sequence_reorder_chunk.png\",\n            \"sequence_fdat_fctl.png\",\n        ]\n        for f in test_files:\n            with self.assertRaises(SyntaxError):\n                with Image.open(\"Tests/images/apng/{0}\".format(f)) as im:\n                    im.seek(im.n_frames - 1)\n                    im.load()\n\n    def test_apng_save(self):\n        with Image.open(\"Tests/images/apng/single_frame.png\") as im:\n            test_file = self.tempfile(\"temp.png\")\n            im.save(test_file, save_all=True)\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertIsNone(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/single_frame_default.png\") as im:\n            frames = []\n            for frame_im in ImageSequence.Iterator(im):\n                frames.append(frame_im.copy())\n            frames[0].save(\n                test_file, save_all=True, default_image=True, append_images=frames[1:]\n            )\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertTrue(im.info.get(\"default_image\"))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_save_split_fdat(self):\n        # test to make sure we do not generate sequence errors when writing\n        # frames with image data spanning multiple fdAT chunks (in this case\n        # both the default image and first animation frame will span multiple\n        # data chunks)\n        test_file = self.tempfile(\"temp.png\")\n        with Image.open(\"Tests/images/old-style-jpeg-compression.png\") as im:\n            frames = [im.copy(), Image.new(\"RGBA\", im.size, (255, 0, 0, 255))]\n            im.save(\n                test_file, save_all=True, default_image=True, append_images=frames,\n            )\n        with Image.open(test_file) as im:\n            exception = None\n            try:\n                im.seek(im.n_frames - 1)\n                im.load()\n            except Exception as e:\n                exception = e\n            self.assertIsNone(exception)\n\n    def test_apng_save_duration_loop(self):\n        test_file = self.tempfile(\"temp.png\")\n        with Image.open(\"Tests/images/apng/delay.png\") as im:\n            frames = []\n            durations = []\n            loop = im.info.get(\"loop\")\n            default_image = im.info.get(\"default_image\")\n            for i, frame_im in enumerate(ImageSequence.Iterator(im)):\n                frames.append(frame_im.copy())\n                if i != 0 or not default_image:\n                    durations.append(frame_im.info.get(\"duration\", 0))\n            frames[0].save(\n                test_file,\n                save_all=True,\n                default_image=default_image,\n                append_images=frames[1:],\n                duration=durations,\n                loop=loop,\n            )\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertEqual(im.info.get(\"loop\"), loop)\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        # test removal of duplicated frames\n        frame = Image.new(\"RGBA\", (128, 64), (255, 0, 0, 255))\n        frame.save(test_file, save_all=True, append_images=[frame], duration=[500, 250])\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertEqual(im.n_frames, 1)\n            self.assertEqual(im.info.get(\"duration\"), 750)\n\n    def test_apng_save_disposal(self):\n        test_file = self.tempfile(\"temp.png\")\n        size = (128, 64)\n        red = Image.new(\"RGBA\", size, (255, 0, 0, 255))\n        green = Image.new(\"RGBA\", size, (0, 255, 0, 255))\n        transparent = Image.new(\"RGBA\", size, (0, 0, 0, 0))\n\n        # test APNG_DISPOSE_OP_NONE\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, transparent],\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_DISPOSE_OP_BACKGROUND\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_BACKGROUND,\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, transparent],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_BACKGROUND,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_DISPOSE_OP_PREVIOUS\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_PREVIOUS,\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, red, transparent],\n            default_image=True,\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(3)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_PREVIOUS,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_save_blend(self):\n        test_file = self.tempfile(\"temp.png\")\n        size = (128, 64)\n        red = Image.new(\"RGBA\", size, (255, 0, 0, 255))\n        green = Image.new(\"RGBA\", size, (0, 255, 0, 255))\n        transparent = Image.new(\"RGBA\", size, (0, 0, 0, 0))\n\n        # test APNG_BLEND_OP_SOURCE on solid color\n        blend = [\n            PngImagePlugin.APNG_BLEND_OP_OVER,\n            PngImagePlugin.APNG_BLEND_OP_SOURCE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, green],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=blend,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_BLEND_OP_SOURCE on transparent color\n        blend = [\n            PngImagePlugin.APNG_BLEND_OP_OVER,\n            PngImagePlugin.APNG_BLEND_OP_SOURCE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, transparent],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=blend,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        # test APNG_BLEND_OP_OVER\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, transparent],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 8,
                            "end_lineno": 544,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 328,
                            "length": 6
                        },
                        "new_range": {
                            "start": 331,
                            "length": 7
                        },
                        "section": "class TestFilePng(PillowTestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        with Image.open(test_file) as im:",
                                "type": "context"
                            },
                            {
                                "content": "            im.load()",
                                "type": "context"
                            },
                            {
                                "content": "            self.assertTrue(im.is_animated)",
                                "type": "context"
                            },
                            {
                                "content": "            self.assertEqual(im.n_frames, 2)",
                                "type": "added"
                            },
                            {
                                "content": "            self.assertEqual(im.get_format_mimetype(), \"image/apng\")",
                                "type": "context"
                            },
                            {
                                "content": "            self.assertTrue(im.info.get(\"default_image\"))",
                                "type": "context"
                            },
                            {
                                "content": "            im.seek(1)",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "Tests/test_file_apng.py",
                            "type": "method",
                            "name": "TestFilePng.test_apng_save",
                            "content": "class TestFilePng(PillowTestCase):\n\n    # APNG browser support tests and fixtures via:\n    # https://philip.html5.org/tests/apng/tests.html\n    # (referenced from https://wiki.mozilla.org/APNG_Specification)\n    def test_apng_basic(self):\n        with Image.open(\"Tests/images/apng/single_frame.png\") as im:\n            self.assertFalse(im.is_animated)\n            self.assertEqual(im.n_frames, 1)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertIsNone(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/single_frame_default.png\") as im:\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.n_frames, 2)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertTrue(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (255, 0, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (255, 0, 0, 255))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n            # test out of bounds seek\n            with self.assertRaises(EOFError):\n                im.seek(2)\n\n            # test rewind support\n            im.seek(0)\n            self.assertEqual(im.getpixel((0, 0)), (255, 0, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (255, 0, 0, 255))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_fdat(self):\n        with Image.open(\"Tests/images/apng/split_fdat.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/split_fdat_zero_chunk.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_dispose(self):\n        with Image.open(\"Tests/images/apng/dispose_op_none.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background_final.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_final.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_first.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n    def test_apng_dispose_region(self):\n        with Image.open(\"Tests/images/apng/dispose_op_none_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\n            \"Tests/images/apng/dispose_op_background_before_region.png\"\n        ) as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 255, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_blend(self):\n        with Image.open(\"Tests/images/apng/blend_op_source_solid.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/blend_op_source_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/blend_op_source_near_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 2))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 2))\n\n        with Image.open(\"Tests/images/apng/blend_op_over.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/blend_op_over_near_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 97))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_chunk_order(self):\n        with Image.open(\"Tests/images/apng/fctl_actl.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_delay(self):\n        with Image.open(\"Tests/images/apng/delay.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_round.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_short_max.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_zero_denom.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_zero_numer.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 0.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 0.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n    def test_apng_num_plays(self):\n        with Image.open(\"Tests/images/apng/num_plays.png\") as im:\n            self.assertEqual(im.info.get(\"loop\"), 0)\n\n        with Image.open(\"Tests/images/apng/num_plays_1.png\") as im:\n            self.assertEqual(im.info.get(\"loop\"), 1)\n\n    def test_apng_mode(self):\n        with Image.open(\"Tests/images/apng/mode_16bit.png\") as im:\n            self.assertEqual(im.mode, \"RGBA\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 128, 191))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 128, 191))\n\n        with Image.open(\"Tests/images/apng/mode_greyscale.png\") as im:\n            self.assertEqual(im.mode, \"L\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), 128)\n            self.assertEqual(im.getpixel((64, 32)), 255)\n\n        with Image.open(\"Tests/images/apng/mode_greyscale_alpha.png\") as im:\n            self.assertEqual(im.mode, \"LA\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (128, 191))\n            self.assertEqual(im.getpixel((64, 32)), (128, 191))\n\n        with Image.open(\"Tests/images/apng/mode_palette.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGB\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0))\n\n        with Image.open(\"Tests/images/apng/mode_palette_alpha.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGBA\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/mode_palette_1bit_alpha.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGBA\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 255, 128))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 255, 128))\n\n    def test_apng_chunk_errors(self):\n        with Image.open(\"Tests/images/apng/chunk_no_actl.png\") as im:\n            self.assertFalse(im.is_animated)\n\n        def open():\n            with Image.open(\"Tests/images/apng/chunk_multi_actl.png\") as im:\n                im.load()\n            self.assertFalse(im.is_animated)\n\n        pytest.warns(UserWarning, open)\n\n        with Image.open(\"Tests/images/apng/chunk_actl_after_idat.png\") as im:\n            self.assertFalse(im.is_animated)\n\n        with Image.open(\"Tests/images/apng/chunk_no_fctl.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n        with Image.open(\"Tests/images/apng/chunk_repeat_fctl.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n        with Image.open(\"Tests/images/apng/chunk_no_fdat.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n    def test_apng_syntax_errors(self):\n        def open_frames_zero():\n            with Image.open(\"Tests/images/apng/syntax_num_frames_zero.png\") as im:\n                self.assertFalse(im.is_animated)\n                with self.assertRaises(OSError):\n                    im.load()\n\n        pytest.warns(UserWarning, open_frames_zero)\n\n        def open_frames_zero_default():\n            with Image.open(\n                \"Tests/images/apng/syntax_num_frames_zero_default.png\"\n            ) as im:\n                self.assertFalse(im.is_animated)\n                im.load()\n\n        pytest.warns(UserWarning, open_frames_zero_default)\n\n        # we can handle this case gracefully\n        exception = None\n        with Image.open(\"Tests/images/apng/syntax_num_frames_low.png\") as im:\n            try:\n                im.seek(im.n_frames - 1)\n            except Exception as e:\n                exception = e\n            self.assertIsNone(exception)\n\n        with self.assertRaises(SyntaxError):\n            with Image.open(\"Tests/images/apng/syntax_num_frames_high.png\") as im:\n                im.seek(im.n_frames - 1)\n                im.load()\n\n        def open():\n            with Image.open(\"Tests/images/apng/syntax_num_frames_invalid.png\") as im:\n                self.assertFalse(im.is_animated)\n                im.load()\n\n        pytest.warns(UserWarning, open)\n\n    def test_apng_sequence_errors(self):\n        test_files = [\n            \"sequence_start.png\",\n            \"sequence_gap.png\",\n            \"sequence_repeat.png\",\n            \"sequence_repeat_chunk.png\",\n            \"sequence_reorder.png\",\n            \"sequence_reorder_chunk.png\",\n            \"sequence_fdat_fctl.png\",\n        ]\n        for f in test_files:\n            with self.assertRaises(SyntaxError):\n                with Image.open(\"Tests/images/apng/{0}\".format(f)) as im:\n                    im.seek(im.n_frames - 1)\n                    im.load()\n\n    def test_apng_save(self):\n        with Image.open(\"Tests/images/apng/single_frame.png\") as im:\n            test_file = self.tempfile(\"temp.png\")\n            im.save(test_file, save_all=True)\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertFalse(im.is_animated)\n            self.assertEqual(im.n_frames, 1)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertIsNone(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/single_frame_default.png\") as im:\n            frames = []\n            for frame_im in ImageSequence.Iterator(im):\n                frames.append(frame_im.copy())\n            frames[0].save(\n                test_file, save_all=True, default_image=True, append_images=frames[1:]\n            )\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.n_frames, 2)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertTrue(im.info.get(\"default_image\"))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_save_split_fdat(self):\n        # test to make sure we do not generate sequence errors when writing\n        # frames with image data spanning multiple fdAT chunks (in this case\n        # both the default image and first animation frame will span multiple\n        # data chunks)\n        test_file = self.tempfile(\"temp.png\")\n        with Image.open(\"Tests/images/old-style-jpeg-compression.png\") as im:\n            frames = [im.copy(), Image.new(\"RGBA\", im.size, (255, 0, 0, 255))]\n            im.save(\n                test_file, save_all=True, default_image=True, append_images=frames,\n            )\n        with Image.open(test_file) as im:\n            exception = None\n            try:\n                im.seek(im.n_frames - 1)\n                im.load()\n            except Exception as e:\n                exception = e\n            self.assertIsNone(exception)\n\n    def test_apng_save_duration_loop(self):\n        test_file = self.tempfile(\"temp.png\")\n        with Image.open(\"Tests/images/apng/delay.png\") as im:\n            frames = []\n            durations = []\n            loop = im.info.get(\"loop\")\n            default_image = im.info.get(\"default_image\")\n            for i, frame_im in enumerate(ImageSequence.Iterator(im)):\n                frames.append(frame_im.copy())\n                if i != 0 or not default_image:\n                    durations.append(frame_im.info.get(\"duration\", 0))\n            frames[0].save(\n                test_file,\n                save_all=True,\n                default_image=default_image,\n                append_images=frames[1:],\n                duration=durations,\n                loop=loop,\n            )\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertEqual(im.info.get(\"loop\"), loop)\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        # test removal of duplicated frames\n        frame = Image.new(\"RGBA\", (128, 64), (255, 0, 0, 255))\n        frame.save(test_file, save_all=True, append_images=[frame], duration=[500, 250])\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertEqual(im.n_frames, 1)\n            self.assertEqual(im.info.get(\"duration\"), 750)\n\n    def test_apng_save_disposal(self):\n        test_file = self.tempfile(\"temp.png\")\n        size = (128, 64)\n        red = Image.new(\"RGBA\", size, (255, 0, 0, 255))\n        green = Image.new(\"RGBA\", size, (0, 255, 0, 255))\n        transparent = Image.new(\"RGBA\", size, (0, 0, 0, 0))\n\n        # test APNG_DISPOSE_OP_NONE\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, transparent],\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_DISPOSE_OP_BACKGROUND\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_BACKGROUND,\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, transparent],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_BACKGROUND,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_DISPOSE_OP_PREVIOUS\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_PREVIOUS,\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, red, transparent],\n            default_image=True,\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(3)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_PREVIOUS,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_save_blend(self):\n        test_file = self.tempfile(\"temp.png\")\n        size = (128, 64)\n        red = Image.new(\"RGBA\", size, (255, 0, 0, 255))\n        green = Image.new(\"RGBA\", size, (0, 255, 0, 255))\n        transparent = Image.new(\"RGBA\", size, (0, 0, 0, 0))\n\n        # test APNG_BLEND_OP_SOURCE on solid color\n        blend = [\n            PngImagePlugin.APNG_BLEND_OP_OVER,\n            PngImagePlugin.APNG_BLEND_OP_SOURCE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, green],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=blend,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_BLEND_OP_SOURCE on transparent color\n        blend = [\n            PngImagePlugin.APNG_BLEND_OP_OVER,\n            PngImagePlugin.APNG_BLEND_OP_SOURCE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, transparent],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=blend,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        # test APNG_BLEND_OP_OVER\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, transparent],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 309,
                            "end_lineno": 339,
                            "parent": {
                                "file_name": "Tests/test_file_apng.py",
                                "type": "class",
                                "name": "TestFilePng",
                                "content": "class TestFilePng(PillowTestCase):\n\n    # APNG browser support tests and fixtures via:\n    # https://philip.html5.org/tests/apng/tests.html\n    # (referenced from https://wiki.mozilla.org/APNG_Specification)\n    def test_apng_basic(self):\n        with Image.open(\"Tests/images/apng/single_frame.png\") as im:\n            self.assertFalse(im.is_animated)\n            self.assertEqual(im.n_frames, 1)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertIsNone(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/single_frame_default.png\") as im:\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.n_frames, 2)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertTrue(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (255, 0, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (255, 0, 0, 255))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n            # test out of bounds seek\n            with self.assertRaises(EOFError):\n                im.seek(2)\n\n            # test rewind support\n            im.seek(0)\n            self.assertEqual(im.getpixel((0, 0)), (255, 0, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (255, 0, 0, 255))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_fdat(self):\n        with Image.open(\"Tests/images/apng/split_fdat.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/split_fdat_zero_chunk.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_dispose(self):\n        with Image.open(\"Tests/images/apng/dispose_op_none.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background_final.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_final.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_first.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n    def test_apng_dispose_region(self):\n        with Image.open(\"Tests/images/apng/dispose_op_none_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\n            \"Tests/images/apng/dispose_op_background_before_region.png\"\n        ) as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 255, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_blend(self):\n        with Image.open(\"Tests/images/apng/blend_op_source_solid.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/blend_op_source_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/blend_op_source_near_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 2))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 2))\n\n        with Image.open(\"Tests/images/apng/blend_op_over.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/blend_op_over_near_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 97))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_chunk_order(self):\n        with Image.open(\"Tests/images/apng/fctl_actl.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_delay(self):\n        with Image.open(\"Tests/images/apng/delay.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_round.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_short_max.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_zero_denom.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_zero_numer.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 0.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 0.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n    def test_apng_num_plays(self):\n        with Image.open(\"Tests/images/apng/num_plays.png\") as im:\n            self.assertEqual(im.info.get(\"loop\"), 0)\n\n        with Image.open(\"Tests/images/apng/num_plays_1.png\") as im:\n            self.assertEqual(im.info.get(\"loop\"), 1)\n\n    def test_apng_mode(self):\n        with Image.open(\"Tests/images/apng/mode_16bit.png\") as im:\n            self.assertEqual(im.mode, \"RGBA\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 128, 191))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 128, 191))\n\n        with Image.open(\"Tests/images/apng/mode_greyscale.png\") as im:\n            self.assertEqual(im.mode, \"L\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), 128)\n            self.assertEqual(im.getpixel((64, 32)), 255)\n\n        with Image.open(\"Tests/images/apng/mode_greyscale_alpha.png\") as im:\n            self.assertEqual(im.mode, \"LA\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (128, 191))\n            self.assertEqual(im.getpixel((64, 32)), (128, 191))\n\n        with Image.open(\"Tests/images/apng/mode_palette.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGB\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0))\n\n        with Image.open(\"Tests/images/apng/mode_palette_alpha.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGBA\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/mode_palette_1bit_alpha.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGBA\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 255, 128))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 255, 128))\n\n    def test_apng_chunk_errors(self):\n        with Image.open(\"Tests/images/apng/chunk_no_actl.png\") as im:\n            self.assertFalse(im.is_animated)\n\n        def open():\n            with Image.open(\"Tests/images/apng/chunk_multi_actl.png\") as im:\n                im.load()\n            self.assertFalse(im.is_animated)\n\n        pytest.warns(UserWarning, open)\n\n        with Image.open(\"Tests/images/apng/chunk_actl_after_idat.png\") as im:\n            self.assertFalse(im.is_animated)\n\n        with Image.open(\"Tests/images/apng/chunk_no_fctl.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n        with Image.open(\"Tests/images/apng/chunk_repeat_fctl.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n        with Image.open(\"Tests/images/apng/chunk_no_fdat.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n    def test_apng_syntax_errors(self):\n        def open_frames_zero():\n            with Image.open(\"Tests/images/apng/syntax_num_frames_zero.png\") as im:\n                self.assertFalse(im.is_animated)\n                with self.assertRaises(OSError):\n                    im.load()\n\n        pytest.warns(UserWarning, open_frames_zero)\n\n        def open_frames_zero_default():\n            with Image.open(\n                \"Tests/images/apng/syntax_num_frames_zero_default.png\"\n            ) as im:\n                self.assertFalse(im.is_animated)\n                im.load()\n\n        pytest.warns(UserWarning, open_frames_zero_default)\n\n        # we can handle this case gracefully\n        exception = None\n        with Image.open(\"Tests/images/apng/syntax_num_frames_low.png\") as im:\n            try:\n                im.seek(im.n_frames - 1)\n            except Exception as e:\n                exception = e\n            self.assertIsNone(exception)\n\n        with self.assertRaises(SyntaxError):\n            with Image.open(\"Tests/images/apng/syntax_num_frames_high.png\") as im:\n                im.seek(im.n_frames - 1)\n                im.load()\n\n        def open():\n            with Image.open(\"Tests/images/apng/syntax_num_frames_invalid.png\") as im:\n                self.assertFalse(im.is_animated)\n                im.load()\n\n        pytest.warns(UserWarning, open)\n\n    def test_apng_sequence_errors(self):\n        test_files = [\n            \"sequence_start.png\",\n            \"sequence_gap.png\",\n            \"sequence_repeat.png\",\n            \"sequence_repeat_chunk.png\",\n            \"sequence_reorder.png\",\n            \"sequence_reorder_chunk.png\",\n            \"sequence_fdat_fctl.png\",\n        ]\n        for f in test_files:\n            with self.assertRaises(SyntaxError):\n                with Image.open(\"Tests/images/apng/{0}\".format(f)) as im:\n                    im.seek(im.n_frames - 1)\n                    im.load()\n\n    def test_apng_save(self):\n        with Image.open(\"Tests/images/apng/single_frame.png\") as im:\n            test_file = self.tempfile(\"temp.png\")\n            im.save(test_file, save_all=True)\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertFalse(im.is_animated)\n            self.assertEqual(im.n_frames, 1)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertIsNone(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/single_frame_default.png\") as im:\n            frames = []\n            for frame_im in ImageSequence.Iterator(im):\n                frames.append(frame_im.copy())\n            frames[0].save(\n                test_file, save_all=True, default_image=True, append_images=frames[1:]\n            )\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.n_frames, 2)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertTrue(im.info.get(\"default_image\"))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_save_split_fdat(self):\n        # test to make sure we do not generate sequence errors when writing\n        # frames with image data spanning multiple fdAT chunks (in this case\n        # both the default image and first animation frame will span multiple\n        # data chunks)\n        test_file = self.tempfile(\"temp.png\")\n        with Image.open(\"Tests/images/old-style-jpeg-compression.png\") as im:\n            frames = [im.copy(), Image.new(\"RGBA\", im.size, (255, 0, 0, 255))]\n            im.save(\n                test_file, save_all=True, default_image=True, append_images=frames,\n            )\n        with Image.open(test_file) as im:\n            exception = None\n            try:\n                im.seek(im.n_frames - 1)\n                im.load()\n            except Exception as e:\n                exception = e\n            self.assertIsNone(exception)\n\n    def test_apng_save_duration_loop(self):\n        test_file = self.tempfile(\"temp.png\")\n        with Image.open(\"Tests/images/apng/delay.png\") as im:\n            frames = []\n            durations = []\n            loop = im.info.get(\"loop\")\n            default_image = im.info.get(\"default_image\")\n            for i, frame_im in enumerate(ImageSequence.Iterator(im)):\n                frames.append(frame_im.copy())\n                if i != 0 or not default_image:\n                    durations.append(frame_im.info.get(\"duration\", 0))\n            frames[0].save(\n                test_file,\n                save_all=True,\n                default_image=default_image,\n                append_images=frames[1:],\n                duration=durations,\n                loop=loop,\n            )\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertEqual(im.info.get(\"loop\"), loop)\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        # test removal of duplicated frames\n        frame = Image.new(\"RGBA\", (128, 64), (255, 0, 0, 255))\n        frame.save(test_file, save_all=True, append_images=[frame], duration=[500, 250])\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertEqual(im.n_frames, 1)\n            self.assertEqual(im.info.get(\"duration\"), 750)\n\n    def test_apng_save_disposal(self):\n        test_file = self.tempfile(\"temp.png\")\n        size = (128, 64)\n        red = Image.new(\"RGBA\", size, (255, 0, 0, 255))\n        green = Image.new(\"RGBA\", size, (0, 255, 0, 255))\n        transparent = Image.new(\"RGBA\", size, (0, 0, 0, 0))\n\n        # test APNG_DISPOSE_OP_NONE\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, transparent],\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_DISPOSE_OP_BACKGROUND\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_BACKGROUND,\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, transparent],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_BACKGROUND,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_DISPOSE_OP_PREVIOUS\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_PREVIOUS,\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, red, transparent],\n            default_image=True,\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(3)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_PREVIOUS,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_save_blend(self):\n        test_file = self.tempfile(\"temp.png\")\n        size = (128, 64)\n        red = Image.new(\"RGBA\", size, (255, 0, 0, 255))\n        green = Image.new(\"RGBA\", size, (0, 255, 0, 255))\n        transparent = Image.new(\"RGBA\", size, (0, 0, 0, 0))\n\n        # test APNG_BLEND_OP_SOURCE on solid color\n        blend = [\n            PngImagePlugin.APNG_BLEND_OP_OVER,\n            PngImagePlugin.APNG_BLEND_OP_SOURCE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, green],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=blend,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_BLEND_OP_SOURCE on transparent color\n        blend = [\n            PngImagePlugin.APNG_BLEND_OP_OVER,\n            PngImagePlugin.APNG_BLEND_OP_SOURCE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, transparent],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=blend,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        # test APNG_BLEND_OP_OVER\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, transparent],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 8,
                                "end_lineno": 548,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "Tests/test_file_apng.py",
                            "type": "class",
                            "name": "TestFilePng",
                            "content": "class TestFilePng(PillowTestCase):\n\n    # APNG browser support tests and fixtures via:\n    # https://philip.html5.org/tests/apng/tests.html\n    # (referenced from https://wiki.mozilla.org/APNG_Specification)\n    def test_apng_basic(self):\n        with Image.open(\"Tests/images/apng/single_frame.png\") as im:\n            self.assertFalse(im.is_animated)\n            self.assertEqual(im.n_frames, 1)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertIsNone(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/single_frame_default.png\") as im:\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.n_frames, 2)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertTrue(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (255, 0, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (255, 0, 0, 255))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n            # test out of bounds seek\n            with self.assertRaises(EOFError):\n                im.seek(2)\n\n            # test rewind support\n            im.seek(0)\n            self.assertEqual(im.getpixel((0, 0)), (255, 0, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (255, 0, 0, 255))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_fdat(self):\n        with Image.open(\"Tests/images/apng/split_fdat.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/split_fdat_zero_chunk.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_dispose(self):\n        with Image.open(\"Tests/images/apng/dispose_op_none.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background_final.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_final.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_first.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n    def test_apng_dispose_region(self):\n        with Image.open(\"Tests/images/apng/dispose_op_none_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\n            \"Tests/images/apng/dispose_op_background_before_region.png\"\n        ) as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 255, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_blend(self):\n        with Image.open(\"Tests/images/apng/blend_op_source_solid.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/blend_op_source_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/blend_op_source_near_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 2))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 2))\n\n        with Image.open(\"Tests/images/apng/blend_op_over.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/blend_op_over_near_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 97))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_chunk_order(self):\n        with Image.open(\"Tests/images/apng/fctl_actl.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_delay(self):\n        with Image.open(\"Tests/images/apng/delay.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_round.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_short_max.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_zero_denom.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_zero_numer.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 0.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 0.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n    def test_apng_num_plays(self):\n        with Image.open(\"Tests/images/apng/num_plays.png\") as im:\n            self.assertEqual(im.info.get(\"loop\"), 0)\n\n        with Image.open(\"Tests/images/apng/num_plays_1.png\") as im:\n            self.assertEqual(im.info.get(\"loop\"), 1)\n\n    def test_apng_mode(self):\n        with Image.open(\"Tests/images/apng/mode_16bit.png\") as im:\n            self.assertEqual(im.mode, \"RGBA\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 128, 191))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 128, 191))\n\n        with Image.open(\"Tests/images/apng/mode_greyscale.png\") as im:\n            self.assertEqual(im.mode, \"L\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), 128)\n            self.assertEqual(im.getpixel((64, 32)), 255)\n\n        with Image.open(\"Tests/images/apng/mode_greyscale_alpha.png\") as im:\n            self.assertEqual(im.mode, \"LA\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (128, 191))\n            self.assertEqual(im.getpixel((64, 32)), (128, 191))\n\n        with Image.open(\"Tests/images/apng/mode_palette.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGB\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0))\n\n        with Image.open(\"Tests/images/apng/mode_palette_alpha.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGBA\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/mode_palette_1bit_alpha.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGBA\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 255, 128))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 255, 128))\n\n    def test_apng_chunk_errors(self):\n        with Image.open(\"Tests/images/apng/chunk_no_actl.png\") as im:\n            self.assertFalse(im.is_animated)\n\n        def open():\n            with Image.open(\"Tests/images/apng/chunk_multi_actl.png\") as im:\n                im.load()\n            self.assertFalse(im.is_animated)\n\n        pytest.warns(UserWarning, open)\n\n        with Image.open(\"Tests/images/apng/chunk_actl_after_idat.png\") as im:\n            self.assertFalse(im.is_animated)\n\n        with Image.open(\"Tests/images/apng/chunk_no_fctl.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n        with Image.open(\"Tests/images/apng/chunk_repeat_fctl.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n        with Image.open(\"Tests/images/apng/chunk_no_fdat.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n    def test_apng_syntax_errors(self):\n        def open_frames_zero():\n            with Image.open(\"Tests/images/apng/syntax_num_frames_zero.png\") as im:\n                self.assertFalse(im.is_animated)\n                with self.assertRaises(OSError):\n                    im.load()\n\n        pytest.warns(UserWarning, open_frames_zero)\n\n        def open_frames_zero_default():\n            with Image.open(\n                \"Tests/images/apng/syntax_num_frames_zero_default.png\"\n            ) as im:\n                self.assertFalse(im.is_animated)\n                im.load()\n\n        pytest.warns(UserWarning, open_frames_zero_default)\n\n        # we can handle this case gracefully\n        exception = None\n        with Image.open(\"Tests/images/apng/syntax_num_frames_low.png\") as im:\n            try:\n                im.seek(im.n_frames - 1)\n            except Exception as e:\n                exception = e\n            self.assertIsNone(exception)\n\n        with self.assertRaises(SyntaxError):\n            with Image.open(\"Tests/images/apng/syntax_num_frames_high.png\") as im:\n                im.seek(im.n_frames - 1)\n                im.load()\n\n        def open():\n            with Image.open(\"Tests/images/apng/syntax_num_frames_invalid.png\") as im:\n                self.assertFalse(im.is_animated)\n                im.load()\n\n        pytest.warns(UserWarning, open)\n\n    def test_apng_sequence_errors(self):\n        test_files = [\n            \"sequence_start.png\",\n            \"sequence_gap.png\",\n            \"sequence_repeat.png\",\n            \"sequence_repeat_chunk.png\",\n            \"sequence_reorder.png\",\n            \"sequence_reorder_chunk.png\",\n            \"sequence_fdat_fctl.png\",\n        ]\n        for f in test_files:\n            with self.assertRaises(SyntaxError):\n                with Image.open(\"Tests/images/apng/{0}\".format(f)) as im:\n                    im.seek(im.n_frames - 1)\n                    im.load()\n\n    def test_apng_save(self):\n        with Image.open(\"Tests/images/apng/single_frame.png\") as im:\n            test_file = self.tempfile(\"temp.png\")\n            im.save(test_file, save_all=True)\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertFalse(im.is_animated)\n            self.assertEqual(im.n_frames, 1)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertIsNone(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/single_frame_default.png\") as im:\n            frames = []\n            for frame_im in ImageSequence.Iterator(im):\n                frames.append(frame_im.copy())\n            frames[0].save(\n                test_file, save_all=True, default_image=True, append_images=frames[1:]\n            )\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.n_frames, 2)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertTrue(im.info.get(\"default_image\"))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_save_split_fdat(self):\n        # test to make sure we do not generate sequence errors when writing\n        # frames with image data spanning multiple fdAT chunks (in this case\n        # both the default image and first animation frame will span multiple\n        # data chunks)\n        test_file = self.tempfile(\"temp.png\")\n        with Image.open(\"Tests/images/old-style-jpeg-compression.png\") as im:\n            frames = [im.copy(), Image.new(\"RGBA\", im.size, (255, 0, 0, 255))]\n            im.save(\n                test_file, save_all=True, default_image=True, append_images=frames,\n            )\n        with Image.open(test_file) as im:\n            exception = None\n            try:\n                im.seek(im.n_frames - 1)\n                im.load()\n            except Exception as e:\n                exception = e\n            self.assertIsNone(exception)\n\n    def test_apng_save_duration_loop(self):\n        test_file = self.tempfile(\"temp.png\")\n        with Image.open(\"Tests/images/apng/delay.png\") as im:\n            frames = []\n            durations = []\n            loop = im.info.get(\"loop\")\n            default_image = im.info.get(\"default_image\")\n            for i, frame_im in enumerate(ImageSequence.Iterator(im)):\n                frames.append(frame_im.copy())\n                if i != 0 or not default_image:\n                    durations.append(frame_im.info.get(\"duration\", 0))\n            frames[0].save(\n                test_file,\n                save_all=True,\n                default_image=default_image,\n                append_images=frames[1:],\n                duration=durations,\n                loop=loop,\n            )\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertEqual(im.info.get(\"loop\"), loop)\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        # test removal of duplicated frames\n        frame = Image.new(\"RGBA\", (128, 64), (255, 0, 0, 255))\n        frame.save(test_file, save_all=True, append_images=[frame], duration=[500, 250])\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertEqual(im.n_frames, 1)\n            self.assertEqual(im.info.get(\"duration\"), 750)\n\n    def test_apng_save_disposal(self):\n        test_file = self.tempfile(\"temp.png\")\n        size = (128, 64)\n        red = Image.new(\"RGBA\", size, (255, 0, 0, 255))\n        green = Image.new(\"RGBA\", size, (0, 255, 0, 255))\n        transparent = Image.new(\"RGBA\", size, (0, 0, 0, 0))\n\n        # test APNG_DISPOSE_OP_NONE\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, transparent],\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_DISPOSE_OP_BACKGROUND\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_BACKGROUND,\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, transparent],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_BACKGROUND,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_DISPOSE_OP_PREVIOUS\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_PREVIOUS,\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, red, transparent],\n            default_image=True,\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(3)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_PREVIOUS,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_save_blend(self):\n        test_file = self.tempfile(\"temp.png\")\n        size = (128, 64)\n        red = Image.new(\"RGBA\", size, (255, 0, 0, 255))\n        green = Image.new(\"RGBA\", size, (0, 255, 0, 255))\n        transparent = Image.new(\"RGBA\", size, (0, 0, 0, 0))\n\n        # test APNG_BLEND_OP_SOURCE on solid color\n        blend = [\n            PngImagePlugin.APNG_BLEND_OP_OVER,\n            PngImagePlugin.APNG_BLEND_OP_SOURCE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, green],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=blend,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_BLEND_OP_SOURCE on transparent color\n        blend = [\n            PngImagePlugin.APNG_BLEND_OP_OVER,\n            PngImagePlugin.APNG_BLEND_OP_SOURCE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, transparent],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=blend,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        # test APNG_BLEND_OP_OVER\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, transparent],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 8,
                            "end_lineno": 548,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": ".. _image-file-formats:\n\nImage file formats\n==================\n\nThe Python Imaging Library supports a wide variety of raster file formats.\nOver 30 different file formats can be identified and read by the library.\nWrite support is less extensive, but most common interchange and presentation\nformats are supported.\n\nThe :py:meth:`~PIL.Image.Image.open` function identifies files from their\ncontents, not their names, but the :py:meth:`~PIL.Image.Image.save` method\nlooks at the name to determine which format to use, unless the format is given\nexplicitly.\n\nFully supported formats\n-----------------------\n\n.. contents::\n\nBMP\n^^^\n\nPillow reads and writes Windows and OS/2 BMP files containing ``1``, ``L``, ``P``,\nor ``RGB`` data. 16-colour images are read as ``P`` images. Run-length encoding\nis not supported.\n\nThe :py:meth:`~PIL.Image.Image.open` method sets the following\n:py:attr:`~PIL.Image.Image.info` properties:\n\n**compression**\n    Set to ``bmp_rle`` if the file is run-length encoded.\n\nDIB\n^^^\n\nPillow reads and writes DIB files. DIB files are similar to BMP files, so see\nabove for more information.\n\n    .. versionadded:: 6.0.0\n\nEPS\n^^^\n\nPillow identifies EPS files containing image data, and can read files that\ncontain embedded raster images (ImageData descriptors). If Ghostscript is\navailable, other EPS files can be read as well. The EPS driver can also write\nEPS images. The EPS driver can read EPS images in ``L``, ``LAB``, ``RGB`` and\n``CMYK`` mode, but Ghostscript may convert the images to ``RGB`` mode rather\nthan leaving them in the original color space. The EPS driver can write images\nin ``L``, ``RGB`` and ``CMYK`` modes.\n\nIf Ghostscript is available, you can call the :py:meth:`~PIL.Image.Image.load`\nmethod with the following parameter to affect how Ghostscript renders the EPS\n\n**scale**\n    Affects the scale of the resultant rasterized image. If the EPS suggests\n    that the image be rendered at 100px x 100px, setting this parameter to\n    2 will make the Ghostscript render a 200px x 200px image instead. The\n    relative position of the bounding box is maintained::\n\n        im = Image.open(...)\n        im.size #(100,100)\n        im.load(scale=2)\n        im.size #(200,200)\n\nGIF\n^^^\n\nPillow reads GIF87a and GIF89a versions of the GIF file format. The library\nwrites run-length encoded files in GIF87a by default, unless GIF89a features\nare used or GIF89a is already in use.\n\nNote that GIF files are always read as grayscale (``L``)\nor palette mode (``P``) images.\n\nThe :py:meth:`~PIL.Image.Image.open` method sets the following\n:py:attr:`~PIL.Image.Image.info` properties:\n\n**background**\n    Default background color (a palette color index).\n\n**transparency**\n    Transparency color index. This key is omitted if the image is not\n    transparent.\n\n**version**\n    Version (either ``GIF87a`` or ``GIF89a``).\n\n**duration**\n    May not be present. The time to display the current frame\n    of the GIF, in milliseconds.\n\n**loop**\n    May not be present. The number of times the GIF should loop. 0 means that\n    it will loop forever.\n\n**comment**\n    May not be present. A comment about the image.\n\n**extension**\n    May not be present. Contains application specific information.\n\nReading sequences\n~~~~~~~~~~~~~~~~~\n\nThe GIF loader supports the :py:meth:`~PIL.Image.Image.seek` and\n:py:meth:`~PIL.Image.Image.tell` methods. You can combine these methods\nto seek to the next frame (``im.seek(im.tell() + 1)``).\n\n``im.seek()`` raises an :py:exc:`EOFError` if you try to seek after the last frame.\n\nSaving\n~~~~~~\n\nWhen calling :py:meth:`~PIL.Image.Image.save` to write a GIF file, the\nfollowing options are available::\n\n    im.save(out, save_all=True, append_images=[im1, im2, ...])\n\n**save_all**\n    If present and true, all frames of the image will be saved. If\n    not, then only the first frame of a multiframe image will be saved.\n\n**append_images**\n    A list of images to append as additional frames. Each of the\n    images in the list can be single or multiframe images.\n    This is currently supported for GIF, PDF, TIFF, and WebP.\n\n    It is also supported for ICNS. If images are passed in of relevant sizes,\n    they will be used instead of scaling down the main image.\n\n**include_color_table**\n    Whether or not to include local color table.\n\n**interlace**\n    Whether or not the image is interlaced. By default, it is, unless the image\n    is less than 16 pixels in width or height.\n\n**disposal**\n    Indicates the way in which the graphic is to be treated after being displayed.\n\n    * 0 - No disposal specified.\n    * 1 - Do not dispose.\n    * 2 - Restore to background color.\n    * 3 - Restore to previous content.\n\n     Pass a single integer for a constant disposal, or a list or tuple\n     to set the disposal for each frame separately.\n\n**palette**\n    Use the specified palette for the saved image. The palette should\n    be a bytes or bytearray object containing the palette entries in\n    RGBRGB... form. It should be no more than 768 bytes. Alternately,\n    the palette can be passed in as an\n    :py:class:`PIL.ImagePalette.ImagePalette` object.\n\n**optimize**\n    If present and true, attempt to compress the palette by\n    eliminating unused colors. This is only useful if the palette can\n    be compressed to the next smaller power of 2 elements.\n\nNote that if the image you are saving comes from an existing GIF, it may have\nthe following properties in its :py:attr:`~PIL.Image.Image.info` dictionary.\nFor these options, if you do not pass them in, they will default to\ntheir :py:attr:`~PIL.Image.Image.info` values.\n\n**transparency**\n    Transparency color index.\n\n**duration**\n    The display duration of each frame of the multiframe gif, in\n    milliseconds. Pass a single integer for a constant duration, or a\n    list or tuple to set the duration for each frame separately.\n\n**loop**\n    Integer number of times the GIF should loop. 0 means that it will loop\n    forever. By default, the image will not loop.\n\n**comment**\n    A comment about the image.\n\nReading local images\n~~~~~~~~~~~~~~~~~~~~\n\nThe GIF loader creates an image memory the same size as the GIF file’s *logical\nscreen size*, and pastes the actual pixel data (the *local image*) into this\nimage. If you only want the actual pixel rectangle, you can manipulate the\n:py:attr:`~PIL.Image.Image.size` and :py:attr:`~PIL.Image.Image.tile`\nattributes before loading the file::\n\n    im = Image.open(...)\n\n    if im.tile[0][0] == \"gif\":\n        # only read the first \"local image\" from this GIF file\n        tag, (x0, y0, x1, y1), offset, extra = im.tile[0]\n        im.size = (x1 - x0, y1 - y0)\n        im.tile = [(tag, (0, 0) + im.size, offset, extra)]\n\nICNS\n^^^^\n\nPillow reads and (macOS only) writes macOS ``.icns`` files.  By default, the\nlargest available icon is read, though you can override this by setting the\n:py:attr:`~PIL.Image.Image.size` property before calling\n:py:meth:`~PIL.Image.Image.load`.  The :py:meth:`~PIL.Image.Image.open` method\nsets the following :py:attr:`~PIL.Image.Image.info` property:\n\n**sizes**\n    A list of supported sizes found in this icon file; these are a\n    3-tuple, ``(width, height, scale)``, where ``scale`` is 2 for a retina\n    icon and 1 for a standard icon.  You *are* permitted to use this 3-tuple\n    format for the :py:attr:`~PIL.Image.Image.size` property if you set it\n    before calling :py:meth:`~PIL.Image.Image.load`; after loading, the size\n    will be reset to a 2-tuple containing pixel dimensions (so, e.g. if you\n    ask for ``(512, 512, 2)``, the final value of\n    :py:attr:`~PIL.Image.Image.size` will be ``(1024, 1024)``).\n\nThe :py:meth:`~PIL.Image.Image.save` method can take the following keyword arguments:\n\n**append_images**\n    A list of images to replace the scaled down versions of the image.\n    The order of the images does not matter, as their use is determined by\n    the size of each image.\n\n    .. versionadded:: 5.1.0\n\nICO\n^^^\n\nICO is used to store icons on Windows. The largest available icon is read.\n\nThe :py:meth:`~PIL.Image.Image.save` method supports the following options:\n\n**sizes**\n    A list of sizes including in this ico file; these are a 2-tuple,\n    ``(width, height)``; Default to ``[(16, 16), (24, 24), (32, 32), (48, 48),\n    (64, 64), (128, 128), (256, 256)]``. Any sizes bigger than the original\n    size or 256 will be ignored.\n\nIM\n^^\n\nIM is a format used by LabEye and other applications based on the IFUNC image\nprocessing library. The library reads and writes most uncompressed interchange\nversions of this format.\n\nIM is the only format that can store all internal Pillow formats.\n\nJPEG\n^^^^\n\nPillow reads JPEG, JFIF, and Adobe JPEG files containing ``L``, ``RGB``, or\n``CMYK`` data. It writes standard and progressive JFIF files.\n\nUsing the :py:meth:`~PIL.Image.Image.draft` method, you can speed things up by\nconverting ``RGB`` images to ``L``, and resize images to 1/2, 1/4 or 1/8 of\ntheir original size while loading them.\n\nThe :py:meth:`~PIL.Image.Image.open` method may set the following\n:py:attr:`~PIL.Image.Image.info` properties if available:\n\n**jfif**\n    JFIF application marker found. If the file is not a JFIF file, this key is\n    not present.\n\n**jfif_version**\n    A tuple representing the jfif version, (major version, minor version).\n\n**jfif_density**\n    A tuple representing the pixel density of the image, in units specified\n    by jfif_unit.\n\n**jfif_unit**\n    Units for the jfif_density:\n\n    * 0 - No Units\n    * 1 - Pixels per Inch\n    * 2 - Pixels per Centimeter\n\n**dpi**\n    A tuple representing the reported pixel density in pixels per inch, if\n    the file is a jfif file and the units are in inches.\n\n**adobe**\n    Adobe application marker found. If the file is not an Adobe JPEG file, this\n    key is not present.\n\n**adobe_transform**\n    Vendor Specific Tag.\n\n**progression**\n    Indicates that this is a progressive JPEG file.\n\n**icc_profile**\n    The ICC color profile for the image.\n\n**exif**\n    Raw EXIF data from the image.\n\n\nThe :py:meth:`~PIL.Image.Image.save` method supports the following options:\n\n**quality**\n    The image quality, on a scale from 1 (worst) to 95 (best). The default is\n    75. Values above 95 should be avoided; 100 disables portions of the JPEG\n    compression algorithm, and results in large files with hardly any gain in\n    image quality.\n\n**optimize**\n    If present and true, indicates that the encoder should make an extra pass\n    over the image in order to select optimal encoder settings.\n\n**progressive**\n    If present and true, indicates that this image should be stored as a\n    progressive JPEG file.\n\n**dpi**\n    A tuple of integers representing the pixel density, ``(x,y)``.\n\n**icc_profile**\n    If present and true, the image is stored with the provided ICC profile.\n    If this parameter is not provided, the image will be saved with no profile\n    attached. To preserve the existing profile::\n\n        im.save(filename, 'jpeg', icc_profile=im.info.get('icc_profile'))\n\n**exif**\n    If present, the image will be stored with the provided raw EXIF data.\n\n**subsampling**\n    If present, sets the subsampling for the encoder.\n\n    * ``keep``: Only valid for JPEG files, will retain the original image setting.\n    * ``4:4:4``, ``4:2:2``, ``4:2:0``: Specific sampling values\n    * ``-1``: equivalent to ``keep``\n    * ``0``: equivalent to ``4:4:4``\n    * ``1``: equivalent to ``4:2:2``\n    * ``2``: equivalent to ``4:2:0``\n\n**qtables**\n    If present, sets the qtables for the encoder. This is listed as an\n    advanced option for wizards in the JPEG documentation. Use with\n    caution. ``qtables`` can be one of several types of values:\n\n    *  a string, naming a preset, e.g. ``keep``, ``web_low``, or ``web_high``\n    *  a list, tuple, or dictionary (with integer keys =\n       range(len(keys))) of lists of 64 integers. There must be\n       between 2 and 4 tables.\n\n    .. versionadded:: 2.5.0\n\n\n.. note::\n\n    To enable JPEG support, you need to build and install the IJG JPEG library\n    before building the Python Imaging Library. See the distribution README for\n    details.\n\nJPEG 2000\n^^^^^^^^^\n\n.. versionadded:: 2.4.0\n\nPillow reads and writes JPEG 2000 files containing ``L``, ``LA``, ``RGB`` or\n``RGBA`` data.  It can also read files containing ``YCbCr`` data, which it\nconverts on read into ``RGB`` or ``RGBA`` depending on whether or not there is\nan alpha channel.  Pillow supports JPEG 2000 raw codestreams (``.j2k`` files),\nas well as boxed JPEG 2000 files (``.j2p`` or ``.jpx`` files).  Pillow does\n*not* support files whose components have different sampling frequencies.\n\nWhen loading, if you set the ``mode`` on the image prior to the\n:py:meth:`~PIL.Image.Image.load` method being invoked, you can ask Pillow to\nconvert the image to either ``RGB`` or ``RGBA`` rather than choosing for\nitself.  It is also possible to set ``reduce`` to the number of resolutions to\ndiscard (each one reduces the size of the resulting image by a factor of 2),\nand ``layers`` to specify the number of quality layers to load.\n\nThe :py:meth:`~PIL.Image.Image.save` method supports the following options:\n\n**offset**\n    The image offset, as a tuple of integers, e.g. (16, 16)\n\n**tile_offset**\n    The tile offset, again as a 2-tuple of integers.\n\n**tile_size**\n    The tile size as a 2-tuple.  If not specified, or if set to None, the\n    image will be saved without tiling.\n\n**quality_mode**\n    Either ``\"rates\"`` or ``\"dB\"`` depending on the units you want to use to\n    specify image quality.\n\n**quality_layers**\n    A sequence of numbers, each of which represents either an approximate size\n    reduction (if quality mode is ``\"rates\"``) or a signal to noise ratio value\n    in decibels.  If not specified, defaults to a single layer of full quality.\n\n**num_resolutions**\n    The number of different image resolutions to be stored (which corresponds\n    to the number of Discrete Wavelet Transform decompositions plus one).\n\n**codeblock_size**\n    The code-block size as a 2-tuple.  Minimum size is 4 x 4, maximum is 1024 x\n    1024, with the additional restriction that no code-block may have more\n    than 4096 coefficients (i.e. the product of the two numbers must be no\n    greater than 4096).\n\n**precinct_size**\n    The precinct size as a 2-tuple.  Must be a power of two along both axes,\n    and must be greater than the code-block size.\n\n**irreversible**\n    If ``True``, use the lossy Irreversible Color Transformation\n    followed by DWT 9-7.  Defaults to ``False``, which means to use the\n    Reversible Color Transformation with DWT 5-3.\n\n**progression**\n    Controls the progression order; must be one of ``\"LRCP\"``, ``\"RLCP\"``,\n    ``\"RPCL\"``, ``\"PCRL\"``, ``\"CPRL\"``.  The letters stand for Component,\n    Position, Resolution and Layer respectively and control the order of\n    encoding, the idea being that e.g. an image encoded using LRCP mode can\n    have its quality layers decoded as they arrive at the decoder, while one\n    encoded using RLCP mode will have increasing resolutions decoded as they\n    arrive, and so on.\n\n**cinema_mode**\n    Set the encoder to produce output compliant with the digital cinema\n    specifications.  The options here are ``\"no\"`` (the default),\n    ``\"cinema2k-24\"`` for 24fps 2K, ``\"cinema2k-48\"`` for 48fps 2K, and\n    ``\"cinema4k-24\"`` for 24fps 4K.  Note that for compliant 2K files,\n    *at least one* of your image dimensions must match 2048 x 1080, while\n    for compliant 4K files, *at least one* of the dimensions must match\n    4096 x 2160.\n\n.. note::\n\n   To enable JPEG 2000 support, you need to build and install the OpenJPEG\n   library, version 2.0.0 or higher, before building the Python Imaging\n   Library.\n\n   Windows users can install the OpenJPEG binaries available on the\n   OpenJPEG website, but must add them to their PATH in order to use Pillow (if\n   you fail to do this, you will get errors about not being able to load the\n   ``_imaging`` DLL).\n\nMSP\n^^^\n\nPillow identifies and reads MSP files from Windows 1 and 2. The library writes\nuncompressed (Windows 1) versions of this format.\n\nPCX\n^^^\n\nPillow reads and writes PCX files containing ``1``, ``L``, ``P``, or ``RGB`` data.\n\nPNG\n^^^\n\nPillow identifies, reads, and writes PNG files containing ``1``, ``L``, ``LA``,\n``I``, ``P``, ``RGB`` or ``RGBA`` data. Interlaced files are supported as of\nv1.1.7.\n\nAs of Pillow 6.0, EXIF data can be read from PNG images. However, unlike other\nimage formats, EXIF data is not guaranteed to be present in\n:py:attr:`~PIL.Image.Image.info` until :py:meth:`~PIL.Image.Image.load` has been\ncalled.\n\nThe :py:meth:`~PIL.Image.Image.open` method sets the following\n:py:attr:`~PIL.Image.Image.info` properties, when appropriate:\n\n**chromaticity**\n    The chromaticity points, as an 8 tuple of floats. (``White Point\n    X``, ``White Point Y``, ``Red X``, ``Red Y``, ``Green X``, ``Green\n    Y``, ``Blue X``, ``Blue Y``)\n\n**gamma**\n    Gamma, given as a floating point number.\n\n**srgb**\n    The sRGB rendering intent as an integer.\n\n      * 0 Perceptual\n      * 1 Relative Colorimetric\n      * 2 Saturation\n      * 3 Absolute Colorimetric\n\n**transparency**\n    For ``P`` images: Either the palette index for full transparent pixels,\n    or a byte string with alpha values for each palette entry.\n\n    For ``1``, ``L``, ``I`` and ``RGB`` images, the color that represents\n    full transparent pixels in this image.\n\n    This key is omitted if the image is not a transparent palette image.\n\n``open`` also sets ``Image.text`` to a dictionary of the values of the\n``tEXt``, ``zTXt``, and ``iTXt`` chunks of the PNG image. Individual\ncompressed chunks are limited to a decompressed size of\n``PngImagePlugin.MAX_TEXT_CHUNK``, by default 1MB, to prevent\ndecompression bombs. Additionally, the total size of all of the text\nchunks is limited to ``PngImagePlugin.MAX_TEXT_MEMORY``, defaulting to\n64MB.\n\nThe :py:meth:`~PIL.Image.Image.save` method supports the following options:\n\n**optimize**\n    If present and true, instructs the PNG writer to make the output file as\n    small as possible. This includes extra processing in order to find optimal\n    encoder settings.\n\n**transparency**\n    For ``P``, ``1``, ``L``, ``I``, and ``RGB`` images, this option controls\n    what color from the image to mark as transparent.\n\n    For ``P`` images, this can be a either the palette index,\n    or a byte string with alpha values for each palette entry.\n\n**dpi**\n    A tuple of two numbers corresponding to the desired dpi in each direction.\n\n**pnginfo**\n    A :py:class:`PIL.PngImagePlugin.PngInfo` instance containing text tags.\n\n**compress_level**\n    ZLIB compression level, a number between 0 and 9: 1 gives best speed,\n    9 gives best compression, 0 gives no compression at all. Default is 6.\n    When ``optimize`` option is True ``compress_level`` has no effect\n    (it is set to 9 regardless of a value passed).\n\n**icc_profile**\n    The ICC Profile to include in the saved file.\n\n**exif**\n    The exif data to include in the saved file.\n\n    .. versionadded:: 6.0.0\n\n**bits (experimental)**\n    For ``P`` images, this option controls how many bits to store. If omitted,\n    the PNG writer uses 8 bits (256 colors).\n\n**dictionary (experimental)**\n    Set the ZLIB encoder dictionary.\n\n.. note::\n\n    To enable PNG support, you need to build and install the ZLIB compression\n    library before building the Python Imaging Library. See the `installation\n    documentation <../installation.html>`_ for details.\n\n.. _apng-sequences:\n\nAPNG sequences\n~~~~~~~~~~~~~~\n\nThe PNG loader includes limited support for reading and writing Animated Portable\nNetwork Graphics (APNG) files.\nWhen an APNG file is loaded, :py:meth:`~PIL.ImageFile.ImageFile.get_format_mimetype`\nwill return ``\"image/apng\"``, and the :py:attr:`~PIL.Image.Image.is_animated` property\nwill be ``True`` (even for single frame APNG files).\nThe :py:meth:`~PIL.Image.Image.seek` and :py:meth:`~PIL.Image.Image.tell` methods\nare supported.\n\n``im.seek()`` raises an :py:exc:`EOFError` if you try to seek after the last frame.\n\nThese :py:attr:`~PIL.Image.Image.info` properties will be set for APNG frames,\nwhere applicable:\n\n**default_image**\n    Specifies whether or not this APNG file contains a separate default image,\n    which is not a part of the actual APNG animation.\n\n    When an APNG file contains a default image, the initially loaded image (i.e.\n    the result of ``seek(0)``) will be the default image.\n    To account for the presence of the default image, the\n    :py:attr:`~PIL.Image.Image.n_frames` property will be set to ``frame_count + 1``,\n    where ``frame_count`` is the actual APNG animation frame count.\n    To load the first APNG animation frame, ``seek(1)`` must be called.\n\n    * ``True`` - The APNG contains default image, which is not an animation frame.\n    * ``False`` - The APNG does not contain a default image. The ``n_frames`` property\n      will be set to the actual APNG animation frame count.\n      The initially loaded image (i.e. ``seek(0)``) will be the first APNG animation\n      frame.\n\n**loop**\n    The number of times to loop this APNG, 0 indicates infinite looping.\n\n**duration**\n    The time to display this APNG frame (in milliseconds).\n\n.. note::\n\n    The APNG loader returns images the same size as the APNG file's logical screen size.\n    The returned image contains the pixel data for a given frame, after applying\n    any APNG frame disposal and frame blend operations (i.e. it contains what a web\n    browser would render for this frame - the composite of all previous frames and this\n    frame).\n\n    Any APNG file containing sequence errors is treated as an invalid image. The APNG\n    loader will not attempt to repair and reorder files containing sequence errors.\n\nSaving\n~~~~~~\n\nWhen calling :py:meth:`~PIL.Image.Image.save`, by default only a single frame PNG file\nwill be saved. To save an APNG file (including a single frame APNG), the ``save_all``\nparameter must be set to ``True``. The following parameters can also be set:\n\n**default_image**\n    Boolean value, specifying whether or not the base image is a default image.\n    If ``True``, the base image will be used as the default image, and the first image\n    from the ``append_images`` sequence will be the first APNG animation frame.\n    If ``False``, the base image will be used as the first APNG animation frame.\n    Defaults to ``False``.\n\n**append_images**\n    A list or tuple of images to append as additional frames. Each of the\n    images in the list can be single or multiframe images. The size of each frame\n    should match the size of the base image. Also note that if a frame's mode does\n    not match that of the base image, the frame will be converted to the base image\n    mode.\n\n**loop**\n    Integer number of times to loop this APNG, 0 indicates infinite looping.\n    Defaults to 0.\n\n**duration**\n    Integer (or list or tuple of integers) length of time to display this APNG frame\n    (in milliseconds).\n    Defaults to 0.\n\n**disposal**\n    An integer (or list or tuple of integers) specifying the APNG disposal\n    operation to be used for this frame before rendering the next frame.\n    Defaults to 0.\n\n    * 0 (:py:data:`~PIL.PngImagePlugin.APNG_DISPOSE_OP_NONE`, default) -\n      No disposal is done on this frame before rendering the next frame.\n    * 1 (:py:data:`PIL.PngImagePlugin.APNG_DISPOSE_OP_BACKGROUND`) -\n      This frame's modified region is cleared to fully transparent black before\n      rendering the next frame.\n    * 2 (:py:data:`~PIL.PngImagePlugin.APNG_DISPOSE_OP_PREVIOUS`) -\n      This frame's modified region is reverted to the previous frame's contents before\n      rendering the next frame.\n\n**blend**\n    An integer (or list or tuple of integers) specifying the APNG blend\n    operation to be used for this frame before rendering the next frame.\n    Defaults to 0.\n\n    * 0 (:py:data:`~PIL.PngImagePlugin.APNG_BLEND_OP_SOURCE`) -\n      All color components of this frame, including alpha, overwrite the previous output\n      image contents.\n    * 1 (:py:data:`~PIL.PngImagePlugin.APNG_BLEND_OP_OVER`) -\n      This frame should be alpha composited with the previous output image contents.\n\n.. note::\n\n    The ``duration``, ``disposal`` and ``blend`` parameters can be set to lists or tuples to\n    specify values for each individual frame in the animation. The length of the list or tuple\n    must be identical to the total number of actual frames in the APNG animation.\n    If the APNG contains a default image (i.e. ``default_image`` is set to ``True``),\n    these list or tuple parameters should not include an entry for the default image.\n\n\nPPM\n^^^\n\nPillow reads and writes PBM, PGM, PPM and PNM files containing ``1``, ``L`` or\n``RGB`` data.\n\nSGI\n^^^\n\nPillow reads and writes uncompressed ``L``, ``RGB``, and ``RGBA`` files.\n\n\nSPIDER\n^^^^^^\n\nPillow reads and writes SPIDER image files of 32-bit floating point data\n(\"F;32F\").\n\nPillow also reads SPIDER stack files containing sequences of SPIDER images. The\n:py:meth:`~PIL.Image.Image.seek` and :py:meth:`~PIL.Image.Image.tell` methods are supported, and\nrandom access is allowed.\n\nThe :py:meth:`~PIL.Image.Image.open` method sets the following attributes:\n\n**format**\n    Set to ``SPIDER``\n\n**istack**\n    Set to 1 if the file is an image stack, else 0.\n\n**n_frames**\n    Set to the number of images in the stack.\n\nA convenience method, :py:meth:`~PIL.Image.Image.convert2byte`, is provided for\nconverting floating point data to byte data (mode ``L``)::\n\n    im = Image.open('image001.spi').convert2byte()\n\nWriting files in SPIDER format\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThe extension of SPIDER files may be any 3 alphanumeric characters. Therefore\nthe output format must be specified explicitly::\n\n    im.save('newimage.spi', format='SPIDER')\n\nFor more information about the SPIDER image processing package, see the\n`SPIDER homepage`_ at `Wadsworth Center`_.\n\n.. _SPIDER homepage: https://spider.wadsworth.org/spider_doc/spider/docs/spider.html\n.. _Wadsworth Center: https://www.wadsworth.org/\n\nTGA\n^^^\n\nPillow reads and writes TGA images containing ``L``, ``LA``, ``P``,\n``RGB``, and ``RGBA`` data. Pillow can read and write both uncompressed and\nrun-length encoded TGAs.\n\nTIFF\n^^^^\n\nPillow reads and writes TIFF files. It can read both striped and tiled\nimages, pixel and plane interleaved multi-band images. If you have\nlibtiff and its headers installed, Pillow can read and write many kinds\nof compressed TIFF files. If not, Pillow will only read and write\nuncompressed files.\n\n.. note::\n\n    Beginning in version 5.0.0, Pillow requires libtiff to read or\n    write compressed files. Prior to that release, Pillow had buggy\n    support for reading Packbits, LZW and JPEG compressed TIFFs\n    without using libtiff.\n\nThe :py:meth:`~PIL.Image.Image.open` method sets the following\n:py:attr:`~PIL.Image.Image.info` properties:\n\n**compression**\n    Compression mode.\n\n    .. versionadded:: 2.0.0\n\n**dpi**\n    Image resolution as an ``(xdpi, ydpi)`` tuple, where applicable. You can use\n    the :py:attr:`~PIL.Image.Image.tag` attribute to get more detailed\n    information about the image resolution.\n\n    .. versionadded:: 1.1.5\n\n**resolution**\n    Image resolution as an ``(xres, yres)`` tuple, where applicable. This is a\n    measurement in whichever unit is specified by the file.\n\n    .. versionadded:: 1.1.5\n\n\nThe :py:attr:`~PIL.Image.Image.tag_v2` attribute contains a dictionary\nof TIFF metadata. The keys are numerical indexes from\n:py:attr:`~PIL.TiffTags.TAGS_V2`.  Values are strings or numbers for single\nitems, multiple values are returned in a tuple of values. Rational\nnumbers are returned as a :py:class:`~PIL.TiffImagePlugin.IFDRational`\nobject.\n\n    .. versionadded:: 3.0.0\n\nFor compatibility with legacy code, the\n:py:attr:`~PIL.Image.Image.tag` attribute contains a dictionary of\ndecoded TIFF fields as returned prior to version 3.0.0.  Values are\nreturned as either strings or tuples of numeric values. Rational\nnumbers are returned as a tuple of ``(numerator, denominator)``.\n\n    .. deprecated:: 3.0.0\n\nReading Multi-frame TIFF Images\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThe TIFF loader supports the :py:meth:`~PIL.Image.Image.seek` and\n:py:meth:`~PIL.Image.Image.tell` methods, taking and returning frame numbers\nwithin the image file. You can combine these methods to seek to the next frame\n(``im.seek(im.tell() + 1)``). Frames are numbered from 0 to ``im.num_frames - 1``,\nand can be accessed in any order.\n\n``im.seek()`` raises an :py:exc:`EOFError` if you try to seek after the\nlast frame.\n\nSaving Tiff Images\n~~~~~~~~~~~~~~~~~~\n\nThe :py:meth:`~PIL.Image.Image.save` method can take the following keyword arguments:\n\n**save_all**\n    If true, Pillow will save all frames of the image to a multiframe tiff document.\n\n    .. versionadded:: 3.4.0\n\n**append_images**\n    A list of images to append as additional frames. Each of the\n    images in the list can be single or multiframe images. Note however, that for\n    correct results, all the appended images should have the same\n    ``encoderinfo`` and ``encoderconfig`` properties.\n\n    .. versionadded:: 4.2.0\n\n**tiffinfo**\n    A :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2` object or dict\n    object containing tiff tags and values. The TIFF field type is\n    autodetected for Numeric and string values, any other types\n    require using an :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`\n    object and setting the type in\n    :py:attr:`~PIL.TiffImagePlugin.ImageFileDirectory_v2.tagtype` with\n    the appropriate numerical value from\n    ``TiffTags.TYPES``.\n\n    .. versionadded:: 2.3.0\n\n    Metadata values that are of the rational type should be passed in\n    using a :py:class:`~PIL.TiffImagePlugin.IFDRational` object.\n\n    .. versionadded:: 3.1.0\n\n    For compatibility with legacy code, a\n    :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1` object may\n    be passed in this field. However, this is deprecated.\n\n    .. versionadded:: 5.4.0\n\n    Previous versions only supported some tags when writing using\n    libtiff. The supported list is found in\n    :py:attr:`~PIL:TiffTags.LIBTIFF_CORE`.\n\n    .. versionadded:: 6.1.0\n\n    Added support for signed types (e.g. ``TIFF_SIGNED_LONG``) and multiple values.\n    Multiple values for a single tag must be to\n    :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2` as a tuple and\n    require a matching type in\n    :py:attr:`~PIL.TiffImagePlugin.ImageFileDirectory_v2.tagtype` tagtype.\n\n**compression**\n    A string containing the desired compression method for the\n    file. (valid only with libtiff installed) Valid compression\n    methods are: ``None``, ``\"tiff_ccitt\"``, ``\"group3\"``,\n    ``\"group4\"``, ``\"tiff_jpeg\"``, ``\"tiff_adobe_deflate\"``,\n    ``\"tiff_thunderscan\"``, ``\"tiff_deflate\"``, ``\"tiff_sgilog\"``,\n    ``\"tiff_sgilog24\"``, ``\"tiff_raw_16\"``\n\n**quality**\n    The image quality for JPEG compression, on a scale from 0 (worst) to 100\n    (best). The default is 75.\n\n    .. versionadded:: 6.1.0\n\nThese arguments to set the tiff header fields are an alternative to\nusing the general tags available through tiffinfo.\n\n**description**\n\n**software**\n\n**date_time**\n\n**artist**\n\n**copyright**\n    Strings\n\n**resolution_unit**\n    An integer. 1 for no unit, 2 for inches and 3 for centimeters.\n\n**resolution**\n    Either an integer or a float, used for both the x and y resolution.\n\n**x_resolution**\n    Either an integer or a float.\n\n**y_resolution**\n    Either an integer or a float.\n\n**dpi**\n    A tuple of (x_resolution, y_resolution), with inches as the resolution\n    unit. For consistency with other image formats, the x and y resolutions\n    of the dpi will be rounded to the nearest integer.\n\n\nWebP\n^^^^\n\nPillow reads and writes WebP files. The specifics of Pillow's capabilities with\nthis format are currently undocumented.\n\nThe :py:meth:`~PIL.Image.Image.save` method supports the following options:\n\n**lossless**\n    If present and true, instructs the WebP writer to use lossless compression.\n\n**quality**\n    Integer, 1-100, Defaults to 80. For lossy, 0 gives the smallest\n    size and 100 the largest. For lossless, this parameter is the amount\n    of effort put into the compression: 0 is the fastest, but gives larger\n    files compared to the slowest, but best, 100.\n\n**method**\n    Quality/speed trade-off (0=fast, 6=slower-better). Defaults to 0.\n\n**icc_profile**\n    The ICC Profile to include in the saved file. Only supported if\n    the system WebP library was built with webpmux support.\n\n**exif**\n    The exif data to include in the saved file. Only supported if\n    the system WebP library was built with webpmux support.\n\nSaving sequences\n~~~~~~~~~~~~~~~~~\n\n.. note::\n\n    Support for animated WebP files will only be enabled if the system WebP\n    library is v0.5.0 or later. You can check webp animation support at\n    runtime by calling ``features.check(\"webp_anim\")``.\n\nWhen calling :py:meth:`~PIL.Image.Image.save` to write a WebP file, the\nfollowing options are available when the ``save_all`` argument is present and\ntrue.\n\n**append_images**\n    A list of images to append as additional frames. Each of the\n    images in the list can be single or multiframe images.\n\n**duration**\n    The display duration of each frame, in milliseconds. Pass a single\n    integer for a constant duration, or a list or tuple to set the\n    duration for each frame separately.\n\n**loop**\n    Number of times to repeat the animation. Defaults to [0 = infinite].\n\n**background**\n    Background color of the canvas, as an RGBA tuple with values in\n    the range of (0-255).\n\n**minimize_size**\n    If true, minimize the output size (slow). Implicitly disables\n    key-frame insertion.\n\n**kmin, kmax**\n    Minimum and maximum distance between consecutive key frames in\n    the output. The library may insert some key frames as needed\n    to satisfy this criteria. Note that these conditions should\n    hold: kmax > kmin and kmin >= kmax / 2 + 1. Also, if kmax <= 0,\n    then key-frame insertion is disabled; and if kmax == 1, then all\n    frames will be key-frames (kmin value does not matter for these\n    special cases).\n\n**allow_mixed**\n    If true, use mixed compression mode; the encoder heuristically\n    chooses between lossy and lossless for each frame.\n\nXBM\n^^^\n\nPillow reads and writes X bitmap files (mode ``1``).\n\nRead-only formats\n-----------------\n\nBLP\n^^^\n\nBLP is the Blizzard Mipmap Format, a texture format used in World of\nWarcraft. Pillow supports reading ``JPEG`` Compressed or raw ``BLP1``\nimages, and all types of ``BLP2`` images.\n\nCUR\n^^^\n\nCUR is used to store cursors on Windows. The CUR decoder reads the largest\navailable cursor. Animated cursors are not supported.\n\nDCX\n^^^\n\nDCX is a container file format for PCX files, defined by Intel. The DCX format\nis commonly used in fax applications. The DCX decoder can read files containing\n``1``, ``L``, ``P``, or ``RGB`` data.\n\nWhen the file is opened, only the first image is read. You can use\n:py:meth:`~PIL.Image.Image.seek` or :py:mod:`~PIL.ImageSequence` to read other images.\n\n\nDDS\n^^^\n\nDDS is a popular container texture format used in video games and natively\nsupported by DirectX.\nCurrently, uncompressed RGB data and DXT1, DXT3, and DXT5 pixel formats are\nsupported, and only in ``RGBA`` mode.\n\n.. versionadded:: 3.4.0 DXT3\n\nFLI, FLC\n^^^^^^^^\n\nPillow reads Autodesk FLI and FLC animations.\n\nThe :py:meth:`~PIL.Image.Image.open` method sets the following\n:py:attr:`~PIL.Image.Image.info` properties:\n\n**duration**\n    The delay (in milliseconds) between each frame.\n\nFPX\n^^^\n\nPillow reads Kodak FlashPix files. In the current version, only the highest\nresolution image is read from the file, and the viewing transform is not taken\ninto account.\n\n.. note::\n\n    To enable full FlashPix support, you need to build and install the IJG JPEG\n    library before building the Python Imaging Library. See the distribution\n    README for details.\n\nFTEX\n^^^^\n\n.. versionadded:: 3.2.0\n\nThe FTEX decoder reads textures used for 3D objects in\nIndependence War 2: Edge Of Chaos. The plugin reads a single texture\nper file, in the compressed and uncompressed formats.\n\nGBR\n^^^\n\nThe GBR decoder reads GIMP brush files, version 1 and 2.\n\nThe :py:meth:`~PIL.Image.Image.open` method sets the following\n:py:attr:`~PIL.Image.Image.info` properties:\n\n**comment**\n    The brush name.\n\n**spacing**\n    The spacing between the brushes, in pixels. Version 2 only.\n\nGD\n^^\n\nPillow reads uncompressed GD2 files. Note that you must use\n:py:func:`PIL.GdImageFile.open` to read such a file.\n\nThe :py:meth:`~PIL.Image.Image.open` method sets the following\n:py:attr:`~PIL.Image.Image.info` properties:\n\n**transparency**\n    Transparency color index. This key is omitted if the image is not\n    transparent.\n\nIMT\n^^^\n\nPillow reads Image Tools images containing ``L`` data.\n\nIPTC/NAA\n^^^^^^^^\n\nPillow provides limited read support for IPTC/NAA newsphoto files.\n\nMCIDAS\n^^^^^^\n\nPillow identifies and reads 8-bit McIdas area files.\n\nMIC\n^^^\n\nPillow identifies and reads Microsoft Image Composer (MIC) files. When opened,\nthe first sprite in the file is loaded. You can use :py:meth:`~PIL.Image.Image.seek` and\n:py:meth:`~PIL.Image.Image.tell` to read other sprites from the file.\n\nNote that there may be an embedded gamma of 2.2 in MIC files.\n\nMPO\n^^^\n\nPillow identifies and reads Multi Picture Object (MPO) files, loading the primary\nimage when first opened. The :py:meth:`~PIL.Image.Image.seek` and :py:meth:`~PIL.Image.Image.tell`\nmethods may be used to read other pictures from the file. The pictures are\nzero-indexed and random access is supported.\n\nPCD\n^^^\n\nPillow reads PhotoCD files containing ``RGB`` data. This only reads the 768x512\nresolution image from the file. Higher resolutions are encoded in a proprietary\nencoding.\n\nPIXAR\n^^^^^\n\nPillow provides limited support for PIXAR raster files. The library can\nidentify and read “dumped” RGB files.\n\nThe format code is ``PIXAR``.\n\nPSD\n^^^\n\nPillow identifies and reads PSD files written by Adobe Photoshop 2.5 and 3.0.\n\n\nWAL\n^^^\n\n.. versionadded:: 1.1.4\n\nPillow reads Quake2 WAL texture files.\n\nNote that this file format cannot be automatically identified, so you must use\nthe open function in the :py:mod:`~PIL.WalImageFile` module to read files in\nthis format.\n\nBy default, a Quake2 standard palette is attached to the texture. To override\nthe palette, use the putpalette method.\n\nWMF\n^^^\n\nPillow can identify WMF files.\n\nOn Windows, it can read WMF files. By default, it will load the image at 72\ndpi. To load it at another resolution:\n\n.. code-block:: python\n\n    from PIL import Image\n    with Image.open(\"drawing.wmf\") as im:\n        im.load(dpi=144)\n\nTo add other read or write support, use\n:py:func:`PIL.WmfImagePlugin.register_handler` to register a WMF handler.\n\n.. code-block:: python\n\n    from PIL import Image\n    from PIL import WmfImagePlugin\n\n    class WmfHandler:\n        def open(self, im):\n            ...\n        def load(self, im):\n            ...\n            return image\n        def save(self, im, fp, filename):\n            ...\n\n    wmf_handler = WmfHandler()\n\n    WmfImagePlugin.register_handler(wmf_handler)\n\n    im = Image.open(\"sample.wmf\")\n\nXPM\n^^^\n\nPillow reads X pixmap files (mode ``P``) with 256 colors or less.\n\nThe :py:meth:`~PIL.Image.Image.open` method sets the following\n:py:attr:`~PIL.Image.Image.info` properties:\n\n**transparency**\n    Transparency color index. This key is omitted if the image is not\n    transparent.\n\nWrite-only formats\n------------------\n\nPALM\n^^^^\n\nPillow provides write-only support for PALM pixmap files.\n\nThe format code is ``Palm``, the extension is ``.palm``.\n\nPDF\n^^^\n\nPillow can write PDF (Acrobat) images. Such images are written as binary PDF 1.4\nfiles, using either JPEG or HEX encoding depending on the image mode (and\nwhether JPEG support is available or not).\n\nThe :py:meth:`~PIL.Image.Image.save` method can take the following keyword arguments:\n\n**save_all**\n    If a multiframe image is used, by default, only the first image will be saved.\n    To save all frames, each frame to a separate page of the PDF, the ``save_all``\n    parameter must be present and set to ``True``.\n\n    .. versionadded:: 3.0.0\n\n**append_images**\n    A list of images to append as additional pages. Each of the\n    images in the list can be single or multiframe images.\n\n    .. versionadded:: 4.2.0\n\n**append**\n    Set to True to append pages to an existing PDF file. If the file doesn't\n    exist, an :py:exc:`IOError` will be raised.\n\n    .. versionadded:: 5.1.0\n\n**resolution**\n    Image resolution in DPI. This, together with the number of pixels in the\n    image, will determine the physical dimensions of the page that will be\n    saved in the PDF.\n\n**title**\n    The document’s title. If not appending to an existing PDF file, this will\n    default to the filename.\n\n    .. versionadded:: 5.1.0\n\n**author**\n    The name of the person who created the document.\n\n    .. versionadded:: 5.1.0\n\n**subject**\n    The subject of the document.\n\n    .. versionadded:: 5.1.0\n\n**keywords**\n    Keywords associated with the document.\n\n    .. versionadded:: 5.1.0\n\n**creator**\n    If the document was converted to PDF from another format, the name of the\n    conforming product that created the original document from which it was\n    converted.\n\n    .. versionadded:: 5.1.0\n\n**producer**\n    If the document was converted to PDF from another format, the name of the\n    conforming product that converted it to PDF.\n\n    .. versionadded:: 5.1.0\n\n**creationDate**\n    The creation date of the document. If not appending to an existing PDF\n    file, this will default to the current time.\n\n    .. versionadded:: 5.3.0\n\n**modDate**\n    The modification date of the document. If not appending to an existing PDF\n    file, this will default to the current time.\n\n    .. versionadded:: 5.3.0\n\nXV Thumbnails\n^^^^^^^^^^^^^\n\nPillow can read XV thumbnail files.\n\nIdentify-only formats\n---------------------\n\nBUFR\n^^^^\n\n.. versionadded:: 1.1.3\n\nPillow provides a stub driver for BUFR files.\n\nTo add read or write support to your application, use\n:py:func:`PIL.BufrStubImagePlugin.register_handler`.\n\nFITS\n^^^^\n\n.. versionadded:: 1.1.5\n\nPillow provides a stub driver for FITS files.\n\nTo add read or write support to your application, use\n:py:func:`PIL.FitsStubImagePlugin.register_handler`.\n\nGRIB\n^^^^\n\n.. versionadded:: 1.1.5\n\nPillow provides a stub driver for GRIB files.\n\nThe driver requires the file to start with a GRIB header. If you have files\nwith embedded GRIB data, or files with multiple GRIB fields, your application\nhas to seek to the header before passing the file handle to Pillow.\n\nTo add read or write support to your application, use\n:py:func:`PIL.GribStubImagePlugin.register_handler`.\n\nHDF5\n^^^^\n\n.. versionadded:: 1.1.5\n\nPillow provides a stub driver for HDF5 files.\n\nTo add read or write support to your application, use\n:py:func:`PIL.Hdf5StubImagePlugin.register_handler`.\n\nMPEG\n^^^^\n\nPillow identifies MPEG files.\n",
            "new_file_content": ".. _image-file-formats:\n\nImage file formats\n==================\n\nThe Python Imaging Library supports a wide variety of raster file formats.\nOver 30 different file formats can be identified and read by the library.\nWrite support is less extensive, but most common interchange and presentation\nformats are supported.\n\nThe :py:meth:`~PIL.Image.Image.open` function identifies files from their\ncontents, not their names, but the :py:meth:`~PIL.Image.Image.save` method\nlooks at the name to determine which format to use, unless the format is given\nexplicitly.\n\nFully supported formats\n-----------------------\n\n.. contents::\n\nBMP\n^^^\n\nPillow reads and writes Windows and OS/2 BMP files containing ``1``, ``L``, ``P``,\nor ``RGB`` data. 16-colour images are read as ``P`` images. Run-length encoding\nis not supported.\n\nThe :py:meth:`~PIL.Image.Image.open` method sets the following\n:py:attr:`~PIL.Image.Image.info` properties:\n\n**compression**\n    Set to ``bmp_rle`` if the file is run-length encoded.\n\nDIB\n^^^\n\nPillow reads and writes DIB files. DIB files are similar to BMP files, so see\nabove for more information.\n\n    .. versionadded:: 6.0.0\n\nEPS\n^^^\n\nPillow identifies EPS files containing image data, and can read files that\ncontain embedded raster images (ImageData descriptors). If Ghostscript is\navailable, other EPS files can be read as well. The EPS driver can also write\nEPS images. The EPS driver can read EPS images in ``L``, ``LAB``, ``RGB`` and\n``CMYK`` mode, but Ghostscript may convert the images to ``RGB`` mode rather\nthan leaving them in the original color space. The EPS driver can write images\nin ``L``, ``RGB`` and ``CMYK`` modes.\n\nIf Ghostscript is available, you can call the :py:meth:`~PIL.Image.Image.load`\nmethod with the following parameter to affect how Ghostscript renders the EPS\n\n**scale**\n    Affects the scale of the resultant rasterized image. If the EPS suggests\n    that the image be rendered at 100px x 100px, setting this parameter to\n    2 will make the Ghostscript render a 200px x 200px image instead. The\n    relative position of the bounding box is maintained::\n\n        im = Image.open(...)\n        im.size #(100,100)\n        im.load(scale=2)\n        im.size #(200,200)\n\nGIF\n^^^\n\nPillow reads GIF87a and GIF89a versions of the GIF file format. The library\nwrites run-length encoded files in GIF87a by default, unless GIF89a features\nare used or GIF89a is already in use.\n\nNote that GIF files are always read as grayscale (``L``)\nor palette mode (``P``) images.\n\nThe :py:meth:`~PIL.Image.Image.open` method sets the following\n:py:attr:`~PIL.Image.Image.info` properties:\n\n**background**\n    Default background color (a palette color index).\n\n**transparency**\n    Transparency color index. This key is omitted if the image is not\n    transparent.\n\n**version**\n    Version (either ``GIF87a`` or ``GIF89a``).\n\n**duration**\n    May not be present. The time to display the current frame\n    of the GIF, in milliseconds.\n\n**loop**\n    May not be present. The number of times the GIF should loop. 0 means that\n    it will loop forever.\n\n**comment**\n    May not be present. A comment about the image.\n\n**extension**\n    May not be present. Contains application specific information.\n\nReading sequences\n~~~~~~~~~~~~~~~~~\n\nThe GIF loader supports the :py:meth:`~PIL.Image.Image.seek` and\n:py:meth:`~PIL.Image.Image.tell` methods. You can combine these methods\nto seek to the next frame (``im.seek(im.tell() + 1)``).\n\n``im.seek()`` raises an :py:exc:`EOFError` if you try to seek after the last frame.\n\nSaving\n~~~~~~\n\nWhen calling :py:meth:`~PIL.Image.Image.save` to write a GIF file, the\nfollowing options are available::\n\n    im.save(out, save_all=True, append_images=[im1, im2, ...])\n\n**save_all**\n    If present and true, all frames of the image will be saved. If\n    not, then only the first frame of a multiframe image will be saved.\n\n**append_images**\n    A list of images to append as additional frames. Each of the\n    images in the list can be single or multiframe images.\n    This is currently supported for GIF, PDF, TIFF, and WebP.\n\n    It is also supported for ICNS. If images are passed in of relevant sizes,\n    they will be used instead of scaling down the main image.\n\n**include_color_table**\n    Whether or not to include local color table.\n\n**interlace**\n    Whether or not the image is interlaced. By default, it is, unless the image\n    is less than 16 pixels in width or height.\n\n**disposal**\n    Indicates the way in which the graphic is to be treated after being displayed.\n\n    * 0 - No disposal specified.\n    * 1 - Do not dispose.\n    * 2 - Restore to background color.\n    * 3 - Restore to previous content.\n\n     Pass a single integer for a constant disposal, or a list or tuple\n     to set the disposal for each frame separately.\n\n**palette**\n    Use the specified palette for the saved image. The palette should\n    be a bytes or bytearray object containing the palette entries in\n    RGBRGB... form. It should be no more than 768 bytes. Alternately,\n    the palette can be passed in as an\n    :py:class:`PIL.ImagePalette.ImagePalette` object.\n\n**optimize**\n    If present and true, attempt to compress the palette by\n    eliminating unused colors. This is only useful if the palette can\n    be compressed to the next smaller power of 2 elements.\n\nNote that if the image you are saving comes from an existing GIF, it may have\nthe following properties in its :py:attr:`~PIL.Image.Image.info` dictionary.\nFor these options, if you do not pass them in, they will default to\ntheir :py:attr:`~PIL.Image.Image.info` values.\n\n**transparency**\n    Transparency color index.\n\n**duration**\n    The display duration of each frame of the multiframe gif, in\n    milliseconds. Pass a single integer for a constant duration, or a\n    list or tuple to set the duration for each frame separately.\n\n**loop**\n    Integer number of times the GIF should loop. 0 means that it will loop\n    forever. By default, the image will not loop.\n\n**comment**\n    A comment about the image.\n\nReading local images\n~~~~~~~~~~~~~~~~~~~~\n\nThe GIF loader creates an image memory the same size as the GIF file’s *logical\nscreen size*, and pastes the actual pixel data (the *local image*) into this\nimage. If you only want the actual pixel rectangle, you can manipulate the\n:py:attr:`~PIL.Image.Image.size` and :py:attr:`~PIL.Image.Image.tile`\nattributes before loading the file::\n\n    im = Image.open(...)\n\n    if im.tile[0][0] == \"gif\":\n        # only read the first \"local image\" from this GIF file\n        tag, (x0, y0, x1, y1), offset, extra = im.tile[0]\n        im.size = (x1 - x0, y1 - y0)\n        im.tile = [(tag, (0, 0) + im.size, offset, extra)]\n\nICNS\n^^^^\n\nPillow reads and (macOS only) writes macOS ``.icns`` files.  By default, the\nlargest available icon is read, though you can override this by setting the\n:py:attr:`~PIL.Image.Image.size` property before calling\n:py:meth:`~PIL.Image.Image.load`.  The :py:meth:`~PIL.Image.Image.open` method\nsets the following :py:attr:`~PIL.Image.Image.info` property:\n\n**sizes**\n    A list of supported sizes found in this icon file; these are a\n    3-tuple, ``(width, height, scale)``, where ``scale`` is 2 for a retina\n    icon and 1 for a standard icon.  You *are* permitted to use this 3-tuple\n    format for the :py:attr:`~PIL.Image.Image.size` property if you set it\n    before calling :py:meth:`~PIL.Image.Image.load`; after loading, the size\n    will be reset to a 2-tuple containing pixel dimensions (so, e.g. if you\n    ask for ``(512, 512, 2)``, the final value of\n    :py:attr:`~PIL.Image.Image.size` will be ``(1024, 1024)``).\n\nThe :py:meth:`~PIL.Image.Image.save` method can take the following keyword arguments:\n\n**append_images**\n    A list of images to replace the scaled down versions of the image.\n    The order of the images does not matter, as their use is determined by\n    the size of each image.\n\n    .. versionadded:: 5.1.0\n\nICO\n^^^\n\nICO is used to store icons on Windows. The largest available icon is read.\n\nThe :py:meth:`~PIL.Image.Image.save` method supports the following options:\n\n**sizes**\n    A list of sizes including in this ico file; these are a 2-tuple,\n    ``(width, height)``; Default to ``[(16, 16), (24, 24), (32, 32), (48, 48),\n    (64, 64), (128, 128), (256, 256)]``. Any sizes bigger than the original\n    size or 256 will be ignored.\n\nIM\n^^\n\nIM is a format used by LabEye and other applications based on the IFUNC image\nprocessing library. The library reads and writes most uncompressed interchange\nversions of this format.\n\nIM is the only format that can store all internal Pillow formats.\n\nJPEG\n^^^^\n\nPillow reads JPEG, JFIF, and Adobe JPEG files containing ``L``, ``RGB``, or\n``CMYK`` data. It writes standard and progressive JFIF files.\n\nUsing the :py:meth:`~PIL.Image.Image.draft` method, you can speed things up by\nconverting ``RGB`` images to ``L``, and resize images to 1/2, 1/4 or 1/8 of\ntheir original size while loading them.\n\nThe :py:meth:`~PIL.Image.Image.open` method may set the following\n:py:attr:`~PIL.Image.Image.info` properties if available:\n\n**jfif**\n    JFIF application marker found. If the file is not a JFIF file, this key is\n    not present.\n\n**jfif_version**\n    A tuple representing the jfif version, (major version, minor version).\n\n**jfif_density**\n    A tuple representing the pixel density of the image, in units specified\n    by jfif_unit.\n\n**jfif_unit**\n    Units for the jfif_density:\n\n    * 0 - No Units\n    * 1 - Pixels per Inch\n    * 2 - Pixels per Centimeter\n\n**dpi**\n    A tuple representing the reported pixel density in pixels per inch, if\n    the file is a jfif file and the units are in inches.\n\n**adobe**\n    Adobe application marker found. If the file is not an Adobe JPEG file, this\n    key is not present.\n\n**adobe_transform**\n    Vendor Specific Tag.\n\n**progression**\n    Indicates that this is a progressive JPEG file.\n\n**icc_profile**\n    The ICC color profile for the image.\n\n**exif**\n    Raw EXIF data from the image.\n\n\nThe :py:meth:`~PIL.Image.Image.save` method supports the following options:\n\n**quality**\n    The image quality, on a scale from 1 (worst) to 95 (best). The default is\n    75. Values above 95 should be avoided; 100 disables portions of the JPEG\n    compression algorithm, and results in large files with hardly any gain in\n    image quality.\n\n**optimize**\n    If present and true, indicates that the encoder should make an extra pass\n    over the image in order to select optimal encoder settings.\n\n**progressive**\n    If present and true, indicates that this image should be stored as a\n    progressive JPEG file.\n\n**dpi**\n    A tuple of integers representing the pixel density, ``(x,y)``.\n\n**icc_profile**\n    If present and true, the image is stored with the provided ICC profile.\n    If this parameter is not provided, the image will be saved with no profile\n    attached. To preserve the existing profile::\n\n        im.save(filename, 'jpeg', icc_profile=im.info.get('icc_profile'))\n\n**exif**\n    If present, the image will be stored with the provided raw EXIF data.\n\n**subsampling**\n    If present, sets the subsampling for the encoder.\n\n    * ``keep``: Only valid for JPEG files, will retain the original image setting.\n    * ``4:4:4``, ``4:2:2``, ``4:2:0``: Specific sampling values\n    * ``-1``: equivalent to ``keep``\n    * ``0``: equivalent to ``4:4:4``\n    * ``1``: equivalent to ``4:2:2``\n    * ``2``: equivalent to ``4:2:0``\n\n**qtables**\n    If present, sets the qtables for the encoder. This is listed as an\n    advanced option for wizards in the JPEG documentation. Use with\n    caution. ``qtables`` can be one of several types of values:\n\n    *  a string, naming a preset, e.g. ``keep``, ``web_low``, or ``web_high``\n    *  a list, tuple, or dictionary (with integer keys =\n       range(len(keys))) of lists of 64 integers. There must be\n       between 2 and 4 tables.\n\n    .. versionadded:: 2.5.0\n\n\n.. note::\n\n    To enable JPEG support, you need to build and install the IJG JPEG library\n    before building the Python Imaging Library. See the distribution README for\n    details.\n\nJPEG 2000\n^^^^^^^^^\n\n.. versionadded:: 2.4.0\n\nPillow reads and writes JPEG 2000 files containing ``L``, ``LA``, ``RGB`` or\n``RGBA`` data.  It can also read files containing ``YCbCr`` data, which it\nconverts on read into ``RGB`` or ``RGBA`` depending on whether or not there is\nan alpha channel.  Pillow supports JPEG 2000 raw codestreams (``.j2k`` files),\nas well as boxed JPEG 2000 files (``.j2p`` or ``.jpx`` files).  Pillow does\n*not* support files whose components have different sampling frequencies.\n\nWhen loading, if you set the ``mode`` on the image prior to the\n:py:meth:`~PIL.Image.Image.load` method being invoked, you can ask Pillow to\nconvert the image to either ``RGB`` or ``RGBA`` rather than choosing for\nitself.  It is also possible to set ``reduce`` to the number of resolutions to\ndiscard (each one reduces the size of the resulting image by a factor of 2),\nand ``layers`` to specify the number of quality layers to load.\n\nThe :py:meth:`~PIL.Image.Image.save` method supports the following options:\n\n**offset**\n    The image offset, as a tuple of integers, e.g. (16, 16)\n\n**tile_offset**\n    The tile offset, again as a 2-tuple of integers.\n\n**tile_size**\n    The tile size as a 2-tuple.  If not specified, or if set to None, the\n    image will be saved without tiling.\n\n**quality_mode**\n    Either ``\"rates\"`` or ``\"dB\"`` depending on the units you want to use to\n    specify image quality.\n\n**quality_layers**\n    A sequence of numbers, each of which represents either an approximate size\n    reduction (if quality mode is ``\"rates\"``) or a signal to noise ratio value\n    in decibels.  If not specified, defaults to a single layer of full quality.\n\n**num_resolutions**\n    The number of different image resolutions to be stored (which corresponds\n    to the number of Discrete Wavelet Transform decompositions plus one).\n\n**codeblock_size**\n    The code-block size as a 2-tuple.  Minimum size is 4 x 4, maximum is 1024 x\n    1024, with the additional restriction that no code-block may have more\n    than 4096 coefficients (i.e. the product of the two numbers must be no\n    greater than 4096).\n\n**precinct_size**\n    The precinct size as a 2-tuple.  Must be a power of two along both axes,\n    and must be greater than the code-block size.\n\n**irreversible**\n    If ``True``, use the lossy Irreversible Color Transformation\n    followed by DWT 9-7.  Defaults to ``False``, which means to use the\n    Reversible Color Transformation with DWT 5-3.\n\n**progression**\n    Controls the progression order; must be one of ``\"LRCP\"``, ``\"RLCP\"``,\n    ``\"RPCL\"``, ``\"PCRL\"``, ``\"CPRL\"``.  The letters stand for Component,\n    Position, Resolution and Layer respectively and control the order of\n    encoding, the idea being that e.g. an image encoded using LRCP mode can\n    have its quality layers decoded as they arrive at the decoder, while one\n    encoded using RLCP mode will have increasing resolutions decoded as they\n    arrive, and so on.\n\n**cinema_mode**\n    Set the encoder to produce output compliant with the digital cinema\n    specifications.  The options here are ``\"no\"`` (the default),\n    ``\"cinema2k-24\"`` for 24fps 2K, ``\"cinema2k-48\"`` for 48fps 2K, and\n    ``\"cinema4k-24\"`` for 24fps 4K.  Note that for compliant 2K files,\n    *at least one* of your image dimensions must match 2048 x 1080, while\n    for compliant 4K files, *at least one* of the dimensions must match\n    4096 x 2160.\n\n.. note::\n\n   To enable JPEG 2000 support, you need to build and install the OpenJPEG\n   library, version 2.0.0 or higher, before building the Python Imaging\n   Library.\n\n   Windows users can install the OpenJPEG binaries available on the\n   OpenJPEG website, but must add them to their PATH in order to use Pillow (if\n   you fail to do this, you will get errors about not being able to load the\n   ``_imaging`` DLL).\n\nMSP\n^^^\n\nPillow identifies and reads MSP files from Windows 1 and 2. The library writes\nuncompressed (Windows 1) versions of this format.\n\nPCX\n^^^\n\nPillow reads and writes PCX files containing ``1``, ``L``, ``P``, or ``RGB`` data.\n\nPNG\n^^^\n\nPillow identifies, reads, and writes PNG files containing ``1``, ``L``, ``LA``,\n``I``, ``P``, ``RGB`` or ``RGBA`` data. Interlaced files are supported as of\nv1.1.7.\n\nAs of Pillow 6.0, EXIF data can be read from PNG images. However, unlike other\nimage formats, EXIF data is not guaranteed to be present in\n:py:attr:`~PIL.Image.Image.info` until :py:meth:`~PIL.Image.Image.load` has been\ncalled.\n\nThe :py:meth:`~PIL.Image.Image.open` method sets the following\n:py:attr:`~PIL.Image.Image.info` properties, when appropriate:\n\n**chromaticity**\n    The chromaticity points, as an 8 tuple of floats. (``White Point\n    X``, ``White Point Y``, ``Red X``, ``Red Y``, ``Green X``, ``Green\n    Y``, ``Blue X``, ``Blue Y``)\n\n**gamma**\n    Gamma, given as a floating point number.\n\n**srgb**\n    The sRGB rendering intent as an integer.\n\n      * 0 Perceptual\n      * 1 Relative Colorimetric\n      * 2 Saturation\n      * 3 Absolute Colorimetric\n\n**transparency**\n    For ``P`` images: Either the palette index for full transparent pixels,\n    or a byte string with alpha values for each palette entry.\n\n    For ``1``, ``L``, ``I`` and ``RGB`` images, the color that represents\n    full transparent pixels in this image.\n\n    This key is omitted if the image is not a transparent palette image.\n\n``open`` also sets ``Image.text`` to a dictionary of the values of the\n``tEXt``, ``zTXt``, and ``iTXt`` chunks of the PNG image. Individual\ncompressed chunks are limited to a decompressed size of\n``PngImagePlugin.MAX_TEXT_CHUNK``, by default 1MB, to prevent\ndecompression bombs. Additionally, the total size of all of the text\nchunks is limited to ``PngImagePlugin.MAX_TEXT_MEMORY``, defaulting to\n64MB.\n\nThe :py:meth:`~PIL.Image.Image.save` method supports the following options:\n\n**optimize**\n    If present and true, instructs the PNG writer to make the output file as\n    small as possible. This includes extra processing in order to find optimal\n    encoder settings.\n\n**transparency**\n    For ``P``, ``1``, ``L``, ``I``, and ``RGB`` images, this option controls\n    what color from the image to mark as transparent.\n\n    For ``P`` images, this can be a either the palette index,\n    or a byte string with alpha values for each palette entry.\n\n**dpi**\n    A tuple of two numbers corresponding to the desired dpi in each direction.\n\n**pnginfo**\n    A :py:class:`PIL.PngImagePlugin.PngInfo` instance containing text tags.\n\n**compress_level**\n    ZLIB compression level, a number between 0 and 9: 1 gives best speed,\n    9 gives best compression, 0 gives no compression at all. Default is 6.\n    When ``optimize`` option is True ``compress_level`` has no effect\n    (it is set to 9 regardless of a value passed).\n\n**icc_profile**\n    The ICC Profile to include in the saved file.\n\n**exif**\n    The exif data to include in the saved file.\n\n    .. versionadded:: 6.0.0\n\n**bits (experimental)**\n    For ``P`` images, this option controls how many bits to store. If omitted,\n    the PNG writer uses 8 bits (256 colors).\n\n**dictionary (experimental)**\n    Set the ZLIB encoder dictionary.\n\n.. note::\n\n    To enable PNG support, you need to build and install the ZLIB compression\n    library before building the Python Imaging Library. See the `installation\n    documentation <../installation.html>`_ for details.\n\n.. _apng-sequences:\n\nAPNG sequences\n~~~~~~~~~~~~~~\n\nThe PNG loader includes limited support for reading and writing Animated Portable\nNetwork Graphics (APNG) files.\nWhen an APNG file is loaded, :py:meth:`~PIL.ImageFile.ImageFile.get_format_mimetype`\nwill return ``\"image/apng\"``. The value of the :py:attr:`~PIL.Image.Image.is_animated`\nproperty will be ``True`` when the :py:attr:`~PIL.Image.Image.n_frames` property is\ngreater than 1. For APNG files, the ``n_frames`` property depends on both the animation\nframe count as well as the presence or absence of a default image. See the\n``default_image`` property documentation below for more details.\nThe :py:meth:`~PIL.Image.Image.seek` and :py:meth:`~PIL.Image.Image.tell` methods\nare supported.\n\n``im.seek()`` raises an :py:exc:`EOFError` if you try to seek after the last frame.\n\nThese :py:attr:`~PIL.Image.Image.info` properties will be set for APNG frames,\nwhere applicable:\n\n**default_image**\n    Specifies whether or not this APNG file contains a separate default image,\n    which is not a part of the actual APNG animation.\n\n    When an APNG file contains a default image, the initially loaded image (i.e.\n    the result of ``seek(0)``) will be the default image.\n    To account for the presence of the default image, the\n    :py:attr:`~PIL.Image.Image.n_frames` property will be set to ``frame_count + 1``,\n    where ``frame_count`` is the actual APNG animation frame count.\n    To load the first APNG animation frame, ``seek(1)`` must be called.\n\n    * ``True`` - The APNG contains default image, which is not an animation frame.\n    * ``False`` - The APNG does not contain a default image. The ``n_frames`` property\n      will be set to the actual APNG animation frame count.\n      The initially loaded image (i.e. ``seek(0)``) will be the first APNG animation\n      frame.\n\n**loop**\n    The number of times to loop this APNG, 0 indicates infinite looping.\n\n**duration**\n    The time to display this APNG frame (in milliseconds).\n\n.. note::\n\n    The APNG loader returns images the same size as the APNG file's logical screen size.\n    The returned image contains the pixel data for a given frame, after applying\n    any APNG frame disposal and frame blend operations (i.e. it contains what a web\n    browser would render for this frame - the composite of all previous frames and this\n    frame).\n\n    Any APNG file containing sequence errors is treated as an invalid image. The APNG\n    loader will not attempt to repair and reorder files containing sequence errors.\n\nSaving\n~~~~~~\n\nWhen calling :py:meth:`~PIL.Image.Image.save`, by default only a single frame PNG file\nwill be saved. To save an APNG file (including a single frame APNG), the ``save_all``\nparameter must be set to ``True``. The following parameters can also be set:\n\n**default_image**\n    Boolean value, specifying whether or not the base image is a default image.\n    If ``True``, the base image will be used as the default image, and the first image\n    from the ``append_images`` sequence will be the first APNG animation frame.\n    If ``False``, the base image will be used as the first APNG animation frame.\n    Defaults to ``False``.\n\n**append_images**\n    A list or tuple of images to append as additional frames. Each of the\n    images in the list can be single or multiframe images. The size of each frame\n    should match the size of the base image. Also note that if a frame's mode does\n    not match that of the base image, the frame will be converted to the base image\n    mode.\n\n**loop**\n    Integer number of times to loop this APNG, 0 indicates infinite looping.\n    Defaults to 0.\n\n**duration**\n    Integer (or list or tuple of integers) length of time to display this APNG frame\n    (in milliseconds).\n    Defaults to 0.\n\n**disposal**\n    An integer (or list or tuple of integers) specifying the APNG disposal\n    operation to be used for this frame before rendering the next frame.\n    Defaults to 0.\n\n    * 0 (:py:data:`~PIL.PngImagePlugin.APNG_DISPOSE_OP_NONE`, default) -\n      No disposal is done on this frame before rendering the next frame.\n    * 1 (:py:data:`PIL.PngImagePlugin.APNG_DISPOSE_OP_BACKGROUND`) -\n      This frame's modified region is cleared to fully transparent black before\n      rendering the next frame.\n    * 2 (:py:data:`~PIL.PngImagePlugin.APNG_DISPOSE_OP_PREVIOUS`) -\n      This frame's modified region is reverted to the previous frame's contents before\n      rendering the next frame.\n\n**blend**\n    An integer (or list or tuple of integers) specifying the APNG blend\n    operation to be used for this frame before rendering the next frame.\n    Defaults to 0.\n\n    * 0 (:py:data:`~PIL.PngImagePlugin.APNG_BLEND_OP_SOURCE`) -\n      All color components of this frame, including alpha, overwrite the previous output\n      image contents.\n    * 1 (:py:data:`~PIL.PngImagePlugin.APNG_BLEND_OP_OVER`) -\n      This frame should be alpha composited with the previous output image contents.\n\n.. note::\n\n    The ``duration``, ``disposal`` and ``blend`` parameters can be set to lists or tuples to\n    specify values for each individual frame in the animation. The length of the list or tuple\n    must be identical to the total number of actual frames in the APNG animation.\n    If the APNG contains a default image (i.e. ``default_image`` is set to ``True``),\n    these list or tuple parameters should not include an entry for the default image.\n\n\nPPM\n^^^\n\nPillow reads and writes PBM, PGM, PPM and PNM files containing ``1``, ``L`` or\n``RGB`` data.\n\nSGI\n^^^\n\nPillow reads and writes uncompressed ``L``, ``RGB``, and ``RGBA`` files.\n\n\nSPIDER\n^^^^^^\n\nPillow reads and writes SPIDER image files of 32-bit floating point data\n(\"F;32F\").\n\nPillow also reads SPIDER stack files containing sequences of SPIDER images. The\n:py:meth:`~PIL.Image.Image.seek` and :py:meth:`~PIL.Image.Image.tell` methods are supported, and\nrandom access is allowed.\n\nThe :py:meth:`~PIL.Image.Image.open` method sets the following attributes:\n\n**format**\n    Set to ``SPIDER``\n\n**istack**\n    Set to 1 if the file is an image stack, else 0.\n\n**n_frames**\n    Set to the number of images in the stack.\n\nA convenience method, :py:meth:`~PIL.Image.Image.convert2byte`, is provided for\nconverting floating point data to byte data (mode ``L``)::\n\n    im = Image.open('image001.spi').convert2byte()\n\nWriting files in SPIDER format\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThe extension of SPIDER files may be any 3 alphanumeric characters. Therefore\nthe output format must be specified explicitly::\n\n    im.save('newimage.spi', format='SPIDER')\n\nFor more information about the SPIDER image processing package, see the\n`SPIDER homepage`_ at `Wadsworth Center`_.\n\n.. _SPIDER homepage: https://spider.wadsworth.org/spider_doc/spider/docs/spider.html\n.. _Wadsworth Center: https://www.wadsworth.org/\n\nTGA\n^^^\n\nPillow reads and writes TGA images containing ``L``, ``LA``, ``P``,\n``RGB``, and ``RGBA`` data. Pillow can read and write both uncompressed and\nrun-length encoded TGAs.\n\nTIFF\n^^^^\n\nPillow reads and writes TIFF files. It can read both striped and tiled\nimages, pixel and plane interleaved multi-band images. If you have\nlibtiff and its headers installed, Pillow can read and write many kinds\nof compressed TIFF files. If not, Pillow will only read and write\nuncompressed files.\n\n.. note::\n\n    Beginning in version 5.0.0, Pillow requires libtiff to read or\n    write compressed files. Prior to that release, Pillow had buggy\n    support for reading Packbits, LZW and JPEG compressed TIFFs\n    without using libtiff.\n\nThe :py:meth:`~PIL.Image.Image.open` method sets the following\n:py:attr:`~PIL.Image.Image.info` properties:\n\n**compression**\n    Compression mode.\n\n    .. versionadded:: 2.0.0\n\n**dpi**\n    Image resolution as an ``(xdpi, ydpi)`` tuple, where applicable. You can use\n    the :py:attr:`~PIL.Image.Image.tag` attribute to get more detailed\n    information about the image resolution.\n\n    .. versionadded:: 1.1.5\n\n**resolution**\n    Image resolution as an ``(xres, yres)`` tuple, where applicable. This is a\n    measurement in whichever unit is specified by the file.\n\n    .. versionadded:: 1.1.5\n\n\nThe :py:attr:`~PIL.Image.Image.tag_v2` attribute contains a dictionary\nof TIFF metadata. The keys are numerical indexes from\n:py:attr:`~PIL.TiffTags.TAGS_V2`.  Values are strings or numbers for single\nitems, multiple values are returned in a tuple of values. Rational\nnumbers are returned as a :py:class:`~PIL.TiffImagePlugin.IFDRational`\nobject.\n\n    .. versionadded:: 3.0.0\n\nFor compatibility with legacy code, the\n:py:attr:`~PIL.Image.Image.tag` attribute contains a dictionary of\ndecoded TIFF fields as returned prior to version 3.0.0.  Values are\nreturned as either strings or tuples of numeric values. Rational\nnumbers are returned as a tuple of ``(numerator, denominator)``.\n\n    .. deprecated:: 3.0.0\n\nReading Multi-frame TIFF Images\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThe TIFF loader supports the :py:meth:`~PIL.Image.Image.seek` and\n:py:meth:`~PIL.Image.Image.tell` methods, taking and returning frame numbers\nwithin the image file. You can combine these methods to seek to the next frame\n(``im.seek(im.tell() + 1)``). Frames are numbered from 0 to ``im.num_frames - 1``,\nand can be accessed in any order.\n\n``im.seek()`` raises an :py:exc:`EOFError` if you try to seek after the\nlast frame.\n\nSaving Tiff Images\n~~~~~~~~~~~~~~~~~~\n\nThe :py:meth:`~PIL.Image.Image.save` method can take the following keyword arguments:\n\n**save_all**\n    If true, Pillow will save all frames of the image to a multiframe tiff document.\n\n    .. versionadded:: 3.4.0\n\n**append_images**\n    A list of images to append as additional frames. Each of the\n    images in the list can be single or multiframe images. Note however, that for\n    correct results, all the appended images should have the same\n    ``encoderinfo`` and ``encoderconfig`` properties.\n\n    .. versionadded:: 4.2.0\n\n**tiffinfo**\n    A :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2` object or dict\n    object containing tiff tags and values. The TIFF field type is\n    autodetected for Numeric and string values, any other types\n    require using an :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`\n    object and setting the type in\n    :py:attr:`~PIL.TiffImagePlugin.ImageFileDirectory_v2.tagtype` with\n    the appropriate numerical value from\n    ``TiffTags.TYPES``.\n\n    .. versionadded:: 2.3.0\n\n    Metadata values that are of the rational type should be passed in\n    using a :py:class:`~PIL.TiffImagePlugin.IFDRational` object.\n\n    .. versionadded:: 3.1.0\n\n    For compatibility with legacy code, a\n    :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1` object may\n    be passed in this field. However, this is deprecated.\n\n    .. versionadded:: 5.4.0\n\n    Previous versions only supported some tags when writing using\n    libtiff. The supported list is found in\n    :py:attr:`~PIL:TiffTags.LIBTIFF_CORE`.\n\n    .. versionadded:: 6.1.0\n\n    Added support for signed types (e.g. ``TIFF_SIGNED_LONG``) and multiple values.\n    Multiple values for a single tag must be to\n    :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2` as a tuple and\n    require a matching type in\n    :py:attr:`~PIL.TiffImagePlugin.ImageFileDirectory_v2.tagtype` tagtype.\n\n**compression**\n    A string containing the desired compression method for the\n    file. (valid only with libtiff installed) Valid compression\n    methods are: ``None``, ``\"tiff_ccitt\"``, ``\"group3\"``,\n    ``\"group4\"``, ``\"tiff_jpeg\"``, ``\"tiff_adobe_deflate\"``,\n    ``\"tiff_thunderscan\"``, ``\"tiff_deflate\"``, ``\"tiff_sgilog\"``,\n    ``\"tiff_sgilog24\"``, ``\"tiff_raw_16\"``\n\n**quality**\n    The image quality for JPEG compression, on a scale from 0 (worst) to 100\n    (best). The default is 75.\n\n    .. versionadded:: 6.1.0\n\nThese arguments to set the tiff header fields are an alternative to\nusing the general tags available through tiffinfo.\n\n**description**\n\n**software**\n\n**date_time**\n\n**artist**\n\n**copyright**\n    Strings\n\n**resolution_unit**\n    An integer. 1 for no unit, 2 for inches and 3 for centimeters.\n\n**resolution**\n    Either an integer or a float, used for both the x and y resolution.\n\n**x_resolution**\n    Either an integer or a float.\n\n**y_resolution**\n    Either an integer or a float.\n\n**dpi**\n    A tuple of (x_resolution, y_resolution), with inches as the resolution\n    unit. For consistency with other image formats, the x and y resolutions\n    of the dpi will be rounded to the nearest integer.\n\n\nWebP\n^^^^\n\nPillow reads and writes WebP files. The specifics of Pillow's capabilities with\nthis format are currently undocumented.\n\nThe :py:meth:`~PIL.Image.Image.save` method supports the following options:\n\n**lossless**\n    If present and true, instructs the WebP writer to use lossless compression.\n\n**quality**\n    Integer, 1-100, Defaults to 80. For lossy, 0 gives the smallest\n    size and 100 the largest. For lossless, this parameter is the amount\n    of effort put into the compression: 0 is the fastest, but gives larger\n    files compared to the slowest, but best, 100.\n\n**method**\n    Quality/speed trade-off (0=fast, 6=slower-better). Defaults to 0.\n\n**icc_profile**\n    The ICC Profile to include in the saved file. Only supported if\n    the system WebP library was built with webpmux support.\n\n**exif**\n    The exif data to include in the saved file. Only supported if\n    the system WebP library was built with webpmux support.\n\nSaving sequences\n~~~~~~~~~~~~~~~~~\n\n.. note::\n\n    Support for animated WebP files will only be enabled if the system WebP\n    library is v0.5.0 or later. You can check webp animation support at\n    runtime by calling ``features.check(\"webp_anim\")``.\n\nWhen calling :py:meth:`~PIL.Image.Image.save` to write a WebP file, the\nfollowing options are available when the ``save_all`` argument is present and\ntrue.\n\n**append_images**\n    A list of images to append as additional frames. Each of the\n    images in the list can be single or multiframe images.\n\n**duration**\n    The display duration of each frame, in milliseconds. Pass a single\n    integer for a constant duration, or a list or tuple to set the\n    duration for each frame separately.\n\n**loop**\n    Number of times to repeat the animation. Defaults to [0 = infinite].\n\n**background**\n    Background color of the canvas, as an RGBA tuple with values in\n    the range of (0-255).\n\n**minimize_size**\n    If true, minimize the output size (slow). Implicitly disables\n    key-frame insertion.\n\n**kmin, kmax**\n    Minimum and maximum distance between consecutive key frames in\n    the output. The library may insert some key frames as needed\n    to satisfy this criteria. Note that these conditions should\n    hold: kmax > kmin and kmin >= kmax / 2 + 1. Also, if kmax <= 0,\n    then key-frame insertion is disabled; and if kmax == 1, then all\n    frames will be key-frames (kmin value does not matter for these\n    special cases).\n\n**allow_mixed**\n    If true, use mixed compression mode; the encoder heuristically\n    chooses between lossy and lossless for each frame.\n\nXBM\n^^^\n\nPillow reads and writes X bitmap files (mode ``1``).\n\nRead-only formats\n-----------------\n\nBLP\n^^^\n\nBLP is the Blizzard Mipmap Format, a texture format used in World of\nWarcraft. Pillow supports reading ``JPEG`` Compressed or raw ``BLP1``\nimages, and all types of ``BLP2`` images.\n\nCUR\n^^^\n\nCUR is used to store cursors on Windows. The CUR decoder reads the largest\navailable cursor. Animated cursors are not supported.\n\nDCX\n^^^\n\nDCX is a container file format for PCX files, defined by Intel. The DCX format\nis commonly used in fax applications. The DCX decoder can read files containing\n``1``, ``L``, ``P``, or ``RGB`` data.\n\nWhen the file is opened, only the first image is read. You can use\n:py:meth:`~PIL.Image.Image.seek` or :py:mod:`~PIL.ImageSequence` to read other images.\n\n\nDDS\n^^^\n\nDDS is a popular container texture format used in video games and natively\nsupported by DirectX.\nCurrently, uncompressed RGB data and DXT1, DXT3, and DXT5 pixel formats are\nsupported, and only in ``RGBA`` mode.\n\n.. versionadded:: 3.4.0 DXT3\n\nFLI, FLC\n^^^^^^^^\n\nPillow reads Autodesk FLI and FLC animations.\n\nThe :py:meth:`~PIL.Image.Image.open` method sets the following\n:py:attr:`~PIL.Image.Image.info` properties:\n\n**duration**\n    The delay (in milliseconds) between each frame.\n\nFPX\n^^^\n\nPillow reads Kodak FlashPix files. In the current version, only the highest\nresolution image is read from the file, and the viewing transform is not taken\ninto account.\n\n.. note::\n\n    To enable full FlashPix support, you need to build and install the IJG JPEG\n    library before building the Python Imaging Library. See the distribution\n    README for details.\n\nFTEX\n^^^^\n\n.. versionadded:: 3.2.0\n\nThe FTEX decoder reads textures used for 3D objects in\nIndependence War 2: Edge Of Chaos. The plugin reads a single texture\nper file, in the compressed and uncompressed formats.\n\nGBR\n^^^\n\nThe GBR decoder reads GIMP brush files, version 1 and 2.\n\nThe :py:meth:`~PIL.Image.Image.open` method sets the following\n:py:attr:`~PIL.Image.Image.info` properties:\n\n**comment**\n    The brush name.\n\n**spacing**\n    The spacing between the brushes, in pixels. Version 2 only.\n\nGD\n^^\n\nPillow reads uncompressed GD2 files. Note that you must use\n:py:func:`PIL.GdImageFile.open` to read such a file.\n\nThe :py:meth:`~PIL.Image.Image.open` method sets the following\n:py:attr:`~PIL.Image.Image.info` properties:\n\n**transparency**\n    Transparency color index. This key is omitted if the image is not\n    transparent.\n\nIMT\n^^^\n\nPillow reads Image Tools images containing ``L`` data.\n\nIPTC/NAA\n^^^^^^^^\n\nPillow provides limited read support for IPTC/NAA newsphoto files.\n\nMCIDAS\n^^^^^^\n\nPillow identifies and reads 8-bit McIdas area files.\n\nMIC\n^^^\n\nPillow identifies and reads Microsoft Image Composer (MIC) files. When opened,\nthe first sprite in the file is loaded. You can use :py:meth:`~PIL.Image.Image.seek` and\n:py:meth:`~PIL.Image.Image.tell` to read other sprites from the file.\n\nNote that there may be an embedded gamma of 2.2 in MIC files.\n\nMPO\n^^^\n\nPillow identifies and reads Multi Picture Object (MPO) files, loading the primary\nimage when first opened. The :py:meth:`~PIL.Image.Image.seek` and :py:meth:`~PIL.Image.Image.tell`\nmethods may be used to read other pictures from the file. The pictures are\nzero-indexed and random access is supported.\n\nPCD\n^^^\n\nPillow reads PhotoCD files containing ``RGB`` data. This only reads the 768x512\nresolution image from the file. Higher resolutions are encoded in a proprietary\nencoding.\n\nPIXAR\n^^^^^\n\nPillow provides limited support for PIXAR raster files. The library can\nidentify and read “dumped” RGB files.\n\nThe format code is ``PIXAR``.\n\nPSD\n^^^\n\nPillow identifies and reads PSD files written by Adobe Photoshop 2.5 and 3.0.\n\n\nWAL\n^^^\n\n.. versionadded:: 1.1.4\n\nPillow reads Quake2 WAL texture files.\n\nNote that this file format cannot be automatically identified, so you must use\nthe open function in the :py:mod:`~PIL.WalImageFile` module to read files in\nthis format.\n\nBy default, a Quake2 standard palette is attached to the texture. To override\nthe palette, use the putpalette method.\n\nWMF\n^^^\n\nPillow can identify WMF files.\n\nOn Windows, it can read WMF files. By default, it will load the image at 72\ndpi. To load it at another resolution:\n\n.. code-block:: python\n\n    from PIL import Image\n    with Image.open(\"drawing.wmf\") as im:\n        im.load(dpi=144)\n\nTo add other read or write support, use\n:py:func:`PIL.WmfImagePlugin.register_handler` to register a WMF handler.\n\n.. code-block:: python\n\n    from PIL import Image\n    from PIL import WmfImagePlugin\n\n    class WmfHandler:\n        def open(self, im):\n            ...\n        def load(self, im):\n            ...\n            return image\n        def save(self, im, fp, filename):\n            ...\n\n    wmf_handler = WmfHandler()\n\n    WmfImagePlugin.register_handler(wmf_handler)\n\n    im = Image.open(\"sample.wmf\")\n\nXPM\n^^^\n\nPillow reads X pixmap files (mode ``P``) with 256 colors or less.\n\nThe :py:meth:`~PIL.Image.Image.open` method sets the following\n:py:attr:`~PIL.Image.Image.info` properties:\n\n**transparency**\n    Transparency color index. This key is omitted if the image is not\n    transparent.\n\nWrite-only formats\n------------------\n\nPALM\n^^^^\n\nPillow provides write-only support for PALM pixmap files.\n\nThe format code is ``Palm``, the extension is ``.palm``.\n\nPDF\n^^^\n\nPillow can write PDF (Acrobat) images. Such images are written as binary PDF 1.4\nfiles, using either JPEG or HEX encoding depending on the image mode (and\nwhether JPEG support is available or not).\n\nThe :py:meth:`~PIL.Image.Image.save` method can take the following keyword arguments:\n\n**save_all**\n    If a multiframe image is used, by default, only the first image will be saved.\n    To save all frames, each frame to a separate page of the PDF, the ``save_all``\n    parameter must be present and set to ``True``.\n\n    .. versionadded:: 3.0.0\n\n**append_images**\n    A list of images to append as additional pages. Each of the\n    images in the list can be single or multiframe images.\n\n    .. versionadded:: 4.2.0\n\n**append**\n    Set to True to append pages to an existing PDF file. If the file doesn't\n    exist, an :py:exc:`IOError` will be raised.\n\n    .. versionadded:: 5.1.0\n\n**resolution**\n    Image resolution in DPI. This, together with the number of pixels in the\n    image, will determine the physical dimensions of the page that will be\n    saved in the PDF.\n\n**title**\n    The document’s title. If not appending to an existing PDF file, this will\n    default to the filename.\n\n    .. versionadded:: 5.1.0\n\n**author**\n    The name of the person who created the document.\n\n    .. versionadded:: 5.1.0\n\n**subject**\n    The subject of the document.\n\n    .. versionadded:: 5.1.0\n\n**keywords**\n    Keywords associated with the document.\n\n    .. versionadded:: 5.1.0\n\n**creator**\n    If the document was converted to PDF from another format, the name of the\n    conforming product that created the original document from which it was\n    converted.\n\n    .. versionadded:: 5.1.0\n\n**producer**\n    If the document was converted to PDF from another format, the name of the\n    conforming product that converted it to PDF.\n\n    .. versionadded:: 5.1.0\n\n**creationDate**\n    The creation date of the document. If not appending to an existing PDF\n    file, this will default to the current time.\n\n    .. versionadded:: 5.3.0\n\n**modDate**\n    The modification date of the document. If not appending to an existing PDF\n    file, this will default to the current time.\n\n    .. versionadded:: 5.3.0\n\nXV Thumbnails\n^^^^^^^^^^^^^\n\nPillow can read XV thumbnail files.\n\nIdentify-only formats\n---------------------\n\nBUFR\n^^^^\n\n.. versionadded:: 1.1.3\n\nPillow provides a stub driver for BUFR files.\n\nTo add read or write support to your application, use\n:py:func:`PIL.BufrStubImagePlugin.register_handler`.\n\nFITS\n^^^^\n\n.. versionadded:: 1.1.5\n\nPillow provides a stub driver for FITS files.\n\nTo add read or write support to your application, use\n:py:func:`PIL.FitsStubImagePlugin.register_handler`.\n\nGRIB\n^^^^\n\n.. versionadded:: 1.1.5\n\nPillow provides a stub driver for GRIB files.\n\nThe driver requires the file to start with a GRIB header. If you have files\nwith embedded GRIB data, or files with multiple GRIB fields, your application\nhas to seek to the header before passing the file handle to Pillow.\n\nTo add read or write support to your application, use\n:py:func:`PIL.GribStubImagePlugin.register_handler`.\n\nHDF5\n^^^^\n\n.. versionadded:: 1.1.5\n\nPillow provides a stub driver for HDF5 files.\n\nTo add read or write support to your application, use\n:py:func:`PIL.Hdf5StubImagePlugin.register_handler`.\n\nMPEG\n^^^^\n\nPillow identifies MPEG files.\n",
            "header": {
                "file": {
                    "path": "docs/handbook/image-file-formats.rst"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "a6b87407d",
                "new_commit_hash": "5d882eb76",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/docs/handbook/image-file-formats.rst"
            },
            "plus_file": {
                "path": "b/docs/handbook/image-file-formats.rst"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 559,
                            "length": 8
                        },
                        "new_range": {
                            "start": 559,
                            "length": 11
                        },
                        "section": "APNG sequences"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "The PNG loader includes limited support for reading and writing Animated Portable",
                                "type": "context"
                            },
                            {
                                "content": "Network Graphics (APNG) files.",
                                "type": "context"
                            },
                            {
                                "content": "When an APNG file is loaded, :py:meth:`~PIL.ImageFile.ImageFile.get_format_mimetype`",
                                "type": "context"
                            },
                            {
                                "content": "will return ``\"image/apng\"``, and the :py:attr:`~PIL.Image.Image.is_animated` property",
                                "type": "deleted"
                            },
                            {
                                "content": "will be ``True`` (even for single frame APNG files).",
                                "type": "deleted"
                            },
                            {
                                "content": "will return ``\"image/apng\"``. The value of the :py:attr:`~PIL.Image.Image.is_animated`",
                                "type": "added"
                            },
                            {
                                "content": "property will be ``True`` when the :py:attr:`~PIL.Image.Image.n_frames` property is",
                                "type": "added"
                            },
                            {
                                "content": "greater than 1. For APNG files, the ``n_frames`` property depends on both the animation",
                                "type": "added"
                            },
                            {
                                "content": "frame count as well as the presence or absence of a default image. See the",
                                "type": "added"
                            },
                            {
                                "content": "``default_image`` property documentation below for more details.",
                                "type": "added"
                            },
                            {
                                "content": "The :py:meth:`~PIL.Image.Image.seek` and :py:meth:`~PIL.Image.Image.tell` methods",
                                "type": "context"
                            },
                            {
                                "content": "are supported.",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "#\n# The Python Imaging Library.\n# $Id$\n#\n# PNG support code\n#\n# See \"PNG (Portable Network Graphics) Specification, version 1.0;\n# W3C Recommendation\", 1996-10-01, Thomas Boutell (ed.).\n#\n# history:\n# 1996-05-06 fl   Created (couldn't resist it)\n# 1996-12-14 fl   Upgraded, added read and verify support (0.2)\n# 1996-12-15 fl   Separate PNG stream parser\n# 1996-12-29 fl   Added write support, added getchunks\n# 1996-12-30 fl   Eliminated circular references in decoder (0.3)\n# 1998-07-12 fl   Read/write 16-bit images as mode I (0.4)\n# 2001-02-08 fl   Added transparency support (from Zircon) (0.5)\n# 2001-04-16 fl   Don't close data source in \"open\" method (0.6)\n# 2004-02-24 fl   Don't even pretend to support interlaced files (0.7)\n# 2004-08-31 fl   Do basic sanity check on chunk identifiers (0.8)\n# 2004-09-20 fl   Added PngInfo chunk container\n# 2004-12-18 fl   Added DPI read support (based on code by Niki Spahiev)\n# 2008-08-13 fl   Added tRNS support for RGB images\n# 2009-03-06 fl   Support for preserving ICC profiles (by Florian Hoech)\n# 2009-03-08 fl   Added zTXT support (from Lowell Alleman)\n# 2009-03-29 fl   Read interlaced PNG files (from Conrado Porto Lopes Gouvua)\n#\n# Copyright (c) 1997-2009 by Secret Labs AB\n# Copyright (c) 1996 by Fredrik Lundh\n#\n# See the README file for information on usage and redistribution.\n#\n\nimport itertools\nimport logging\nimport re\nimport struct\nimport warnings\nimport zlib\n\nfrom . import Image, ImageChops, ImageFile, ImagePalette, ImageSequence\nfrom ._binary import i8, i16be as i16, i32be as i32, o8, o16be as o16, o32be as o32\n\nlogger = logging.getLogger(__name__)\n\nis_cid = re.compile(br\"\\w\\w\\w\\w\").match\n\n\n_MAGIC = b\"\\211PNG\\r\\n\\032\\n\"\n\n\n_MODES = {\n    # supported bits/color combinations, and corresponding modes/rawmodes\n    # Greyscale\n    (1, 0): (\"1\", \"1\"),\n    (2, 0): (\"L\", \"L;2\"),\n    (4, 0): (\"L\", \"L;4\"),\n    (8, 0): (\"L\", \"L\"),\n    (16, 0): (\"I\", \"I;16B\"),\n    # Truecolour\n    (8, 2): (\"RGB\", \"RGB\"),\n    (16, 2): (\"RGB\", \"RGB;16B\"),\n    # Indexed-colour\n    (1, 3): (\"P\", \"P;1\"),\n    (2, 3): (\"P\", \"P;2\"),\n    (4, 3): (\"P\", \"P;4\"),\n    (8, 3): (\"P\", \"P\"),\n    # Greyscale with alpha\n    (8, 4): (\"LA\", \"LA\"),\n    (16, 4): (\"RGBA\", \"LA;16B\"),  # LA;16B->LA not yet available\n    # Truecolour with alpha\n    (8, 6): (\"RGBA\", \"RGBA\"),\n    (16, 6): (\"RGBA\", \"RGBA;16B\"),\n}\n\n\n_simple_palette = re.compile(b\"^\\xff*\\x00\\xff*$\")\n\n# Maximum decompressed size for a iTXt or zTXt chunk.\n# Eliminates decompression bombs where compressed chunks can expand 1000x\nMAX_TEXT_CHUNK = ImageFile.SAFEBLOCK\n# Set the maximum total text chunk size.\nMAX_TEXT_MEMORY = 64 * MAX_TEXT_CHUNK\n\n\n# APNG frame disposal modes\nAPNG_DISPOSE_OP_NONE = 0\nAPNG_DISPOSE_OP_BACKGROUND = 1\nAPNG_DISPOSE_OP_PREVIOUS = 2\n\n# APNG frame blend modes\nAPNG_BLEND_OP_SOURCE = 0\nAPNG_BLEND_OP_OVER = 1\n\n\ndef _safe_zlib_decompress(s):\n    dobj = zlib.decompressobj()\n    plaintext = dobj.decompress(s, MAX_TEXT_CHUNK)\n    if dobj.unconsumed_tail:\n        raise ValueError(\"Decompressed Data Too Large\")\n    return plaintext\n\n\ndef _crc32(data, seed=0):\n    return zlib.crc32(data, seed) & 0xFFFFFFFF\n\n\n# --------------------------------------------------------------------\n# Support classes.  Suitable for PNG and related formats like MNG etc.\n\n\nclass ChunkStream:\n    def __init__(self, fp):\n\n        self.fp = fp\n        self.queue = []\n\n    def read(self):\n        \"\"\"Fetch a new chunk. Returns header information.\"\"\"\n        cid = None\n\n        if self.queue:\n            cid, pos, length = self.queue.pop()\n            self.fp.seek(pos)\n        else:\n            s = self.fp.read(8)\n            cid = s[4:]\n            pos = self.fp.tell()\n            length = i32(s)\n\n        if not is_cid(cid):\n            if not ImageFile.LOAD_TRUNCATED_IMAGES:\n                raise SyntaxError(\"broken PNG file (chunk %s)\" % repr(cid))\n\n        return cid, pos, length\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, *args):\n        self.close()\n\n    def close(self):\n        self.queue = self.crc = self.fp = None\n\n    def push(self, cid, pos, length):\n\n        self.queue.append((cid, pos, length))\n\n    def call(self, cid, pos, length):\n        \"\"\"Call the appropriate chunk handler\"\"\"\n\n        logger.debug(\"STREAM %r %s %s\", cid, pos, length)\n        return getattr(self, \"chunk_\" + cid.decode(\"ascii\"))(pos, length)\n\n    def crc(self, cid, data):\n        \"\"\"Read and verify checksum\"\"\"\n\n        # Skip CRC checks for ancillary chunks if allowed to load truncated\n        # images\n        # 5th byte of first char is 1 [specs, section 5.4]\n        if ImageFile.LOAD_TRUNCATED_IMAGES and (i8(cid[0]) >> 5 & 1):\n            self.crc_skip(cid, data)\n            return\n\n        try:\n            crc1 = _crc32(data, _crc32(cid))\n            crc2 = i32(self.fp.read(4))\n            if crc1 != crc2:\n                raise SyntaxError(\"broken PNG file (bad header checksum in %r)\" % cid)\n        except struct.error:\n            raise SyntaxError(\"broken PNG file (incomplete checksum in %r)\" % cid)\n\n    def crc_skip(self, cid, data):\n        \"\"\"Read checksum.  Used if the C module is not present\"\"\"\n\n        self.fp.read(4)\n\n    def verify(self, endchunk=b\"IEND\"):\n\n        # Simple approach; just calculate checksum for all remaining\n        # blocks.  Must be called directly after open.\n\n        cids = []\n\n        while True:\n            try:\n                cid, pos, length = self.read()\n            except struct.error:\n                raise OSError(\"truncated PNG file\")\n\n            if cid == endchunk:\n                break\n            self.crc(cid, ImageFile._safe_read(self.fp, length))\n            cids.append(cid)\n\n        return cids\n\n\nclass iTXt(str):\n    \"\"\"\n    Subclass of string to allow iTXt chunks to look like strings while\n    keeping their extra information\n\n    \"\"\"\n\n    @staticmethod\n    def __new__(cls, text, lang=None, tkey=None):\n        \"\"\"\n        :param cls: the class to use when creating the instance\n        :param text: value for this key\n        :param lang: language code\n        :param tkey: UTF-8 version of the key name\n        \"\"\"\n\n        self = str.__new__(cls, text)\n        self.lang = lang\n        self.tkey = tkey\n        return self\n\n\nclass PngInfo:\n    \"\"\"\n    PNG chunk container (for use with save(pnginfo=))\n\n    \"\"\"\n\n    def __init__(self):\n        self.chunks = []\n\n    def add(self, cid, data):\n        \"\"\"Appends an arbitrary chunk. Use with caution.\n\n        :param cid: a byte string, 4 bytes long.\n        :param data: a byte string of the encoded data\n\n        \"\"\"\n\n        self.chunks.append((cid, data))\n\n    def add_itxt(self, key, value, lang=\"\", tkey=\"\", zip=False):\n        \"\"\"Appends an iTXt chunk.\n\n        :param key: latin-1 encodable text key name\n        :param value: value for this key\n        :param lang: language code\n        :param tkey: UTF-8 version of the key name\n        :param zip: compression flag\n\n        \"\"\"\n\n        if not isinstance(key, bytes):\n            key = key.encode(\"latin-1\", \"strict\")\n        if not isinstance(value, bytes):\n            value = value.encode(\"utf-8\", \"strict\")\n        if not isinstance(lang, bytes):\n            lang = lang.encode(\"utf-8\", \"strict\")\n        if not isinstance(tkey, bytes):\n            tkey = tkey.encode(\"utf-8\", \"strict\")\n\n        if zip:\n            self.add(\n                b\"iTXt\",\n                key + b\"\\0\\x01\\0\" + lang + b\"\\0\" + tkey + b\"\\0\" + zlib.compress(value),\n            )\n        else:\n            self.add(b\"iTXt\", key + b\"\\0\\0\\0\" + lang + b\"\\0\" + tkey + b\"\\0\" + value)\n\n    def add_text(self, key, value, zip=False):\n        \"\"\"Appends a text chunk.\n\n        :param key: latin-1 encodable text key name\n        :param value: value for this key, text or an\n           :py:class:`PIL.PngImagePlugin.iTXt` instance\n        :param zip: compression flag\n\n        \"\"\"\n        if isinstance(value, iTXt):\n            return self.add_itxt(key, value, value.lang, value.tkey, zip=zip)\n\n        # The tEXt chunk stores latin-1 text\n        if not isinstance(value, bytes):\n            try:\n                value = value.encode(\"latin-1\", \"strict\")\n            except UnicodeError:\n                return self.add_itxt(key, value, zip=zip)\n\n        if not isinstance(key, bytes):\n            key = key.encode(\"latin-1\", \"strict\")\n\n        if zip:\n            self.add(b\"zTXt\", key + b\"\\0\\0\" + zlib.compress(value))\n        else:\n            self.add(b\"tEXt\", key + b\"\\0\" + value)\n\n\n# --------------------------------------------------------------------\n# PNG image stream (IHDR/IEND)\n\n\nclass PngStream(ChunkStream):\n    def __init__(self, fp):\n        super().__init__(fp)\n\n        # local copies of Image attributes\n        self.im_info = {}\n        self.im_text = {}\n        self.im_size = (0, 0)\n        self.im_mode = None\n        self.im_tile = None\n        self.im_palette = None\n        self.im_custom_mimetype = None\n        self.im_n_frames = None\n        self._seq_num = None\n        self.rewind_state = None\n\n        self.text_memory = 0\n\n    def check_text_memory(self, chunklen):\n        self.text_memory += chunklen\n        if self.text_memory > MAX_TEXT_MEMORY:\n            raise ValueError(\n                \"Too much memory used in text chunks: %s>MAX_TEXT_MEMORY\"\n                % self.text_memory\n            )\n\n    def save_rewind(self):\n        self.rewind_state = {\n            \"info\": self.im_info.copy(),\n            \"tile\": self.im_tile,\n            \"seq_num\": self._seq_num,\n        }\n\n    def rewind(self):\n        self.im_info = self.rewind_state[\"info\"]\n        self.im_tile = self.rewind_state[\"tile\"]\n        self._seq_num = self.rewind_state[\"seq_num\"]\n\n    def chunk_iCCP(self, pos, length):\n\n        # ICC profile\n        s = ImageFile._safe_read(self.fp, length)\n        # according to PNG spec, the iCCP chunk contains:\n        # Profile name  1-79 bytes (character string)\n        # Null separator        1 byte (null character)\n        # Compression method    1 byte (0)\n        # Compressed profile    n bytes (zlib with deflate compression)\n        i = s.find(b\"\\0\")\n        logger.debug(\"iCCP profile name %r\", s[:i])\n        logger.debug(\"Compression method %s\", i8(s[i]))\n        comp_method = i8(s[i])\n        if comp_method != 0:\n            raise SyntaxError(\n                \"Unknown compression method %s in iCCP chunk\" % comp_method\n            )\n        try:\n            icc_profile = _safe_zlib_decompress(s[i + 2 :])\n        except ValueError:\n            if ImageFile.LOAD_TRUNCATED_IMAGES:\n                icc_profile = None\n            else:\n                raise\n        except zlib.error:\n            icc_profile = None  # FIXME\n        self.im_info[\"icc_profile\"] = icc_profile\n        return s\n\n    def chunk_IHDR(self, pos, length):\n\n        # image header\n        s = ImageFile._safe_read(self.fp, length)\n        self.im_size = i32(s), i32(s[4:])\n        try:\n            self.im_mode, self.im_rawmode = _MODES[(i8(s[8]), i8(s[9]))]\n        except Exception:\n            pass\n        if i8(s[12]):\n            self.im_info[\"interlace\"] = 1\n        if i8(s[11]):\n            raise SyntaxError(\"unknown filter category\")\n        return s\n\n    def chunk_IDAT(self, pos, length):\n\n        # image data\n        if \"bbox\" in self.im_info:\n            tile = [(\"zip\", self.im_info[\"bbox\"], pos, self.im_rawmode)]\n        else:\n            if self.im_n_frames is not None:\n                self.im_info[\"default_image\"] = True\n            tile = [(\"zip\", (0, 0) + self.im_size, pos, self.im_rawmode)]\n        self.im_tile = tile\n        self.im_idat = length\n        raise EOFError\n\n    def chunk_IEND(self, pos, length):\n\n        # end of PNG image\n        raise EOFError\n\n    def chunk_PLTE(self, pos, length):\n\n        # palette\n        s = ImageFile._safe_read(self.fp, length)\n        if self.im_mode == \"P\":\n            self.im_palette = \"RGB\", s\n        return s\n\n    def chunk_tRNS(self, pos, length):\n\n        # transparency\n        s = ImageFile._safe_read(self.fp, length)\n        if self.im_mode == \"P\":\n            if _simple_palette.match(s):\n                # tRNS contains only one full-transparent entry,\n                # other entries are full opaque\n                i = s.find(b\"\\0\")\n                if i >= 0:\n                    self.im_info[\"transparency\"] = i\n            else:\n                # otherwise, we have a byte string with one alpha value\n                # for each palette entry\n                self.im_info[\"transparency\"] = s\n        elif self.im_mode in (\"1\", \"L\", \"I\"):\n            self.im_info[\"transparency\"] = i16(s)\n        elif self.im_mode == \"RGB\":\n            self.im_info[\"transparency\"] = i16(s), i16(s[2:]), i16(s[4:])\n        return s\n\n    def chunk_gAMA(self, pos, length):\n        # gamma setting\n        s = ImageFile._safe_read(self.fp, length)\n        self.im_info[\"gamma\"] = i32(s) / 100000.0\n        return s\n\n    def chunk_cHRM(self, pos, length):\n        # chromaticity, 8 unsigned ints, actual value is scaled by 100,000\n        # WP x,y, Red x,y, Green x,y Blue x,y\n\n        s = ImageFile._safe_read(self.fp, length)\n        raw_vals = struct.unpack(\">%dI\" % (len(s) // 4), s)\n        self.im_info[\"chromaticity\"] = tuple(elt / 100000.0 for elt in raw_vals)\n        return s\n\n    def chunk_sRGB(self, pos, length):\n        # srgb rendering intent, 1 byte\n        # 0 perceptual\n        # 1 relative colorimetric\n        # 2 saturation\n        # 3 absolute colorimetric\n\n        s = ImageFile._safe_read(self.fp, length)\n        self.im_info[\"srgb\"] = i8(s)\n        return s\n\n    def chunk_pHYs(self, pos, length):\n\n        # pixels per unit\n        s = ImageFile._safe_read(self.fp, length)\n        px, py = i32(s), i32(s[4:])\n        unit = i8(s[8])\n        if unit == 1:  # meter\n            dpi = int(px * 0.0254 + 0.5), int(py * 0.0254 + 0.5)\n            self.im_info[\"dpi\"] = dpi\n        elif unit == 0:\n            self.im_info[\"aspect\"] = px, py\n        return s\n\n    def chunk_tEXt(self, pos, length):\n\n        # text\n        s = ImageFile._safe_read(self.fp, length)\n        try:\n            k, v = s.split(b\"\\0\", 1)\n        except ValueError:\n            # fallback for broken tEXt tags\n            k = s\n            v = b\"\"\n        if k:\n            k = k.decode(\"latin-1\", \"strict\")\n            v = v.decode(\"latin-1\", \"replace\")\n\n            self.im_info[k] = self.im_text[k] = v\n            self.check_text_memory(len(v))\n\n        return s\n\n    def chunk_zTXt(self, pos, length):\n\n        # compressed text\n        s = ImageFile._safe_read(self.fp, length)\n        try:\n            k, v = s.split(b\"\\0\", 1)\n        except ValueError:\n            k = s\n            v = b\"\"\n        if v:\n            comp_method = i8(v[0])\n        else:\n            comp_method = 0\n        if comp_method != 0:\n            raise SyntaxError(\n                \"Unknown compression method %s in zTXt chunk\" % comp_method\n            )\n        try:\n            v = _safe_zlib_decompress(v[1:])\n        except ValueError:\n            if ImageFile.LOAD_TRUNCATED_IMAGES:\n                v = b\"\"\n            else:\n                raise\n        except zlib.error:\n            v = b\"\"\n\n        if k:\n            k = k.decode(\"latin-1\", \"strict\")\n            v = v.decode(\"latin-1\", \"replace\")\n\n            self.im_info[k] = self.im_text[k] = v\n            self.check_text_memory(len(v))\n\n        return s\n\n    def chunk_iTXt(self, pos, length):\n\n        # international text\n        r = s = ImageFile._safe_read(self.fp, length)\n        try:\n            k, r = r.split(b\"\\0\", 1)\n        except ValueError:\n            return s\n        if len(r) < 2:\n            return s\n        cf, cm, r = i8(r[0]), i8(r[1]), r[2:]\n        try:\n            lang, tk, v = r.split(b\"\\0\", 2)\n        except ValueError:\n            return s\n        if cf != 0:\n            if cm == 0:\n                try:\n                    v = _safe_zlib_decompress(v)\n                except ValueError:\n                    if ImageFile.LOAD_TRUNCATED_IMAGES:\n                        return s\n                    else:\n                        raise\n                except zlib.error:\n                    return s\n            else:\n                return s\n        try:\n            k = k.decode(\"latin-1\", \"strict\")\n            lang = lang.decode(\"utf-8\", \"strict\")\n            tk = tk.decode(\"utf-8\", \"strict\")\n            v = v.decode(\"utf-8\", \"strict\")\n        except UnicodeError:\n            return s\n\n        self.im_info[k] = self.im_text[k] = iTXt(v, lang, tk)\n        self.check_text_memory(len(v))\n\n        return s\n\n    def chunk_eXIf(self, pos, length):\n        s = ImageFile._safe_read(self.fp, length)\n        self.im_info[\"exif\"] = b\"Exif\\x00\\x00\" + s\n        return s\n\n    # APNG chunks\n    def chunk_acTL(self, pos, length):\n        s = ImageFile._safe_read(self.fp, length)\n        if self.im_n_frames is not None:\n            self.im_n_frames = None\n            warnings.warn(\"Invalid APNG, will use default PNG image if possible\")\n            return s\n        n_frames = i32(s)\n        if n_frames == 0 or n_frames > 0x80000000:\n            warnings.warn(\"Invalid APNG, will use default PNG image if possible\")\n            return s\n        self.im_n_frames = n_frames\n        self.im_info[\"loop\"] = i32(s[4:])\n        self.im_custom_mimetype = \"image/apng\"\n        return s\n\n    def chunk_fcTL(self, pos, length):\n        s = ImageFile._safe_read(self.fp, length)\n        seq = i32(s)\n        if (self._seq_num is None and seq != 0) or (\n            self._seq_num is not None and self._seq_num != seq - 1\n        ):\n            raise SyntaxError(\"APNG contains frame sequence errors\")\n        self._seq_num = seq\n        width, height = i32(s[4:]), i32(s[8:])\n        px, py = i32(s[12:]), i32(s[16:])\n        im_w, im_h = self.im_size\n        if px + width > im_w or py + height > im_h:\n            raise SyntaxError(\"APNG contains invalid frames\")\n        self.im_info[\"bbox\"] = (px, py, px + width, py + height)\n        delay_num, delay_den = i16(s[20:]), i16(s[22:])\n        if delay_den == 0:\n            delay_den = 100\n        self.im_info[\"duration\"] = float(delay_num) / float(delay_den) * 1000\n        self.im_info[\"disposal\"] = i8(s[24])\n        self.im_info[\"blend\"] = i8(s[25])\n        return s\n\n    def chunk_fdAT(self, pos, length):\n        s = ImageFile._safe_read(self.fp, 4)\n        seq = i32(s)\n        if self._seq_num != seq - 1:\n            raise SyntaxError(\"APNG contains frame sequence errors\")\n        self._seq_num = seq\n        return self.chunk_IDAT(pos + 4, length - 4)\n\n\n# --------------------------------------------------------------------\n# PNG reader\n\n\ndef _accept(prefix):\n    return prefix[:8] == _MAGIC\n\n\n##\n# Image plugin for PNG images.\n\n\nclass PngImageFile(ImageFile.ImageFile):\n\n    format = \"PNG\"\n    format_description = \"Portable network graphics\"\n\n    def _open(self):\n\n        if self.fp.read(8) != _MAGIC:\n            raise SyntaxError(\"not a PNG file\")\n        self.__fp = self.fp\n\n        #\n        # Parse headers up to the first IDAT or fDAT chunk\n\n        self.png = PngStream(self.fp)\n\n        while True:\n\n            #\n            # get next chunk\n\n            cid, pos, length = self.png.read()\n\n            try:\n                s = self.png.call(cid, pos, length)\n            except EOFError:\n                break\n            except AttributeError:\n                logger.debug(\"%r %s %s (unknown)\", cid, pos, length)\n                s = ImageFile._safe_read(self.fp, length)\n\n            self.png.crc(cid, s)\n\n        #\n        # Copy relevant attributes from the PngStream.  An alternative\n        # would be to let the PngStream class modify these attributes\n        # directly, but that introduces circular references which are\n        # difficult to break if things go wrong in the decoder...\n        # (believe me, I've tried ;-)\n\n        self.mode = self.png.im_mode\n        self._size = self.png.im_size\n        self.info = self.png.im_info\n        self._text = None\n        self.tile = self.png.im_tile\n        self.custom_mimetype = self.png.im_custom_mimetype\n        self._n_frames = self.png.im_n_frames\n        self.default_image = self.info.get(\"default_image\", False)\n\n        if self.png.im_palette:\n            rawmode, data = self.png.im_palette\n            self.palette = ImagePalette.raw(rawmode, data)\n\n        if cid == b\"fdAT\":\n            self.__prepare_idat = length - 4\n        else:\n            self.__prepare_idat = length  # used by load_prepare()\n\n        if self._n_frames is not None:\n            self._close_exclusive_fp_after_loading = False\n            self.png.save_rewind()\n            self.__rewind_idat = self.__prepare_idat\n            self.__rewind = self.__fp.tell()\n            if self.default_image:\n                # IDAT chunk contains default image and not first animation frame\n                self._n_frames += 1\n            self._seek(0)\n\n    @property\n    def text(self):\n        # experimental\n        if self._text is None:\n            # iTxt, tEXt and zTXt chunks may appear at the end of the file\n            # So load the file to ensure that they are read\n            if self.is_animated:\n                frame = self.__frame\n                # for APNG, seek to the final frame before loading\n                self.seek(self.n_frames - 1)\n            self.load()\n            if self.is_animated:\n                self.seek(frame)\n        return self._text\n\n    @property\n    def n_frames(self):\n        if self._n_frames is None:\n            return 1\n        return self._n_frames\n\n    @property\n    def is_animated(self):\n        return self._n_frames is not None\n\n    def verify(self):\n        \"\"\"Verify PNG file\"\"\"\n\n        if self.fp is None:\n            raise RuntimeError(\"verify must be called directly after open\")\n\n        # back up to beginning of IDAT block\n        self.fp.seek(self.tile[0][2] - 8)\n\n        self.png.verify()\n        self.png.close()\n\n        if self._exclusive_fp:\n            self.fp.close()\n        self.fp = None\n\n    def seek(self, frame):\n        if not self._seek_check(frame):\n            return\n        if frame < self.__frame:\n            self._seek(0, True)\n\n        last_frame = self.__frame\n        for f in range(self.__frame + 1, frame + 1):\n            try:\n                self._seek(f)\n            except EOFError:\n                self.seek(last_frame)\n                raise EOFError(\"no more images in APNG file\")\n\n    def _seek(self, frame, rewind=False):\n        if frame == 0:\n            if rewind:\n                self.__fp.seek(self.__rewind)\n                self.png.rewind()\n                self.__prepare_idat = self.__rewind_idat\n                self.im = None\n                if self.pyaccess:\n                    self.pyaccess = None\n                self.info = self.png.im_info\n                self.tile = self.png.im_tile\n                self.fp = self.__fp\n            self._prev_im = None\n            self.dispose = None\n            self.default_image = self.info.get(\"default_image\", False)\n            self.dispose_op = self.info.get(\"disposal\")\n            self.blend_op = self.info.get(\"blend\")\n            self.dispose_extent = self.info.get(\"bbox\")\n            self.__frame = 0\n            return\n        else:\n            if frame != self.__frame + 1:\n                raise ValueError(\"cannot seek to frame %d\" % frame)\n\n        # ensure previous frame was loaded\n        self.load()\n\n        self.fp = self.__fp\n\n        # advance to the next frame\n        if self.__prepare_idat:\n            ImageFile._safe_read(self.fp, self.__prepare_idat)\n            self.__prepare_idat = 0\n        frame_start = False\n        while True:\n            self.fp.read(4)  # CRC\n\n            try:\n                cid, pos, length = self.png.read()\n            except (struct.error, SyntaxError):\n                break\n\n            if cid == b\"IEND\":\n                raise EOFError(\"No more images in APNG file\")\n            if cid == b\"fcTL\":\n                if frame_start:\n                    # there must be at least one fdAT chunk between fcTL chunks\n                    raise SyntaxError(\"APNG missing frame data\")\n                frame_start = True\n\n            try:\n                self.png.call(cid, pos, length)\n            except UnicodeDecodeError:\n                break\n            except EOFError:\n                if cid == b\"fdAT\":\n                    length -= 4\n                    if frame_start:\n                        self.__prepare_idat = length\n                        break\n                ImageFile._safe_read(self.fp, length)\n            except AttributeError:\n                logger.debug(\"%r %s %s (unknown)\", cid, pos, length)\n                ImageFile._safe_read(self.fp, length)\n\n        self.__frame = frame\n        self.tile = self.png.im_tile\n        self.dispose_op = self.info.get(\"disposal\")\n        self.blend_op = self.info.get(\"blend\")\n        self.dispose_extent = self.info.get(\"bbox\")\n\n        if not self.tile:\n            raise EOFError\n\n    def tell(self):\n        return self.__frame\n\n    def load_prepare(self):\n        \"\"\"internal: prepare to read PNG file\"\"\"\n\n        if self.info.get(\"interlace\"):\n            self.decoderconfig = self.decoderconfig + (1,)\n\n        self.__idat = self.__prepare_idat  # used by load_read()\n        ImageFile.ImageFile.load_prepare(self)\n\n    def load_read(self, read_bytes):\n        \"\"\"internal: read more image data\"\"\"\n\n        while self.__idat == 0:\n            # end of chunk, skip forward to next one\n\n            self.fp.read(4)  # CRC\n\n            cid, pos, length = self.png.read()\n\n            if cid not in [b\"IDAT\", b\"DDAT\", b\"fdAT\"]:\n                self.png.push(cid, pos, length)\n                return b\"\"\n\n            if cid == b\"fdAT\":\n                try:\n                    self.png.call(cid, pos, length)\n                except EOFError:\n                    pass\n                self.__idat = length - 4  # sequence_num has already been read\n            else:\n                self.__idat = length  # empty chunks are allowed\n\n        # read more data from this chunk\n        if read_bytes <= 0:\n            read_bytes = self.__idat\n        else:\n            read_bytes = min(read_bytes, self.__idat)\n\n        self.__idat = self.__idat - read_bytes\n\n        return self.fp.read(read_bytes)\n\n    def load_end(self):\n        \"\"\"internal: finished reading image data\"\"\"\n        while True:\n            self.fp.read(4)  # CRC\n\n            try:\n                cid, pos, length = self.png.read()\n            except (struct.error, SyntaxError):\n                break\n\n            if cid == b\"IEND\":\n                break\n            elif cid == b\"fcTL\" and self.is_animated:\n                # start of the next frame, stop reading\n                self.__prepare_idat = 0\n                self.png.push(cid, pos, length)\n                break\n\n            try:\n                self.png.call(cid, pos, length)\n            except UnicodeDecodeError:\n                break\n            except EOFError:\n                if cid == b\"fdAT\":\n                    length -= 4\n                ImageFile._safe_read(self.fp, length)\n            except AttributeError:\n                logger.debug(\"%r %s %s (unknown)\", cid, pos, length)\n                ImageFile._safe_read(self.fp, length)\n        self._text = self.png.im_text\n        if not self.is_animated:\n            self.png.close()\n            self.png = None\n        else:\n            # setup frame disposal (actual disposal done when needed in _seek())\n            if self._prev_im is None and self.dispose_op == APNG_DISPOSE_OP_PREVIOUS:\n                self.dispose_op = APNG_DISPOSE_OP_BACKGROUND\n\n            if self.dispose_op == APNG_DISPOSE_OP_PREVIOUS:\n                dispose = self._prev_im.copy()\n                dispose = self._crop(dispose, self.dispose_extent)\n            elif self.dispose_op == APNG_DISPOSE_OP_BACKGROUND:\n                dispose = Image.core.fill(\"RGBA\", self.size, (0, 0, 0, 0))\n                dispose = self._crop(dispose, self.dispose_extent)\n            else:\n                dispose = None\n\n            if self._prev_im and self.blend_op == APNG_BLEND_OP_OVER:\n                updated = self._crop(self.im, self.dispose_extent)\n                self._prev_im.paste(\n                    updated, self.dispose_extent, updated.convert(\"RGBA\")\n                )\n                self.im = self._prev_im\n                if self.pyaccess:\n                    self.pyaccess = None\n            self._prev_im = self.im.copy()\n\n            if dispose:\n                self._prev_im.paste(dispose, self.dispose_extent)\n\n    def _getexif(self):\n        if \"exif\" not in self.info:\n            self.load()\n        if \"exif\" not in self.info:\n            return None\n        return dict(self.getexif())\n\n    def getexif(self):\n        if \"exif\" not in self.info:\n            self.load()\n        return ImageFile.ImageFile.getexif(self)\n\n    def _close__fp(self):\n        try:\n            if self.__fp != self.fp:\n                self.__fp.close()\n        except AttributeError:\n            pass\n        finally:\n            self.__fp = None\n\n\n# --------------------------------------------------------------------\n# PNG writer\n\n_OUTMODES = {\n    # supported PIL modes, and corresponding rawmodes/bits/color combinations\n    \"1\": (\"1\", b\"\\x01\\x00\"),\n    \"L;1\": (\"L;1\", b\"\\x01\\x00\"),\n    \"L;2\": (\"L;2\", b\"\\x02\\x00\"),\n    \"L;4\": (\"L;4\", b\"\\x04\\x00\"),\n    \"L\": (\"L\", b\"\\x08\\x00\"),\n    \"LA\": (\"LA\", b\"\\x08\\x04\"),\n    \"I\": (\"I;16B\", b\"\\x10\\x00\"),\n    \"I;16\": (\"I;16B\", b\"\\x10\\x00\"),\n    \"P;1\": (\"P;1\", b\"\\x01\\x03\"),\n    \"P;2\": (\"P;2\", b\"\\x02\\x03\"),\n    \"P;4\": (\"P;4\", b\"\\x04\\x03\"),\n    \"P\": (\"P\", b\"\\x08\\x03\"),\n    \"RGB\": (\"RGB\", b\"\\x08\\x02\"),\n    \"RGBA\": (\"RGBA\", b\"\\x08\\x06\"),\n}\n\n\ndef putchunk(fp, cid, *data):\n    \"\"\"Write a PNG chunk (including CRC field)\"\"\"\n\n    data = b\"\".join(data)\n\n    fp.write(o32(len(data)) + cid)\n    fp.write(data)\n    crc = _crc32(data, _crc32(cid))\n    fp.write(o32(crc))\n\n\nclass _idat:\n    # wrap output from the encoder in IDAT chunks\n\n    def __init__(self, fp, chunk):\n        self.fp = fp\n        self.chunk = chunk\n\n    def write(self, data):\n        self.chunk(self.fp, b\"IDAT\", data)\n\n\nclass _fdat:\n    # wrap encoder output in fdAT chunks\n\n    def __init__(self, fp, chunk, seq_num):\n        self.fp = fp\n        self.chunk = chunk\n        self.seq_num = seq_num\n\n    def write(self, data):\n        self.chunk(self.fp, b\"fdAT\", o32(self.seq_num), data)\n        self.seq_num += 1\n\n\ndef _write_multiple_frames(im, fp, chunk, rawmode):\n    default_image = im.encoderinfo.get(\"default_image\", im.info.get(\"default_image\"))\n    duration = im.encoderinfo.get(\"duration\", im.info.get(\"duration\", 0))\n    loop = im.encoderinfo.get(\"loop\", im.info.get(\"loop\", 0))\n    disposal = im.encoderinfo.get(\"disposal\", im.info.get(\"disposal\"))\n    blend = im.encoderinfo.get(\"blend\", im.info.get(\"blend\"))\n\n    if default_image:\n        chain = itertools.chain(im.encoderinfo.get(\"append_images\", []))\n    else:\n        chain = itertools.chain([im], im.encoderinfo.get(\"append_images\", []))\n\n    im_frames = []\n    frame_count = 0\n    for im_seq in chain:\n        for im_frame in ImageSequence.Iterator(im_seq):\n            im_frame = im_frame.copy()\n            if im_frame.mode != im.mode:\n                if im.mode == \"P\":\n                    im_frame = im_frame.convert(im.mode, palette=im.palette)\n                else:\n                    im_frame = im_frame.convert(im.mode)\n            encoderinfo = im.encoderinfo.copy()\n            if isinstance(duration, (list, tuple)):\n                encoderinfo[\"duration\"] = duration[frame_count]\n            if isinstance(disposal, (list, tuple)):\n                encoderinfo[\"disposal\"] = disposal[frame_count]\n            if isinstance(blend, (list, tuple)):\n                encoderinfo[\"blend\"] = blend[frame_count]\n            frame_count += 1\n\n            if im_frames:\n                previous = im_frames[-1]\n                prev_disposal = previous[\"encoderinfo\"].get(\"disposal\")\n                prev_blend = previous[\"encoderinfo\"].get(\"blend\")\n                if prev_disposal == APNG_DISPOSE_OP_PREVIOUS and len(im_frames) < 2:\n                    prev_disposal == APNG_DISPOSE_OP_BACKGROUND\n\n                if prev_disposal == APNG_DISPOSE_OP_BACKGROUND:\n                    base_im = previous[\"im\"]\n                    dispose = Image.core.fill(\"RGBA\", im.size, (0, 0, 0, 0))\n                    bbox = previous[\"bbox\"]\n                    if bbox:\n                        dispose = dispose.crop(bbox)\n                    else:\n                        bbox = (0, 0) + im.size\n                    base_im.paste(dispose, bbox)\n                elif prev_disposal == APNG_DISPOSE_OP_PREVIOUS:\n                    base_im = im_frames[-2][\"im\"]\n                else:\n                    base_im = previous[\"im\"]\n                delta = ImageChops.subtract_modulo(im_frame, base_im)\n                bbox = delta.getbbox()\n                if (\n                    not bbox\n                    and prev_disposal == encoderinfo.get(\"disposal\")\n                    and prev_blend == encoderinfo.get(\"blend\")\n                ):\n                    duration = encoderinfo.get(\"duration\", 0)\n                    if duration:\n                        if \"duration\" in previous[\"encoderinfo\"]:\n                            previous[\"encoderinfo\"][\"duration\"] += duration\n                        else:\n                            previous[\"encoderinfo\"][\"duration\"] = duration\n                    continue\n            else:\n                bbox = None\n            im_frames.append({\"im\": im_frame, \"bbox\": bbox, \"encoderinfo\": encoderinfo})\n\n    # animation control\n    chunk(\n        fp, b\"acTL\", o32(len(im_frames)), o32(loop),  # 0: num_frames  # 4: num_plays\n    )\n\n    # default image IDAT (if it exists)\n    if default_image:\n        ImageFile._save(im, _idat(fp, chunk), [(\"zip\", (0, 0) + im.size, 0, rawmode)])\n\n    seq_num = 0\n    for frame, frame_data in enumerate(im_frames):\n        im_frame = frame_data[\"im\"]\n        if not frame_data[\"bbox\"]:\n            bbox = (0, 0) + im_frame.size\n        else:\n            bbox = frame_data[\"bbox\"]\n            im_frame = im_frame.crop(bbox)\n        size = im_frame.size\n        duration = int(round(frame_data[\"encoderinfo\"].get(\"duration\", 0)))\n        disposal = frame_data[\"encoderinfo\"].get(\"disposal\", APNG_DISPOSE_OP_NONE)\n        blend = frame_data[\"encoderinfo\"].get(\"blend\", APNG_BLEND_OP_SOURCE)\n        # frame control\n        chunk(\n            fp,\n            b\"fcTL\",\n            o32(seq_num),  # sequence_number\n            o32(size[0]),  # width\n            o32(size[1]),  # height\n            o32(bbox[0]),  # x_offset\n            o32(bbox[1]),  # y_offset\n            o16(duration),  # delay_numerator\n            o16(1000),  # delay_denominator\n            o8(disposal),  # dispose_op\n            o8(blend),  # blend_op\n        )\n        seq_num += 1\n        # frame data\n        if frame == 0 and not default_image:\n            # first frame must be in IDAT chunks for backwards compatibility\n            ImageFile._save(\n                im_frame,\n                _idat(fp, chunk),\n                [(\"zip\", (0, 0) + im_frame.size, 0, rawmode)],\n            )\n        else:\n            fdat_chunks = _fdat(fp, chunk, seq_num)\n            ImageFile._save(\n                im_frame, fdat_chunks, [(\"zip\", (0, 0) + im_frame.size, 0, rawmode)],\n            )\n            seq_num = fdat_chunks.seq_num\n\n\ndef _save_all(im, fp, filename):\n    _save(im, fp, filename, save_all=True)\n\n\ndef _save(im, fp, filename, chunk=putchunk, save_all=False):\n    # save an image to disk (called by the save method)\n\n    mode = im.mode\n\n    if mode == \"P\":\n\n        #\n        # attempt to minimize storage requirements for palette images\n        if \"bits\" in im.encoderinfo:\n            # number of bits specified by user\n            colors = 1 << im.encoderinfo[\"bits\"]\n        else:\n            # check palette contents\n            if im.palette:\n                colors = max(min(len(im.palette.getdata()[1]) // 3, 256), 2)\n            else:\n                colors = 256\n\n        if colors <= 2:\n            bits = 1\n        elif colors <= 4:\n            bits = 2\n        elif colors <= 16:\n            bits = 4\n        else:\n            bits = 8\n        if bits != 8:\n            mode = \"%s;%d\" % (mode, bits)\n\n    # encoder options\n    im.encoderconfig = (\n        im.encoderinfo.get(\"optimize\", False),\n        im.encoderinfo.get(\"compress_level\", -1),\n        im.encoderinfo.get(\"compress_type\", -1),\n        im.encoderinfo.get(\"dictionary\", b\"\"),\n    )\n\n    # get the corresponding PNG mode\n    try:\n        rawmode, mode = _OUTMODES[mode]\n    except KeyError:\n        raise OSError(\"cannot write mode %s as PNG\" % mode)\n\n    #\n    # write minimal PNG file\n\n    fp.write(_MAGIC)\n\n    chunk(\n        fp,\n        b\"IHDR\",\n        o32(im.size[0]),  # 0: size\n        o32(im.size[1]),\n        mode,  # 8: depth/type\n        b\"\\0\",  # 10: compression\n        b\"\\0\",  # 11: filter category\n        b\"\\0\",  # 12: interlace flag\n    )\n\n    chunks = [b\"cHRM\", b\"gAMA\", b\"sBIT\", b\"sRGB\", b\"tIME\"]\n\n    icc = im.encoderinfo.get(\"icc_profile\", im.info.get(\"icc_profile\"))\n    if icc:\n        # ICC profile\n        # according to PNG spec, the iCCP chunk contains:\n        # Profile name  1-79 bytes (character string)\n        # Null separator        1 byte (null character)\n        # Compression method    1 byte (0)\n        # Compressed profile    n bytes (zlib with deflate compression)\n        name = b\"ICC Profile\"\n        data = name + b\"\\0\\0\" + zlib.compress(icc)\n        chunk(fp, b\"iCCP\", data)\n\n        # You must either have sRGB or iCCP.\n        # Disallow sRGB chunks when an iCCP-chunk has been emitted.\n        chunks.remove(b\"sRGB\")\n\n    info = im.encoderinfo.get(\"pnginfo\")\n    if info:\n        chunks_multiple_allowed = [b\"sPLT\", b\"iTXt\", b\"tEXt\", b\"zTXt\"]\n        for cid, data in info.chunks:\n            if cid in chunks:\n                chunks.remove(cid)\n                chunk(fp, cid, data)\n            elif cid in chunks_multiple_allowed:\n                chunk(fp, cid, data)\n\n    if im.mode == \"P\":\n        palette_byte_number = (2 ** bits) * 3\n        palette_bytes = im.im.getpalette(\"RGB\")[:palette_byte_number]\n        while len(palette_bytes) < palette_byte_number:\n            palette_bytes += b\"\\0\"\n        chunk(fp, b\"PLTE\", palette_bytes)\n\n    transparency = im.encoderinfo.get(\"transparency\", im.info.get(\"transparency\", None))\n\n    if transparency or transparency == 0:\n        if im.mode == \"P\":\n            # limit to actual palette size\n            alpha_bytes = 2 ** bits\n            if isinstance(transparency, bytes):\n                chunk(fp, b\"tRNS\", transparency[:alpha_bytes])\n            else:\n                transparency = max(0, min(255, transparency))\n                alpha = b\"\\xFF\" * transparency + b\"\\0\"\n                chunk(fp, b\"tRNS\", alpha[:alpha_bytes])\n        elif im.mode in (\"1\", \"L\", \"I\"):\n            transparency = max(0, min(65535, transparency))\n            chunk(fp, b\"tRNS\", o16(transparency))\n        elif im.mode == \"RGB\":\n            red, green, blue = transparency\n            chunk(fp, b\"tRNS\", o16(red) + o16(green) + o16(blue))\n        else:\n            if \"transparency\" in im.encoderinfo:\n                # don't bother with transparency if it's an RGBA\n                # and it's in the info dict. It's probably just stale.\n                raise OSError(\"cannot use transparency for this mode\")\n    else:\n        if im.mode == \"P\" and im.im.getpalettemode() == \"RGBA\":\n            alpha = im.im.getpalette(\"RGBA\", \"A\")\n            alpha_bytes = 2 ** bits\n            chunk(fp, b\"tRNS\", alpha[:alpha_bytes])\n\n    dpi = im.encoderinfo.get(\"dpi\")\n    if dpi:\n        chunk(\n            fp,\n            b\"pHYs\",\n            o32(int(dpi[0] / 0.0254 + 0.5)),\n            o32(int(dpi[1] / 0.0254 + 0.5)),\n            b\"\\x01\",\n        )\n\n    if info:\n        chunks = [b\"bKGD\", b\"hIST\"]\n        for cid, data in info.chunks:\n            if cid in chunks:\n                chunks.remove(cid)\n                chunk(fp, cid, data)\n\n    exif = im.encoderinfo.get(\"exif\", im.info.get(\"exif\"))\n    if exif:\n        if isinstance(exif, Image.Exif):\n            exif = exif.tobytes(8)\n        if exif.startswith(b\"Exif\\x00\\x00\"):\n            exif = exif[6:]\n        chunk(fp, b\"eXIf\", exif)\n\n    if save_all:\n        _write_multiple_frames(im, fp, chunk, rawmode)\n    else:\n        ImageFile._save(im, _idat(fp, chunk), [(\"zip\", (0, 0) + im.size, 0, rawmode)])\n\n    chunk(fp, b\"IEND\", b\"\")\n\n    if hasattr(fp, \"flush\"):\n        fp.flush()\n\n\n# --------------------------------------------------------------------\n# PNG chunk converter\n\n\ndef getchunks(im, **params):\n    \"\"\"Return a list of PNG chunks representing this image.\"\"\"\n\n    class collector:\n        data = []\n\n        def write(self, data):\n            pass\n\n        def append(self, chunk):\n            self.data.append(chunk)\n\n    def append(fp, cid, *data):\n        data = b\"\".join(data)\n        crc = o32(_crc32(data, _crc32(cid)))\n        fp.append((cid, data, crc))\n\n    fp = collector()\n\n    try:\n        im.encoderinfo = params\n        _save(im, fp, None, append)\n    finally:\n        del im.encoderinfo\n\n    return fp.data\n\n\n# --------------------------------------------------------------------\n# Registry\n\nImage.register_open(PngImageFile.format, PngImageFile, _accept)\nImage.register_save(PngImageFile.format, _save)\nImage.register_save_all(PngImageFile.format, _save_all)\n\nImage.register_extensions(PngImageFile.format, [\".png\", \".apng\"])\n\nImage.register_mime(PngImageFile.format, \"image/png\")\n",
            "new_file_content": "#\n# The Python Imaging Library.\n# $Id$\n#\n# PNG support code\n#\n# See \"PNG (Portable Network Graphics) Specification, version 1.0;\n# W3C Recommendation\", 1996-10-01, Thomas Boutell (ed.).\n#\n# history:\n# 1996-05-06 fl   Created (couldn't resist it)\n# 1996-12-14 fl   Upgraded, added read and verify support (0.2)\n# 1996-12-15 fl   Separate PNG stream parser\n# 1996-12-29 fl   Added write support, added getchunks\n# 1996-12-30 fl   Eliminated circular references in decoder (0.3)\n# 1998-07-12 fl   Read/write 16-bit images as mode I (0.4)\n# 2001-02-08 fl   Added transparency support (from Zircon) (0.5)\n# 2001-04-16 fl   Don't close data source in \"open\" method (0.6)\n# 2004-02-24 fl   Don't even pretend to support interlaced files (0.7)\n# 2004-08-31 fl   Do basic sanity check on chunk identifiers (0.8)\n# 2004-09-20 fl   Added PngInfo chunk container\n# 2004-12-18 fl   Added DPI read support (based on code by Niki Spahiev)\n# 2008-08-13 fl   Added tRNS support for RGB images\n# 2009-03-06 fl   Support for preserving ICC profiles (by Florian Hoech)\n# 2009-03-08 fl   Added zTXT support (from Lowell Alleman)\n# 2009-03-29 fl   Read interlaced PNG files (from Conrado Porto Lopes Gouvua)\n#\n# Copyright (c) 1997-2009 by Secret Labs AB\n# Copyright (c) 1996 by Fredrik Lundh\n#\n# See the README file for information on usage and redistribution.\n#\n\nimport itertools\nimport logging\nimport re\nimport struct\nimport warnings\nimport zlib\n\nfrom . import Image, ImageChops, ImageFile, ImagePalette, ImageSequence\nfrom ._binary import i8, i16be as i16, i32be as i32, o8, o16be as o16, o32be as o32\n\nlogger = logging.getLogger(__name__)\n\nis_cid = re.compile(br\"\\w\\w\\w\\w\").match\n\n\n_MAGIC = b\"\\211PNG\\r\\n\\032\\n\"\n\n\n_MODES = {\n    # supported bits/color combinations, and corresponding modes/rawmodes\n    # Greyscale\n    (1, 0): (\"1\", \"1\"),\n    (2, 0): (\"L\", \"L;2\"),\n    (4, 0): (\"L\", \"L;4\"),\n    (8, 0): (\"L\", \"L\"),\n    (16, 0): (\"I\", \"I;16B\"),\n    # Truecolour\n    (8, 2): (\"RGB\", \"RGB\"),\n    (16, 2): (\"RGB\", \"RGB;16B\"),\n    # Indexed-colour\n    (1, 3): (\"P\", \"P;1\"),\n    (2, 3): (\"P\", \"P;2\"),\n    (4, 3): (\"P\", \"P;4\"),\n    (8, 3): (\"P\", \"P\"),\n    # Greyscale with alpha\n    (8, 4): (\"LA\", \"LA\"),\n    (16, 4): (\"RGBA\", \"LA;16B\"),  # LA;16B->LA not yet available\n    # Truecolour with alpha\n    (8, 6): (\"RGBA\", \"RGBA\"),\n    (16, 6): (\"RGBA\", \"RGBA;16B\"),\n}\n\n\n_simple_palette = re.compile(b\"^\\xff*\\x00\\xff*$\")\n\n# Maximum decompressed size for a iTXt or zTXt chunk.\n# Eliminates decompression bombs where compressed chunks can expand 1000x\nMAX_TEXT_CHUNK = ImageFile.SAFEBLOCK\n# Set the maximum total text chunk size.\nMAX_TEXT_MEMORY = 64 * MAX_TEXT_CHUNK\n\n\n# APNG frame disposal modes\nAPNG_DISPOSE_OP_NONE = 0\nAPNG_DISPOSE_OP_BACKGROUND = 1\nAPNG_DISPOSE_OP_PREVIOUS = 2\n\n# APNG frame blend modes\nAPNG_BLEND_OP_SOURCE = 0\nAPNG_BLEND_OP_OVER = 1\n\n\ndef _safe_zlib_decompress(s):\n    dobj = zlib.decompressobj()\n    plaintext = dobj.decompress(s, MAX_TEXT_CHUNK)\n    if dobj.unconsumed_tail:\n        raise ValueError(\"Decompressed Data Too Large\")\n    return plaintext\n\n\ndef _crc32(data, seed=0):\n    return zlib.crc32(data, seed) & 0xFFFFFFFF\n\n\n# --------------------------------------------------------------------\n# Support classes.  Suitable for PNG and related formats like MNG etc.\n\n\nclass ChunkStream:\n    def __init__(self, fp):\n\n        self.fp = fp\n        self.queue = []\n\n    def read(self):\n        \"\"\"Fetch a new chunk. Returns header information.\"\"\"\n        cid = None\n\n        if self.queue:\n            cid, pos, length = self.queue.pop()\n            self.fp.seek(pos)\n        else:\n            s = self.fp.read(8)\n            cid = s[4:]\n            pos = self.fp.tell()\n            length = i32(s)\n\n        if not is_cid(cid):\n            if not ImageFile.LOAD_TRUNCATED_IMAGES:\n                raise SyntaxError(\"broken PNG file (chunk %s)\" % repr(cid))\n\n        return cid, pos, length\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, *args):\n        self.close()\n\n    def close(self):\n        self.queue = self.crc = self.fp = None\n\n    def push(self, cid, pos, length):\n\n        self.queue.append((cid, pos, length))\n\n    def call(self, cid, pos, length):\n        \"\"\"Call the appropriate chunk handler\"\"\"\n\n        logger.debug(\"STREAM %r %s %s\", cid, pos, length)\n        return getattr(self, \"chunk_\" + cid.decode(\"ascii\"))(pos, length)\n\n    def crc(self, cid, data):\n        \"\"\"Read and verify checksum\"\"\"\n\n        # Skip CRC checks for ancillary chunks if allowed to load truncated\n        # images\n        # 5th byte of first char is 1 [specs, section 5.4]\n        if ImageFile.LOAD_TRUNCATED_IMAGES and (i8(cid[0]) >> 5 & 1):\n            self.crc_skip(cid, data)\n            return\n\n        try:\n            crc1 = _crc32(data, _crc32(cid))\n            crc2 = i32(self.fp.read(4))\n            if crc1 != crc2:\n                raise SyntaxError(\"broken PNG file (bad header checksum in %r)\" % cid)\n        except struct.error:\n            raise SyntaxError(\"broken PNG file (incomplete checksum in %r)\" % cid)\n\n    def crc_skip(self, cid, data):\n        \"\"\"Read checksum.  Used if the C module is not present\"\"\"\n\n        self.fp.read(4)\n\n    def verify(self, endchunk=b\"IEND\"):\n\n        # Simple approach; just calculate checksum for all remaining\n        # blocks.  Must be called directly after open.\n\n        cids = []\n\n        while True:\n            try:\n                cid, pos, length = self.read()\n            except struct.error:\n                raise OSError(\"truncated PNG file\")\n\n            if cid == endchunk:\n                break\n            self.crc(cid, ImageFile._safe_read(self.fp, length))\n            cids.append(cid)\n\n        return cids\n\n\nclass iTXt(str):\n    \"\"\"\n    Subclass of string to allow iTXt chunks to look like strings while\n    keeping their extra information\n\n    \"\"\"\n\n    @staticmethod\n    def __new__(cls, text, lang=None, tkey=None):\n        \"\"\"\n        :param cls: the class to use when creating the instance\n        :param text: value for this key\n        :param lang: language code\n        :param tkey: UTF-8 version of the key name\n        \"\"\"\n\n        self = str.__new__(cls, text)\n        self.lang = lang\n        self.tkey = tkey\n        return self\n\n\nclass PngInfo:\n    \"\"\"\n    PNG chunk container (for use with save(pnginfo=))\n\n    \"\"\"\n\n    def __init__(self):\n        self.chunks = []\n\n    def add(self, cid, data):\n        \"\"\"Appends an arbitrary chunk. Use with caution.\n\n        :param cid: a byte string, 4 bytes long.\n        :param data: a byte string of the encoded data\n\n        \"\"\"\n\n        self.chunks.append((cid, data))\n\n    def add_itxt(self, key, value, lang=\"\", tkey=\"\", zip=False):\n        \"\"\"Appends an iTXt chunk.\n\n        :param key: latin-1 encodable text key name\n        :param value: value for this key\n        :param lang: language code\n        :param tkey: UTF-8 version of the key name\n        :param zip: compression flag\n\n        \"\"\"\n\n        if not isinstance(key, bytes):\n            key = key.encode(\"latin-1\", \"strict\")\n        if not isinstance(value, bytes):\n            value = value.encode(\"utf-8\", \"strict\")\n        if not isinstance(lang, bytes):\n            lang = lang.encode(\"utf-8\", \"strict\")\n        if not isinstance(tkey, bytes):\n            tkey = tkey.encode(\"utf-8\", \"strict\")\n\n        if zip:\n            self.add(\n                b\"iTXt\",\n                key + b\"\\0\\x01\\0\" + lang + b\"\\0\" + tkey + b\"\\0\" + zlib.compress(value),\n            )\n        else:\n            self.add(b\"iTXt\", key + b\"\\0\\0\\0\" + lang + b\"\\0\" + tkey + b\"\\0\" + value)\n\n    def add_text(self, key, value, zip=False):\n        \"\"\"Appends a text chunk.\n\n        :param key: latin-1 encodable text key name\n        :param value: value for this key, text or an\n           :py:class:`PIL.PngImagePlugin.iTXt` instance\n        :param zip: compression flag\n\n        \"\"\"\n        if isinstance(value, iTXt):\n            return self.add_itxt(key, value, value.lang, value.tkey, zip=zip)\n\n        # The tEXt chunk stores latin-1 text\n        if not isinstance(value, bytes):\n            try:\n                value = value.encode(\"latin-1\", \"strict\")\n            except UnicodeError:\n                return self.add_itxt(key, value, zip=zip)\n\n        if not isinstance(key, bytes):\n            key = key.encode(\"latin-1\", \"strict\")\n\n        if zip:\n            self.add(b\"zTXt\", key + b\"\\0\\0\" + zlib.compress(value))\n        else:\n            self.add(b\"tEXt\", key + b\"\\0\" + value)\n\n\n# --------------------------------------------------------------------\n# PNG image stream (IHDR/IEND)\n\n\nclass PngStream(ChunkStream):\n    def __init__(self, fp):\n        super().__init__(fp)\n\n        # local copies of Image attributes\n        self.im_info = {}\n        self.im_text = {}\n        self.im_size = (0, 0)\n        self.im_mode = None\n        self.im_tile = None\n        self.im_palette = None\n        self.im_custom_mimetype = None\n        self.im_n_frames = None\n        self._seq_num = None\n        self.rewind_state = None\n\n        self.text_memory = 0\n\n    def check_text_memory(self, chunklen):\n        self.text_memory += chunklen\n        if self.text_memory > MAX_TEXT_MEMORY:\n            raise ValueError(\n                \"Too much memory used in text chunks: %s>MAX_TEXT_MEMORY\"\n                % self.text_memory\n            )\n\n    def save_rewind(self):\n        self.rewind_state = {\n            \"info\": self.im_info.copy(),\n            \"tile\": self.im_tile,\n            \"seq_num\": self._seq_num,\n        }\n\n    def rewind(self):\n        self.im_info = self.rewind_state[\"info\"]\n        self.im_tile = self.rewind_state[\"tile\"]\n        self._seq_num = self.rewind_state[\"seq_num\"]\n\n    def chunk_iCCP(self, pos, length):\n\n        # ICC profile\n        s = ImageFile._safe_read(self.fp, length)\n        # according to PNG spec, the iCCP chunk contains:\n        # Profile name  1-79 bytes (character string)\n        # Null separator        1 byte (null character)\n        # Compression method    1 byte (0)\n        # Compressed profile    n bytes (zlib with deflate compression)\n        i = s.find(b\"\\0\")\n        logger.debug(\"iCCP profile name %r\", s[:i])\n        logger.debug(\"Compression method %s\", i8(s[i]))\n        comp_method = i8(s[i])\n        if comp_method != 0:\n            raise SyntaxError(\n                \"Unknown compression method %s in iCCP chunk\" % comp_method\n            )\n        try:\n            icc_profile = _safe_zlib_decompress(s[i + 2 :])\n        except ValueError:\n            if ImageFile.LOAD_TRUNCATED_IMAGES:\n                icc_profile = None\n            else:\n                raise\n        except zlib.error:\n            icc_profile = None  # FIXME\n        self.im_info[\"icc_profile\"] = icc_profile\n        return s\n\n    def chunk_IHDR(self, pos, length):\n\n        # image header\n        s = ImageFile._safe_read(self.fp, length)\n        self.im_size = i32(s), i32(s[4:])\n        try:\n            self.im_mode, self.im_rawmode = _MODES[(i8(s[8]), i8(s[9]))]\n        except Exception:\n            pass\n        if i8(s[12]):\n            self.im_info[\"interlace\"] = 1\n        if i8(s[11]):\n            raise SyntaxError(\"unknown filter category\")\n        return s\n\n    def chunk_IDAT(self, pos, length):\n\n        # image data\n        if \"bbox\" in self.im_info:\n            tile = [(\"zip\", self.im_info[\"bbox\"], pos, self.im_rawmode)]\n        else:\n            if self.im_n_frames is not None:\n                self.im_info[\"default_image\"] = True\n            tile = [(\"zip\", (0, 0) + self.im_size, pos, self.im_rawmode)]\n        self.im_tile = tile\n        self.im_idat = length\n        raise EOFError\n\n    def chunk_IEND(self, pos, length):\n\n        # end of PNG image\n        raise EOFError\n\n    def chunk_PLTE(self, pos, length):\n\n        # palette\n        s = ImageFile._safe_read(self.fp, length)\n        if self.im_mode == \"P\":\n            self.im_palette = \"RGB\", s\n        return s\n\n    def chunk_tRNS(self, pos, length):\n\n        # transparency\n        s = ImageFile._safe_read(self.fp, length)\n        if self.im_mode == \"P\":\n            if _simple_palette.match(s):\n                # tRNS contains only one full-transparent entry,\n                # other entries are full opaque\n                i = s.find(b\"\\0\")\n                if i >= 0:\n                    self.im_info[\"transparency\"] = i\n            else:\n                # otherwise, we have a byte string with one alpha value\n                # for each palette entry\n                self.im_info[\"transparency\"] = s\n        elif self.im_mode in (\"1\", \"L\", \"I\"):\n            self.im_info[\"transparency\"] = i16(s)\n        elif self.im_mode == \"RGB\":\n            self.im_info[\"transparency\"] = i16(s), i16(s[2:]), i16(s[4:])\n        return s\n\n    def chunk_gAMA(self, pos, length):\n        # gamma setting\n        s = ImageFile._safe_read(self.fp, length)\n        self.im_info[\"gamma\"] = i32(s) / 100000.0\n        return s\n\n    def chunk_cHRM(self, pos, length):\n        # chromaticity, 8 unsigned ints, actual value is scaled by 100,000\n        # WP x,y, Red x,y, Green x,y Blue x,y\n\n        s = ImageFile._safe_read(self.fp, length)\n        raw_vals = struct.unpack(\">%dI\" % (len(s) // 4), s)\n        self.im_info[\"chromaticity\"] = tuple(elt / 100000.0 for elt in raw_vals)\n        return s\n\n    def chunk_sRGB(self, pos, length):\n        # srgb rendering intent, 1 byte\n        # 0 perceptual\n        # 1 relative colorimetric\n        # 2 saturation\n        # 3 absolute colorimetric\n\n        s = ImageFile._safe_read(self.fp, length)\n        self.im_info[\"srgb\"] = i8(s)\n        return s\n\n    def chunk_pHYs(self, pos, length):\n\n        # pixels per unit\n        s = ImageFile._safe_read(self.fp, length)\n        px, py = i32(s), i32(s[4:])\n        unit = i8(s[8])\n        if unit == 1:  # meter\n            dpi = int(px * 0.0254 + 0.5), int(py * 0.0254 + 0.5)\n            self.im_info[\"dpi\"] = dpi\n        elif unit == 0:\n            self.im_info[\"aspect\"] = px, py\n        return s\n\n    def chunk_tEXt(self, pos, length):\n\n        # text\n        s = ImageFile._safe_read(self.fp, length)\n        try:\n            k, v = s.split(b\"\\0\", 1)\n        except ValueError:\n            # fallback for broken tEXt tags\n            k = s\n            v = b\"\"\n        if k:\n            k = k.decode(\"latin-1\", \"strict\")\n            v = v.decode(\"latin-1\", \"replace\")\n\n            self.im_info[k] = self.im_text[k] = v\n            self.check_text_memory(len(v))\n\n        return s\n\n    def chunk_zTXt(self, pos, length):\n\n        # compressed text\n        s = ImageFile._safe_read(self.fp, length)\n        try:\n            k, v = s.split(b\"\\0\", 1)\n        except ValueError:\n            k = s\n            v = b\"\"\n        if v:\n            comp_method = i8(v[0])\n        else:\n            comp_method = 0\n        if comp_method != 0:\n            raise SyntaxError(\n                \"Unknown compression method %s in zTXt chunk\" % comp_method\n            )\n        try:\n            v = _safe_zlib_decompress(v[1:])\n        except ValueError:\n            if ImageFile.LOAD_TRUNCATED_IMAGES:\n                v = b\"\"\n            else:\n                raise\n        except zlib.error:\n            v = b\"\"\n\n        if k:\n            k = k.decode(\"latin-1\", \"strict\")\n            v = v.decode(\"latin-1\", \"replace\")\n\n            self.im_info[k] = self.im_text[k] = v\n            self.check_text_memory(len(v))\n\n        return s\n\n    def chunk_iTXt(self, pos, length):\n\n        # international text\n        r = s = ImageFile._safe_read(self.fp, length)\n        try:\n            k, r = r.split(b\"\\0\", 1)\n        except ValueError:\n            return s\n        if len(r) < 2:\n            return s\n        cf, cm, r = i8(r[0]), i8(r[1]), r[2:]\n        try:\n            lang, tk, v = r.split(b\"\\0\", 2)\n        except ValueError:\n            return s\n        if cf != 0:\n            if cm == 0:\n                try:\n                    v = _safe_zlib_decompress(v)\n                except ValueError:\n                    if ImageFile.LOAD_TRUNCATED_IMAGES:\n                        return s\n                    else:\n                        raise\n                except zlib.error:\n                    return s\n            else:\n                return s\n        try:\n            k = k.decode(\"latin-1\", \"strict\")\n            lang = lang.decode(\"utf-8\", \"strict\")\n            tk = tk.decode(\"utf-8\", \"strict\")\n            v = v.decode(\"utf-8\", \"strict\")\n        except UnicodeError:\n            return s\n\n        self.im_info[k] = self.im_text[k] = iTXt(v, lang, tk)\n        self.check_text_memory(len(v))\n\n        return s\n\n    def chunk_eXIf(self, pos, length):\n        s = ImageFile._safe_read(self.fp, length)\n        self.im_info[\"exif\"] = b\"Exif\\x00\\x00\" + s\n        return s\n\n    # APNG chunks\n    def chunk_acTL(self, pos, length):\n        s = ImageFile._safe_read(self.fp, length)\n        if self.im_n_frames is not None:\n            self.im_n_frames = None\n            warnings.warn(\"Invalid APNG, will use default PNG image if possible\")\n            return s\n        n_frames = i32(s)\n        if n_frames == 0 or n_frames > 0x80000000:\n            warnings.warn(\"Invalid APNG, will use default PNG image if possible\")\n            return s\n        self.im_n_frames = n_frames\n        self.im_info[\"loop\"] = i32(s[4:])\n        self.im_custom_mimetype = \"image/apng\"\n        return s\n\n    def chunk_fcTL(self, pos, length):\n        s = ImageFile._safe_read(self.fp, length)\n        seq = i32(s)\n        if (self._seq_num is None and seq != 0) or (\n            self._seq_num is not None and self._seq_num != seq - 1\n        ):\n            raise SyntaxError(\"APNG contains frame sequence errors\")\n        self._seq_num = seq\n        width, height = i32(s[4:]), i32(s[8:])\n        px, py = i32(s[12:]), i32(s[16:])\n        im_w, im_h = self.im_size\n        if px + width > im_w or py + height > im_h:\n            raise SyntaxError(\"APNG contains invalid frames\")\n        self.im_info[\"bbox\"] = (px, py, px + width, py + height)\n        delay_num, delay_den = i16(s[20:]), i16(s[22:])\n        if delay_den == 0:\n            delay_den = 100\n        self.im_info[\"duration\"] = float(delay_num) / float(delay_den) * 1000\n        self.im_info[\"disposal\"] = i8(s[24])\n        self.im_info[\"blend\"] = i8(s[25])\n        return s\n\n    def chunk_fdAT(self, pos, length):\n        s = ImageFile._safe_read(self.fp, 4)\n        seq = i32(s)\n        if self._seq_num != seq - 1:\n            raise SyntaxError(\"APNG contains frame sequence errors\")\n        self._seq_num = seq\n        return self.chunk_IDAT(pos + 4, length - 4)\n\n\n# --------------------------------------------------------------------\n# PNG reader\n\n\ndef _accept(prefix):\n    return prefix[:8] == _MAGIC\n\n\n##\n# Image plugin for PNG images.\n\n\nclass PngImageFile(ImageFile.ImageFile):\n\n    format = \"PNG\"\n    format_description = \"Portable network graphics\"\n\n    def _open(self):\n\n        if self.fp.read(8) != _MAGIC:\n            raise SyntaxError(\"not a PNG file\")\n        self.__fp = self.fp\n\n        #\n        # Parse headers up to the first IDAT or fDAT chunk\n\n        self.png = PngStream(self.fp)\n\n        while True:\n\n            #\n            # get next chunk\n\n            cid, pos, length = self.png.read()\n\n            try:\n                s = self.png.call(cid, pos, length)\n            except EOFError:\n                break\n            except AttributeError:\n                logger.debug(\"%r %s %s (unknown)\", cid, pos, length)\n                s = ImageFile._safe_read(self.fp, length)\n\n            self.png.crc(cid, s)\n\n        #\n        # Copy relevant attributes from the PngStream.  An alternative\n        # would be to let the PngStream class modify these attributes\n        # directly, but that introduces circular references which are\n        # difficult to break if things go wrong in the decoder...\n        # (believe me, I've tried ;-)\n\n        self.mode = self.png.im_mode\n        self._size = self.png.im_size\n        self.info = self.png.im_info\n        self._text = None\n        self.tile = self.png.im_tile\n        self.custom_mimetype = self.png.im_custom_mimetype\n        self._n_frames = self.png.im_n_frames\n        self.default_image = self.info.get(\"default_image\", False)\n\n        if self.png.im_palette:\n            rawmode, data = self.png.im_palette\n            self.palette = ImagePalette.raw(rawmode, data)\n\n        if cid == b\"fdAT\":\n            self.__prepare_idat = length - 4\n        else:\n            self.__prepare_idat = length  # used by load_prepare()\n\n        if self._n_frames is not None:\n            self._close_exclusive_fp_after_loading = False\n            self.png.save_rewind()\n            self.__rewind_idat = self.__prepare_idat\n            self.__rewind = self.__fp.tell()\n            if self.default_image:\n                # IDAT chunk contains default image and not first animation frame\n                self._n_frames += 1\n            self._seek(0)\n\n    @property\n    def text(self):\n        # experimental\n        if self._text is None:\n            # iTxt, tEXt and zTXt chunks may appear at the end of the file\n            # So load the file to ensure that they are read\n            if self.is_animated:\n                frame = self.__frame\n                # for APNG, seek to the final frame before loading\n                self.seek(self.n_frames - 1)\n            self.load()\n            if self.is_animated:\n                self.seek(frame)\n        return self._text\n\n    @property\n    def n_frames(self):\n        if self._n_frames is None:\n            return 1\n        return self._n_frames\n\n    @property\n    def is_animated(self):\n        return self._n_frames is not None and self._n_frames > 1\n\n    def verify(self):\n        \"\"\"Verify PNG file\"\"\"\n\n        if self.fp is None:\n            raise RuntimeError(\"verify must be called directly after open\")\n\n        # back up to beginning of IDAT block\n        self.fp.seek(self.tile[0][2] - 8)\n\n        self.png.verify()\n        self.png.close()\n\n        if self._exclusive_fp:\n            self.fp.close()\n        self.fp = None\n\n    def seek(self, frame):\n        if not self._seek_check(frame):\n            return\n        if frame < self.__frame:\n            self._seek(0, True)\n\n        last_frame = self.__frame\n        for f in range(self.__frame + 1, frame + 1):\n            try:\n                self._seek(f)\n            except EOFError:\n                self.seek(last_frame)\n                raise EOFError(\"no more images in APNG file\")\n\n    def _seek(self, frame, rewind=False):\n        if frame == 0:\n            if rewind:\n                self.__fp.seek(self.__rewind)\n                self.png.rewind()\n                self.__prepare_idat = self.__rewind_idat\n                self.im = None\n                if self.pyaccess:\n                    self.pyaccess = None\n                self.info = self.png.im_info\n                self.tile = self.png.im_tile\n                self.fp = self.__fp\n            self._prev_im = None\n            self.dispose = None\n            self.default_image = self.info.get(\"default_image\", False)\n            self.dispose_op = self.info.get(\"disposal\")\n            self.blend_op = self.info.get(\"blend\")\n            self.dispose_extent = self.info.get(\"bbox\")\n            self.__frame = 0\n            return\n        else:\n            if frame != self.__frame + 1:\n                raise ValueError(\"cannot seek to frame %d\" % frame)\n\n        # ensure previous frame was loaded\n        self.load()\n\n        self.fp = self.__fp\n\n        # advance to the next frame\n        if self.__prepare_idat:\n            ImageFile._safe_read(self.fp, self.__prepare_idat)\n            self.__prepare_idat = 0\n        frame_start = False\n        while True:\n            self.fp.read(4)  # CRC\n\n            try:\n                cid, pos, length = self.png.read()\n            except (struct.error, SyntaxError):\n                break\n\n            if cid == b\"IEND\":\n                raise EOFError(\"No more images in APNG file\")\n            if cid == b\"fcTL\":\n                if frame_start:\n                    # there must be at least one fdAT chunk between fcTL chunks\n                    raise SyntaxError(\"APNG missing frame data\")\n                frame_start = True\n\n            try:\n                self.png.call(cid, pos, length)\n            except UnicodeDecodeError:\n                break\n            except EOFError:\n                if cid == b\"fdAT\":\n                    length -= 4\n                    if frame_start:\n                        self.__prepare_idat = length\n                        break\n                ImageFile._safe_read(self.fp, length)\n            except AttributeError:\n                logger.debug(\"%r %s %s (unknown)\", cid, pos, length)\n                ImageFile._safe_read(self.fp, length)\n\n        self.__frame = frame\n        self.tile = self.png.im_tile\n        self.dispose_op = self.info.get(\"disposal\")\n        self.blend_op = self.info.get(\"blend\")\n        self.dispose_extent = self.info.get(\"bbox\")\n\n        if not self.tile:\n            raise EOFError\n\n    def tell(self):\n        return self.__frame\n\n    def load_prepare(self):\n        \"\"\"internal: prepare to read PNG file\"\"\"\n\n        if self.info.get(\"interlace\"):\n            self.decoderconfig = self.decoderconfig + (1,)\n\n        self.__idat = self.__prepare_idat  # used by load_read()\n        ImageFile.ImageFile.load_prepare(self)\n\n    def load_read(self, read_bytes):\n        \"\"\"internal: read more image data\"\"\"\n\n        while self.__idat == 0:\n            # end of chunk, skip forward to next one\n\n            self.fp.read(4)  # CRC\n\n            cid, pos, length = self.png.read()\n\n            if cid not in [b\"IDAT\", b\"DDAT\", b\"fdAT\"]:\n                self.png.push(cid, pos, length)\n                return b\"\"\n\n            if cid == b\"fdAT\":\n                try:\n                    self.png.call(cid, pos, length)\n                except EOFError:\n                    pass\n                self.__idat = length - 4  # sequence_num has already been read\n            else:\n                self.__idat = length  # empty chunks are allowed\n\n        # read more data from this chunk\n        if read_bytes <= 0:\n            read_bytes = self.__idat\n        else:\n            read_bytes = min(read_bytes, self.__idat)\n\n        self.__idat = self.__idat - read_bytes\n\n        return self.fp.read(read_bytes)\n\n    def load_end(self):\n        \"\"\"internal: finished reading image data\"\"\"\n        while True:\n            self.fp.read(4)  # CRC\n\n            try:\n                cid, pos, length = self.png.read()\n            except (struct.error, SyntaxError):\n                break\n\n            if cid == b\"IEND\":\n                break\n            elif cid == b\"fcTL\" and self.is_animated:\n                # start of the next frame, stop reading\n                self.__prepare_idat = 0\n                self.png.push(cid, pos, length)\n                break\n\n            try:\n                self.png.call(cid, pos, length)\n            except UnicodeDecodeError:\n                break\n            except EOFError:\n                if cid == b\"fdAT\":\n                    length -= 4\n                ImageFile._safe_read(self.fp, length)\n            except AttributeError:\n                logger.debug(\"%r %s %s (unknown)\", cid, pos, length)\n                ImageFile._safe_read(self.fp, length)\n        self._text = self.png.im_text\n        if not self.is_animated:\n            self.png.close()\n            self.png = None\n        else:\n            # setup frame disposal (actual disposal done when needed in _seek())\n            if self._prev_im is None and self.dispose_op == APNG_DISPOSE_OP_PREVIOUS:\n                self.dispose_op = APNG_DISPOSE_OP_BACKGROUND\n\n            if self.dispose_op == APNG_DISPOSE_OP_PREVIOUS:\n                dispose = self._prev_im.copy()\n                dispose = self._crop(dispose, self.dispose_extent)\n            elif self.dispose_op == APNG_DISPOSE_OP_BACKGROUND:\n                dispose = Image.core.fill(\"RGBA\", self.size, (0, 0, 0, 0))\n                dispose = self._crop(dispose, self.dispose_extent)\n            else:\n                dispose = None\n\n            if self._prev_im and self.blend_op == APNG_BLEND_OP_OVER:\n                updated = self._crop(self.im, self.dispose_extent)\n                self._prev_im.paste(\n                    updated, self.dispose_extent, updated.convert(\"RGBA\")\n                )\n                self.im = self._prev_im\n                if self.pyaccess:\n                    self.pyaccess = None\n            self._prev_im = self.im.copy()\n\n            if dispose:\n                self._prev_im.paste(dispose, self.dispose_extent)\n\n    def _getexif(self):\n        if \"exif\" not in self.info:\n            self.load()\n        if \"exif\" not in self.info:\n            return None\n        return dict(self.getexif())\n\n    def getexif(self):\n        if \"exif\" not in self.info:\n            self.load()\n        return ImageFile.ImageFile.getexif(self)\n\n    def _close__fp(self):\n        try:\n            if self.__fp != self.fp:\n                self.__fp.close()\n        except AttributeError:\n            pass\n        finally:\n            self.__fp = None\n\n\n# --------------------------------------------------------------------\n# PNG writer\n\n_OUTMODES = {\n    # supported PIL modes, and corresponding rawmodes/bits/color combinations\n    \"1\": (\"1\", b\"\\x01\\x00\"),\n    \"L;1\": (\"L;1\", b\"\\x01\\x00\"),\n    \"L;2\": (\"L;2\", b\"\\x02\\x00\"),\n    \"L;4\": (\"L;4\", b\"\\x04\\x00\"),\n    \"L\": (\"L\", b\"\\x08\\x00\"),\n    \"LA\": (\"LA\", b\"\\x08\\x04\"),\n    \"I\": (\"I;16B\", b\"\\x10\\x00\"),\n    \"I;16\": (\"I;16B\", b\"\\x10\\x00\"),\n    \"P;1\": (\"P;1\", b\"\\x01\\x03\"),\n    \"P;2\": (\"P;2\", b\"\\x02\\x03\"),\n    \"P;4\": (\"P;4\", b\"\\x04\\x03\"),\n    \"P\": (\"P\", b\"\\x08\\x03\"),\n    \"RGB\": (\"RGB\", b\"\\x08\\x02\"),\n    \"RGBA\": (\"RGBA\", b\"\\x08\\x06\"),\n}\n\n\ndef putchunk(fp, cid, *data):\n    \"\"\"Write a PNG chunk (including CRC field)\"\"\"\n\n    data = b\"\".join(data)\n\n    fp.write(o32(len(data)) + cid)\n    fp.write(data)\n    crc = _crc32(data, _crc32(cid))\n    fp.write(o32(crc))\n\n\nclass _idat:\n    # wrap output from the encoder in IDAT chunks\n\n    def __init__(self, fp, chunk):\n        self.fp = fp\n        self.chunk = chunk\n\n    def write(self, data):\n        self.chunk(self.fp, b\"IDAT\", data)\n\n\nclass _fdat:\n    # wrap encoder output in fdAT chunks\n\n    def __init__(self, fp, chunk, seq_num):\n        self.fp = fp\n        self.chunk = chunk\n        self.seq_num = seq_num\n\n    def write(self, data):\n        self.chunk(self.fp, b\"fdAT\", o32(self.seq_num), data)\n        self.seq_num += 1\n\n\ndef _write_multiple_frames(im, fp, chunk, rawmode):\n    default_image = im.encoderinfo.get(\"default_image\", im.info.get(\"default_image\"))\n    duration = im.encoderinfo.get(\"duration\", im.info.get(\"duration\", 0))\n    loop = im.encoderinfo.get(\"loop\", im.info.get(\"loop\", 0))\n    disposal = im.encoderinfo.get(\"disposal\", im.info.get(\"disposal\"))\n    blend = im.encoderinfo.get(\"blend\", im.info.get(\"blend\"))\n\n    if default_image:\n        chain = itertools.chain(im.encoderinfo.get(\"append_images\", []))\n    else:\n        chain = itertools.chain([im], im.encoderinfo.get(\"append_images\", []))\n\n    im_frames = []\n    frame_count = 0\n    for im_seq in chain:\n        for im_frame in ImageSequence.Iterator(im_seq):\n            im_frame = im_frame.copy()\n            if im_frame.mode != im.mode:\n                if im.mode == \"P\":\n                    im_frame = im_frame.convert(im.mode, palette=im.palette)\n                else:\n                    im_frame = im_frame.convert(im.mode)\n            encoderinfo = im.encoderinfo.copy()\n            if isinstance(duration, (list, tuple)):\n                encoderinfo[\"duration\"] = duration[frame_count]\n            if isinstance(disposal, (list, tuple)):\n                encoderinfo[\"disposal\"] = disposal[frame_count]\n            if isinstance(blend, (list, tuple)):\n                encoderinfo[\"blend\"] = blend[frame_count]\n            frame_count += 1\n\n            if im_frames:\n                previous = im_frames[-1]\n                prev_disposal = previous[\"encoderinfo\"].get(\"disposal\")\n                prev_blend = previous[\"encoderinfo\"].get(\"blend\")\n                if prev_disposal == APNG_DISPOSE_OP_PREVIOUS and len(im_frames) < 2:\n                    prev_disposal == APNG_DISPOSE_OP_BACKGROUND\n\n                if prev_disposal == APNG_DISPOSE_OP_BACKGROUND:\n                    base_im = previous[\"im\"]\n                    dispose = Image.core.fill(\"RGBA\", im.size, (0, 0, 0, 0))\n                    bbox = previous[\"bbox\"]\n                    if bbox:\n                        dispose = dispose.crop(bbox)\n                    else:\n                        bbox = (0, 0) + im.size\n                    base_im.paste(dispose, bbox)\n                elif prev_disposal == APNG_DISPOSE_OP_PREVIOUS:\n                    base_im = im_frames[-2][\"im\"]\n                else:\n                    base_im = previous[\"im\"]\n                delta = ImageChops.subtract_modulo(im_frame, base_im)\n                bbox = delta.getbbox()\n                if (\n                    not bbox\n                    and prev_disposal == encoderinfo.get(\"disposal\")\n                    and prev_blend == encoderinfo.get(\"blend\")\n                ):\n                    duration = encoderinfo.get(\"duration\", 0)\n                    if duration:\n                        if \"duration\" in previous[\"encoderinfo\"]:\n                            previous[\"encoderinfo\"][\"duration\"] += duration\n                        else:\n                            previous[\"encoderinfo\"][\"duration\"] = duration\n                    continue\n            else:\n                bbox = None\n            im_frames.append({\"im\": im_frame, \"bbox\": bbox, \"encoderinfo\": encoderinfo})\n\n    # animation control\n    chunk(\n        fp, b\"acTL\", o32(len(im_frames)), o32(loop),  # 0: num_frames  # 4: num_plays\n    )\n\n    # default image IDAT (if it exists)\n    if default_image:\n        ImageFile._save(im, _idat(fp, chunk), [(\"zip\", (0, 0) + im.size, 0, rawmode)])\n\n    seq_num = 0\n    for frame, frame_data in enumerate(im_frames):\n        im_frame = frame_data[\"im\"]\n        if not frame_data[\"bbox\"]:\n            bbox = (0, 0) + im_frame.size\n        else:\n            bbox = frame_data[\"bbox\"]\n            im_frame = im_frame.crop(bbox)\n        size = im_frame.size\n        duration = int(round(frame_data[\"encoderinfo\"].get(\"duration\", 0)))\n        disposal = frame_data[\"encoderinfo\"].get(\"disposal\", APNG_DISPOSE_OP_NONE)\n        blend = frame_data[\"encoderinfo\"].get(\"blend\", APNG_BLEND_OP_SOURCE)\n        # frame control\n        chunk(\n            fp,\n            b\"fcTL\",\n            o32(seq_num),  # sequence_number\n            o32(size[0]),  # width\n            o32(size[1]),  # height\n            o32(bbox[0]),  # x_offset\n            o32(bbox[1]),  # y_offset\n            o16(duration),  # delay_numerator\n            o16(1000),  # delay_denominator\n            o8(disposal),  # dispose_op\n            o8(blend),  # blend_op\n        )\n        seq_num += 1\n        # frame data\n        if frame == 0 and not default_image:\n            # first frame must be in IDAT chunks for backwards compatibility\n            ImageFile._save(\n                im_frame,\n                _idat(fp, chunk),\n                [(\"zip\", (0, 0) + im_frame.size, 0, rawmode)],\n            )\n        else:\n            fdat_chunks = _fdat(fp, chunk, seq_num)\n            ImageFile._save(\n                im_frame, fdat_chunks, [(\"zip\", (0, 0) + im_frame.size, 0, rawmode)],\n            )\n            seq_num = fdat_chunks.seq_num\n\n\ndef _save_all(im, fp, filename):\n    _save(im, fp, filename, save_all=True)\n\n\ndef _save(im, fp, filename, chunk=putchunk, save_all=False):\n    # save an image to disk (called by the save method)\n\n    mode = im.mode\n\n    if mode == \"P\":\n\n        #\n        # attempt to minimize storage requirements for palette images\n        if \"bits\" in im.encoderinfo:\n            # number of bits specified by user\n            colors = 1 << im.encoderinfo[\"bits\"]\n        else:\n            # check palette contents\n            if im.palette:\n                colors = max(min(len(im.palette.getdata()[1]) // 3, 256), 2)\n            else:\n                colors = 256\n\n        if colors <= 2:\n            bits = 1\n        elif colors <= 4:\n            bits = 2\n        elif colors <= 16:\n            bits = 4\n        else:\n            bits = 8\n        if bits != 8:\n            mode = \"%s;%d\" % (mode, bits)\n\n    # encoder options\n    im.encoderconfig = (\n        im.encoderinfo.get(\"optimize\", False),\n        im.encoderinfo.get(\"compress_level\", -1),\n        im.encoderinfo.get(\"compress_type\", -1),\n        im.encoderinfo.get(\"dictionary\", b\"\"),\n    )\n\n    # get the corresponding PNG mode\n    try:\n        rawmode, mode = _OUTMODES[mode]\n    except KeyError:\n        raise OSError(\"cannot write mode %s as PNG\" % mode)\n\n    #\n    # write minimal PNG file\n\n    fp.write(_MAGIC)\n\n    chunk(\n        fp,\n        b\"IHDR\",\n        o32(im.size[0]),  # 0: size\n        o32(im.size[1]),\n        mode,  # 8: depth/type\n        b\"\\0\",  # 10: compression\n        b\"\\0\",  # 11: filter category\n        b\"\\0\",  # 12: interlace flag\n    )\n\n    chunks = [b\"cHRM\", b\"gAMA\", b\"sBIT\", b\"sRGB\", b\"tIME\"]\n\n    icc = im.encoderinfo.get(\"icc_profile\", im.info.get(\"icc_profile\"))\n    if icc:\n        # ICC profile\n        # according to PNG spec, the iCCP chunk contains:\n        # Profile name  1-79 bytes (character string)\n        # Null separator        1 byte (null character)\n        # Compression method    1 byte (0)\n        # Compressed profile    n bytes (zlib with deflate compression)\n        name = b\"ICC Profile\"\n        data = name + b\"\\0\\0\" + zlib.compress(icc)\n        chunk(fp, b\"iCCP\", data)\n\n        # You must either have sRGB or iCCP.\n        # Disallow sRGB chunks when an iCCP-chunk has been emitted.\n        chunks.remove(b\"sRGB\")\n\n    info = im.encoderinfo.get(\"pnginfo\")\n    if info:\n        chunks_multiple_allowed = [b\"sPLT\", b\"iTXt\", b\"tEXt\", b\"zTXt\"]\n        for cid, data in info.chunks:\n            if cid in chunks:\n                chunks.remove(cid)\n                chunk(fp, cid, data)\n            elif cid in chunks_multiple_allowed:\n                chunk(fp, cid, data)\n\n    if im.mode == \"P\":\n        palette_byte_number = (2 ** bits) * 3\n        palette_bytes = im.im.getpalette(\"RGB\")[:palette_byte_number]\n        while len(palette_bytes) < palette_byte_number:\n            palette_bytes += b\"\\0\"\n        chunk(fp, b\"PLTE\", palette_bytes)\n\n    transparency = im.encoderinfo.get(\"transparency\", im.info.get(\"transparency\", None))\n\n    if transparency or transparency == 0:\n        if im.mode == \"P\":\n            # limit to actual palette size\n            alpha_bytes = 2 ** bits\n            if isinstance(transparency, bytes):\n                chunk(fp, b\"tRNS\", transparency[:alpha_bytes])\n            else:\n                transparency = max(0, min(255, transparency))\n                alpha = b\"\\xFF\" * transparency + b\"\\0\"\n                chunk(fp, b\"tRNS\", alpha[:alpha_bytes])\n        elif im.mode in (\"1\", \"L\", \"I\"):\n            transparency = max(0, min(65535, transparency))\n            chunk(fp, b\"tRNS\", o16(transparency))\n        elif im.mode == \"RGB\":\n            red, green, blue = transparency\n            chunk(fp, b\"tRNS\", o16(red) + o16(green) + o16(blue))\n        else:\n            if \"transparency\" in im.encoderinfo:\n                # don't bother with transparency if it's an RGBA\n                # and it's in the info dict. It's probably just stale.\n                raise OSError(\"cannot use transparency for this mode\")\n    else:\n        if im.mode == \"P\" and im.im.getpalettemode() == \"RGBA\":\n            alpha = im.im.getpalette(\"RGBA\", \"A\")\n            alpha_bytes = 2 ** bits\n            chunk(fp, b\"tRNS\", alpha[:alpha_bytes])\n\n    dpi = im.encoderinfo.get(\"dpi\")\n    if dpi:\n        chunk(\n            fp,\n            b\"pHYs\",\n            o32(int(dpi[0] / 0.0254 + 0.5)),\n            o32(int(dpi[1] / 0.0254 + 0.5)),\n            b\"\\x01\",\n        )\n\n    if info:\n        chunks = [b\"bKGD\", b\"hIST\"]\n        for cid, data in info.chunks:\n            if cid in chunks:\n                chunks.remove(cid)\n                chunk(fp, cid, data)\n\n    exif = im.encoderinfo.get(\"exif\", im.info.get(\"exif\"))\n    if exif:\n        if isinstance(exif, Image.Exif):\n            exif = exif.tobytes(8)\n        if exif.startswith(b\"Exif\\x00\\x00\"):\n            exif = exif[6:]\n        chunk(fp, b\"eXIf\", exif)\n\n    if save_all:\n        _write_multiple_frames(im, fp, chunk, rawmode)\n    else:\n        ImageFile._save(im, _idat(fp, chunk), [(\"zip\", (0, 0) + im.size, 0, rawmode)])\n\n    chunk(fp, b\"IEND\", b\"\")\n\n    if hasattr(fp, \"flush\"):\n        fp.flush()\n\n\n# --------------------------------------------------------------------\n# PNG chunk converter\n\n\ndef getchunks(im, **params):\n    \"\"\"Return a list of PNG chunks representing this image.\"\"\"\n\n    class collector:\n        data = []\n\n        def write(self, data):\n            pass\n\n        def append(self, chunk):\n            self.data.append(chunk)\n\n    def append(fp, cid, *data):\n        data = b\"\".join(data)\n        crc = o32(_crc32(data, _crc32(cid)))\n        fp.append((cid, data, crc))\n\n    fp = collector()\n\n    try:\n        im.encoderinfo = params\n        _save(im, fp, None, append)\n    finally:\n        del im.encoderinfo\n\n    return fp.data\n\n\n# --------------------------------------------------------------------\n# Registry\n\nImage.register_open(PngImageFile.format, PngImageFile, _accept)\nImage.register_save(PngImageFile.format, _save)\nImage.register_save_all(PngImageFile.format, _save_all)\n\nImage.register_extensions(PngImageFile.format, [\".png\", \".apng\"])\n\nImage.register_mime(PngImageFile.format, \"image/png\")\n",
            "header": {
                "file": {
                    "path": "src/PIL/PngImagePlugin.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "398eade3c",
                "new_commit_hash": "dd3673b53",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/src/PIL/PngImagePlugin.py"
            },
            "plus_file": {
                "path": "b/src/PIL/PngImagePlugin.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 717,
                            "length": 7
                        },
                        "new_range": {
                            "start": 717,
                            "length": 7
                        },
                        "section": "class PngImageFile(ImageFile.ImageFile):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    @property",
                                "type": "context"
                            },
                            {
                                "content": "    def is_animated(self):",
                                "type": "context"
                            },
                            {
                                "content": "        return self._n_frames is not None",
                                "type": "deleted"
                            },
                            {
                                "content": "        return self._n_frames is not None and self._n_frames > 1",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def verify(self):",
                                "type": "context"
                            },
                            {
                                "content": "        \"\"\"Verify PNG file\"\"\"",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "src/PIL/PngImagePlugin.py",
                            "type": "method",
                            "name": "PngImageFile.is_animated",
                            "content": "class PngImageFile(ImageFile.ImageFile):\n\n    format = \"PNG\"\n    format_description = \"Portable network graphics\"\n\n    def _open(self):\n\n        if self.fp.read(8) != _MAGIC:\n            raise SyntaxError(\"not a PNG file\")\n        self.__fp = self.fp\n\n        #\n        # Parse headers up to the first IDAT or fDAT chunk\n\n        self.png = PngStream(self.fp)\n\n        while True:\n\n            #\n            # get next chunk\n\n            cid, pos, length = self.png.read()\n\n            try:\n                s = self.png.call(cid, pos, length)\n            except EOFError:\n                break\n            except AttributeError:\n                logger.debug(\"%r %s %s (unknown)\", cid, pos, length)\n                s = ImageFile._safe_read(self.fp, length)\n\n            self.png.crc(cid, s)\n\n        #\n        # Copy relevant attributes from the PngStream.  An alternative\n        # would be to let the PngStream class modify these attributes\n        # directly, but that introduces circular references which are\n        # difficult to break if things go wrong in the decoder...\n        # (believe me, I've tried ;-)\n\n        self.mode = self.png.im_mode\n        self._size = self.png.im_size\n        self.info = self.png.im_info\n        self._text = None\n        self.tile = self.png.im_tile\n        self.custom_mimetype = self.png.im_custom_mimetype\n        self._n_frames = self.png.im_n_frames\n        self.default_image = self.info.get(\"default_image\", False)\n\n        if self.png.im_palette:\n            rawmode, data = self.png.im_palette\n            self.palette = ImagePalette.raw(rawmode, data)\n\n        if cid == b\"fdAT\":\n            self.__prepare_idat = length - 4\n        else:\n            self.__prepare_idat = length  # used by load_prepare()\n\n        if self._n_frames is not None:\n            self._close_exclusive_fp_after_loading = False\n            self.png.save_rewind()\n            self.__rewind_idat = self.__prepare_idat\n            self.__rewind = self.__fp.tell()\n            if self.default_image:\n                # IDAT chunk contains default image and not first animation frame\n                self._n_frames += 1\n            self._seek(0)\n\n    @property\n    def text(self):\n        # experimental\n        if self._text is None:\n            # iTxt, tEXt and zTXt chunks may appear at the end of the file\n            # So load the file to ensure that they are read\n            if self.is_animated:\n                frame = self.__frame\n                # for APNG, seek to the final frame before loading\n                self.seek(self.n_frames - 1)\n            self.load()\n            if self.is_animated:\n                self.seek(frame)\n        return self._text\n\n    @property\n    def n_frames(self):\n        if self._n_frames is None:\n            return 1\n        return self._n_frames\n\n    @property\n    def is_animated(self):\n        return self._n_frames is not None\n\n    def verify(self):\n        \"\"\"Verify PNG file\"\"\"\n\n        if self.fp is None:\n            raise RuntimeError(\"verify must be called directly after open\")\n\n        # back up to beginning of IDAT block\n        self.fp.seek(self.tile[0][2] - 8)\n\n        self.png.verify()\n        self.png.close()\n\n        if self._exclusive_fp:\n            self.fp.close()\n        self.fp = None\n\n    def seek(self, frame):\n        if not self._seek_check(frame):\n            return\n        if frame < self.__frame:\n            self._seek(0, True)\n\n        last_frame = self.__frame\n        for f in range(self.__frame + 1, frame + 1):\n            try:\n                self._seek(f)\n            except EOFError:\n                self.seek(last_frame)\n                raise EOFError(\"no more images in APNG file\")\n\n    def _seek(self, frame, rewind=False):\n        if frame == 0:\n            if rewind:\n                self.__fp.seek(self.__rewind)\n                self.png.rewind()\n                self.__prepare_idat = self.__rewind_idat\n                self.im = None\n                if self.pyaccess:\n                    self.pyaccess = None\n                self.info = self.png.im_info\n                self.tile = self.png.im_tile\n                self.fp = self.__fp\n            self._prev_im = None\n            self.dispose = None\n            self.default_image = self.info.get(\"default_image\", False)\n            self.dispose_op = self.info.get(\"disposal\")\n            self.blend_op = self.info.get(\"blend\")\n            self.dispose_extent = self.info.get(\"bbox\")\n            self.__frame = 0\n            return\n        else:\n            if frame != self.__frame + 1:\n                raise ValueError(\"cannot seek to frame %d\" % frame)\n\n        # ensure previous frame was loaded\n        self.load()\n\n        self.fp = self.__fp\n\n        # advance to the next frame\n        if self.__prepare_idat:\n            ImageFile._safe_read(self.fp, self.__prepare_idat)\n            self.__prepare_idat = 0\n        frame_start = False\n        while True:\n            self.fp.read(4)  # CRC\n\n            try:\n                cid, pos, length = self.png.read()\n            except (struct.error, SyntaxError):\n                break\n\n            if cid == b\"IEND\":\n                raise EOFError(\"No more images in APNG file\")\n            if cid == b\"fcTL\":\n                if frame_start:\n                    # there must be at least one fdAT chunk between fcTL chunks\n                    raise SyntaxError(\"APNG missing frame data\")\n                frame_start = True\n\n            try:\n                self.png.call(cid, pos, length)\n            except UnicodeDecodeError:\n                break\n            except EOFError:\n                if cid == b\"fdAT\":\n                    length -= 4\n                    if frame_start:\n                        self.__prepare_idat = length\n                        break\n                ImageFile._safe_read(self.fp, length)\n            except AttributeError:\n                logger.debug(\"%r %s %s (unknown)\", cid, pos, length)\n                ImageFile._safe_read(self.fp, length)\n\n        self.__frame = frame\n        self.tile = self.png.im_tile\n        self.dispose_op = self.info.get(\"disposal\")\n        self.blend_op = self.info.get(\"blend\")\n        self.dispose_extent = self.info.get(\"bbox\")\n\n        if not self.tile:\n            raise EOFError\n\n    def tell(self):\n        return self.__frame\n\n    def load_prepare(self):\n        \"\"\"internal: prepare to read PNG file\"\"\"\n\n        if self.info.get(\"interlace\"):\n            self.decoderconfig = self.decoderconfig + (1,)\n\n        self.__idat = self.__prepare_idat  # used by load_read()\n        ImageFile.ImageFile.load_prepare(self)\n\n    def load_read(self, read_bytes):\n        \"\"\"internal: read more image data\"\"\"\n\n        while self.__idat == 0:\n            # end of chunk, skip forward to next one\n\n            self.fp.read(4)  # CRC\n\n            cid, pos, length = self.png.read()\n\n            if cid not in [b\"IDAT\", b\"DDAT\", b\"fdAT\"]:\n                self.png.push(cid, pos, length)\n                return b\"\"\n\n            if cid == b\"fdAT\":\n                try:\n                    self.png.call(cid, pos, length)\n                except EOFError:\n                    pass\n                self.__idat = length - 4  # sequence_num has already been read\n            else:\n                self.__idat = length  # empty chunks are allowed\n\n        # read more data from this chunk\n        if read_bytes <= 0:\n            read_bytes = self.__idat\n        else:\n            read_bytes = min(read_bytes, self.__idat)\n\n        self.__idat = self.__idat - read_bytes\n\n        return self.fp.read(read_bytes)\n\n    def load_end(self):\n        \"\"\"internal: finished reading image data\"\"\"\n        while True:\n            self.fp.read(4)  # CRC\n\n            try:\n                cid, pos, length = self.png.read()\n            except (struct.error, SyntaxError):\n                break\n\n            if cid == b\"IEND\":\n                break\n            elif cid == b\"fcTL\" and self.is_animated:\n                # start of the next frame, stop reading\n                self.__prepare_idat = 0\n                self.png.push(cid, pos, length)\n                break\n\n            try:\n                self.png.call(cid, pos, length)\n            except UnicodeDecodeError:\n                break\n            except EOFError:\n                if cid == b\"fdAT\":\n                    length -= 4\n                ImageFile._safe_read(self.fp, length)\n            except AttributeError:\n                logger.debug(\"%r %s %s (unknown)\", cid, pos, length)\n                ImageFile._safe_read(self.fp, length)\n        self._text = self.png.im_text\n        if not self.is_animated:\n            self.png.close()\n            self.png = None\n        else:\n            # setup frame disposal (actual disposal done when needed in _seek())\n            if self._prev_im is None and self.dispose_op == APNG_DISPOSE_OP_PREVIOUS:\n                self.dispose_op = APNG_DISPOSE_OP_BACKGROUND\n\n            if self.dispose_op == APNG_DISPOSE_OP_PREVIOUS:\n                dispose = self._prev_im.copy()\n                dispose = self._crop(dispose, self.dispose_extent)\n            elif self.dispose_op == APNG_DISPOSE_OP_BACKGROUND:\n                dispose = Image.core.fill(\"RGBA\", self.size, (0, 0, 0, 0))\n                dispose = self._crop(dispose, self.dispose_extent)\n            else:\n                dispose = None\n\n            if self._prev_im and self.blend_op == APNG_BLEND_OP_OVER:\n                updated = self._crop(self.im, self.dispose_extent)\n                self._prev_im.paste(\n                    updated, self.dispose_extent, updated.convert(\"RGBA\")\n                )\n                self.im = self._prev_im\n                if self.pyaccess:\n                    self.pyaccess = None\n            self._prev_im = self.im.copy()\n\n            if dispose:\n                self._prev_im.paste(dispose, self.dispose_extent)\n\n    def _getexif(self):\n        if \"exif\" not in self.info:\n            self.load()\n        if \"exif\" not in self.info:\n            return None\n        return dict(self.getexif())\n\n    def getexif(self):\n        if \"exif\" not in self.info:\n            self.load()\n        return ImageFile.ImageFile.getexif(self)\n\n    def _close__fp(self):\n        try:\n            if self.__fp != self.fp:\n                self.__fp.close()\n        except AttributeError:\n            pass\n        finally:\n            self.__fp = None",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 719,
                            "end_lineno": 720,
                            "parent": {
                                "file_name": "src/PIL/PngImagePlugin.py",
                                "type": "class",
                                "name": "PngImageFile",
                                "content": "class PngImageFile(ImageFile.ImageFile):\n\n    format = \"PNG\"\n    format_description = \"Portable network graphics\"\n\n    def _open(self):\n\n        if self.fp.read(8) != _MAGIC:\n            raise SyntaxError(\"not a PNG file\")\n        self.__fp = self.fp\n\n        #\n        # Parse headers up to the first IDAT or fDAT chunk\n\n        self.png = PngStream(self.fp)\n\n        while True:\n\n            #\n            # get next chunk\n\n            cid, pos, length = self.png.read()\n\n            try:\n                s = self.png.call(cid, pos, length)\n            except EOFError:\n                break\n            except AttributeError:\n                logger.debug(\"%r %s %s (unknown)\", cid, pos, length)\n                s = ImageFile._safe_read(self.fp, length)\n\n            self.png.crc(cid, s)\n\n        #\n        # Copy relevant attributes from the PngStream.  An alternative\n        # would be to let the PngStream class modify these attributes\n        # directly, but that introduces circular references which are\n        # difficult to break if things go wrong in the decoder...\n        # (believe me, I've tried ;-)\n\n        self.mode = self.png.im_mode\n        self._size = self.png.im_size\n        self.info = self.png.im_info\n        self._text = None\n        self.tile = self.png.im_tile\n        self.custom_mimetype = self.png.im_custom_mimetype\n        self._n_frames = self.png.im_n_frames\n        self.default_image = self.info.get(\"default_image\", False)\n\n        if self.png.im_palette:\n            rawmode, data = self.png.im_palette\n            self.palette = ImagePalette.raw(rawmode, data)\n\n        if cid == b\"fdAT\":\n            self.__prepare_idat = length - 4\n        else:\n            self.__prepare_idat = length  # used by load_prepare()\n\n        if self._n_frames is not None:\n            self._close_exclusive_fp_after_loading = False\n            self.png.save_rewind()\n            self.__rewind_idat = self.__prepare_idat\n            self.__rewind = self.__fp.tell()\n            if self.default_image:\n                # IDAT chunk contains default image and not first animation frame\n                self._n_frames += 1\n            self._seek(0)\n\n    @property\n    def text(self):\n        # experimental\n        if self._text is None:\n            # iTxt, tEXt and zTXt chunks may appear at the end of the file\n            # So load the file to ensure that they are read\n            if self.is_animated:\n                frame = self.__frame\n                # for APNG, seek to the final frame before loading\n                self.seek(self.n_frames - 1)\n            self.load()\n            if self.is_animated:\n                self.seek(frame)\n        return self._text\n\n    @property\n    def n_frames(self):\n        if self._n_frames is None:\n            return 1\n        return self._n_frames\n\n    @property\n    def is_animated(self):\n        return self._n_frames is not None\n\n    def verify(self):\n        \"\"\"Verify PNG file\"\"\"\n\n        if self.fp is None:\n            raise RuntimeError(\"verify must be called directly after open\")\n\n        # back up to beginning of IDAT block\n        self.fp.seek(self.tile[0][2] - 8)\n\n        self.png.verify()\n        self.png.close()\n\n        if self._exclusive_fp:\n            self.fp.close()\n        self.fp = None\n\n    def seek(self, frame):\n        if not self._seek_check(frame):\n            return\n        if frame < self.__frame:\n            self._seek(0, True)\n\n        last_frame = self.__frame\n        for f in range(self.__frame + 1, frame + 1):\n            try:\n                self._seek(f)\n            except EOFError:\n                self.seek(last_frame)\n                raise EOFError(\"no more images in APNG file\")\n\n    def _seek(self, frame, rewind=False):\n        if frame == 0:\n            if rewind:\n                self.__fp.seek(self.__rewind)\n                self.png.rewind()\n                self.__prepare_idat = self.__rewind_idat\n                self.im = None\n                if self.pyaccess:\n                    self.pyaccess = None\n                self.info = self.png.im_info\n                self.tile = self.png.im_tile\n                self.fp = self.__fp\n            self._prev_im = None\n            self.dispose = None\n            self.default_image = self.info.get(\"default_image\", False)\n            self.dispose_op = self.info.get(\"disposal\")\n            self.blend_op = self.info.get(\"blend\")\n            self.dispose_extent = self.info.get(\"bbox\")\n            self.__frame = 0\n            return\n        else:\n            if frame != self.__frame + 1:\n                raise ValueError(\"cannot seek to frame %d\" % frame)\n\n        # ensure previous frame was loaded\n        self.load()\n\n        self.fp = self.__fp\n\n        # advance to the next frame\n        if self.__prepare_idat:\n            ImageFile._safe_read(self.fp, self.__prepare_idat)\n            self.__prepare_idat = 0\n        frame_start = False\n        while True:\n            self.fp.read(4)  # CRC\n\n            try:\n                cid, pos, length = self.png.read()\n            except (struct.error, SyntaxError):\n                break\n\n            if cid == b\"IEND\":\n                raise EOFError(\"No more images in APNG file\")\n            if cid == b\"fcTL\":\n                if frame_start:\n                    # there must be at least one fdAT chunk between fcTL chunks\n                    raise SyntaxError(\"APNG missing frame data\")\n                frame_start = True\n\n            try:\n                self.png.call(cid, pos, length)\n            except UnicodeDecodeError:\n                break\n            except EOFError:\n                if cid == b\"fdAT\":\n                    length -= 4\n                    if frame_start:\n                        self.__prepare_idat = length\n                        break\n                ImageFile._safe_read(self.fp, length)\n            except AttributeError:\n                logger.debug(\"%r %s %s (unknown)\", cid, pos, length)\n                ImageFile._safe_read(self.fp, length)\n\n        self.__frame = frame\n        self.tile = self.png.im_tile\n        self.dispose_op = self.info.get(\"disposal\")\n        self.blend_op = self.info.get(\"blend\")\n        self.dispose_extent = self.info.get(\"bbox\")\n\n        if not self.tile:\n            raise EOFError\n\n    def tell(self):\n        return self.__frame\n\n    def load_prepare(self):\n        \"\"\"internal: prepare to read PNG file\"\"\"\n\n        if self.info.get(\"interlace\"):\n            self.decoderconfig = self.decoderconfig + (1,)\n\n        self.__idat = self.__prepare_idat  # used by load_read()\n        ImageFile.ImageFile.load_prepare(self)\n\n    def load_read(self, read_bytes):\n        \"\"\"internal: read more image data\"\"\"\n\n        while self.__idat == 0:\n            # end of chunk, skip forward to next one\n\n            self.fp.read(4)  # CRC\n\n            cid, pos, length = self.png.read()\n\n            if cid not in [b\"IDAT\", b\"DDAT\", b\"fdAT\"]:\n                self.png.push(cid, pos, length)\n                return b\"\"\n\n            if cid == b\"fdAT\":\n                try:\n                    self.png.call(cid, pos, length)\n                except EOFError:\n                    pass\n                self.__idat = length - 4  # sequence_num has already been read\n            else:\n                self.__idat = length  # empty chunks are allowed\n\n        # read more data from this chunk\n        if read_bytes <= 0:\n            read_bytes = self.__idat\n        else:\n            read_bytes = min(read_bytes, self.__idat)\n\n        self.__idat = self.__idat - read_bytes\n\n        return self.fp.read(read_bytes)\n\n    def load_end(self):\n        \"\"\"internal: finished reading image data\"\"\"\n        while True:\n            self.fp.read(4)  # CRC\n\n            try:\n                cid, pos, length = self.png.read()\n            except (struct.error, SyntaxError):\n                break\n\n            if cid == b\"IEND\":\n                break\n            elif cid == b\"fcTL\" and self.is_animated:\n                # start of the next frame, stop reading\n                self.__prepare_idat = 0\n                self.png.push(cid, pos, length)\n                break\n\n            try:\n                self.png.call(cid, pos, length)\n            except UnicodeDecodeError:\n                break\n            except EOFError:\n                if cid == b\"fdAT\":\n                    length -= 4\n                ImageFile._safe_read(self.fp, length)\n            except AttributeError:\n                logger.debug(\"%r %s %s (unknown)\", cid, pos, length)\n                ImageFile._safe_read(self.fp, length)\n        self._text = self.png.im_text\n        if not self.is_animated:\n            self.png.close()\n            self.png = None\n        else:\n            # setup frame disposal (actual disposal done when needed in _seek())\n            if self._prev_im is None and self.dispose_op == APNG_DISPOSE_OP_PREVIOUS:\n                self.dispose_op = APNG_DISPOSE_OP_BACKGROUND\n\n            if self.dispose_op == APNG_DISPOSE_OP_PREVIOUS:\n                dispose = self._prev_im.copy()\n                dispose = self._crop(dispose, self.dispose_extent)\n            elif self.dispose_op == APNG_DISPOSE_OP_BACKGROUND:\n                dispose = Image.core.fill(\"RGBA\", self.size, (0, 0, 0, 0))\n                dispose = self._crop(dispose, self.dispose_extent)\n            else:\n                dispose = None\n\n            if self._prev_im and self.blend_op == APNG_BLEND_OP_OVER:\n                updated = self._crop(self.im, self.dispose_extent)\n                self._prev_im.paste(\n                    updated, self.dispose_extent, updated.convert(\"RGBA\")\n                )\n                self.im = self._prev_im\n                if self.pyaccess:\n                    self.pyaccess = None\n            self._prev_im = self.im.copy()\n\n            if dispose:\n                self._prev_im.paste(dispose, self.dispose_extent)\n\n    def _getexif(self):\n        if \"exif\" not in self.info:\n            self.load()\n        if \"exif\" not in self.info:\n            return None\n        return dict(self.getexif())\n\n    def getexif(self):\n        if \"exif\" not in self.info:\n            self.load()\n        return ImageFile.ImageFile.getexif(self)\n\n    def _close__fp(self):\n        try:\n            if self.__fp != self.fp:\n                self.__fp.close()\n        except AttributeError:\n            pass\n        finally:\n            self.__fp = None",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 629,
                                "end_lineno": 950,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "src/PIL/PngImagePlugin.py",
                            "type": "class",
                            "name": "PngImageFile",
                            "content": "class PngImageFile(ImageFile.ImageFile):\n\n    format = \"PNG\"\n    format_description = \"Portable network graphics\"\n\n    def _open(self):\n\n        if self.fp.read(8) != _MAGIC:\n            raise SyntaxError(\"not a PNG file\")\n        self.__fp = self.fp\n\n        #\n        # Parse headers up to the first IDAT or fDAT chunk\n\n        self.png = PngStream(self.fp)\n\n        while True:\n\n            #\n            # get next chunk\n\n            cid, pos, length = self.png.read()\n\n            try:\n                s = self.png.call(cid, pos, length)\n            except EOFError:\n                break\n            except AttributeError:\n                logger.debug(\"%r %s %s (unknown)\", cid, pos, length)\n                s = ImageFile._safe_read(self.fp, length)\n\n            self.png.crc(cid, s)\n\n        #\n        # Copy relevant attributes from the PngStream.  An alternative\n        # would be to let the PngStream class modify these attributes\n        # directly, but that introduces circular references which are\n        # difficult to break if things go wrong in the decoder...\n        # (believe me, I've tried ;-)\n\n        self.mode = self.png.im_mode\n        self._size = self.png.im_size\n        self.info = self.png.im_info\n        self._text = None\n        self.tile = self.png.im_tile\n        self.custom_mimetype = self.png.im_custom_mimetype\n        self._n_frames = self.png.im_n_frames\n        self.default_image = self.info.get(\"default_image\", False)\n\n        if self.png.im_palette:\n            rawmode, data = self.png.im_palette\n            self.palette = ImagePalette.raw(rawmode, data)\n\n        if cid == b\"fdAT\":\n            self.__prepare_idat = length - 4\n        else:\n            self.__prepare_idat = length  # used by load_prepare()\n\n        if self._n_frames is not None:\n            self._close_exclusive_fp_after_loading = False\n            self.png.save_rewind()\n            self.__rewind_idat = self.__prepare_idat\n            self.__rewind = self.__fp.tell()\n            if self.default_image:\n                # IDAT chunk contains default image and not first animation frame\n                self._n_frames += 1\n            self._seek(0)\n\n    @property\n    def text(self):\n        # experimental\n        if self._text is None:\n            # iTxt, tEXt and zTXt chunks may appear at the end of the file\n            # So load the file to ensure that they are read\n            if self.is_animated:\n                frame = self.__frame\n                # for APNG, seek to the final frame before loading\n                self.seek(self.n_frames - 1)\n            self.load()\n            if self.is_animated:\n                self.seek(frame)\n        return self._text\n\n    @property\n    def n_frames(self):\n        if self._n_frames is None:\n            return 1\n        return self._n_frames\n\n    @property\n    def is_animated(self):\n        return self._n_frames is not None\n\n    def verify(self):\n        \"\"\"Verify PNG file\"\"\"\n\n        if self.fp is None:\n            raise RuntimeError(\"verify must be called directly after open\")\n\n        # back up to beginning of IDAT block\n        self.fp.seek(self.tile[0][2] - 8)\n\n        self.png.verify()\n        self.png.close()\n\n        if self._exclusive_fp:\n            self.fp.close()\n        self.fp = None\n\n    def seek(self, frame):\n        if not self._seek_check(frame):\n            return\n        if frame < self.__frame:\n            self._seek(0, True)\n\n        last_frame = self.__frame\n        for f in range(self.__frame + 1, frame + 1):\n            try:\n                self._seek(f)\n            except EOFError:\n                self.seek(last_frame)\n                raise EOFError(\"no more images in APNG file\")\n\n    def _seek(self, frame, rewind=False):\n        if frame == 0:\n            if rewind:\n                self.__fp.seek(self.__rewind)\n                self.png.rewind()\n                self.__prepare_idat = self.__rewind_idat\n                self.im = None\n                if self.pyaccess:\n                    self.pyaccess = None\n                self.info = self.png.im_info\n                self.tile = self.png.im_tile\n                self.fp = self.__fp\n            self._prev_im = None\n            self.dispose = None\n            self.default_image = self.info.get(\"default_image\", False)\n            self.dispose_op = self.info.get(\"disposal\")\n            self.blend_op = self.info.get(\"blend\")\n            self.dispose_extent = self.info.get(\"bbox\")\n            self.__frame = 0\n            return\n        else:\n            if frame != self.__frame + 1:\n                raise ValueError(\"cannot seek to frame %d\" % frame)\n\n        # ensure previous frame was loaded\n        self.load()\n\n        self.fp = self.__fp\n\n        # advance to the next frame\n        if self.__prepare_idat:\n            ImageFile._safe_read(self.fp, self.__prepare_idat)\n            self.__prepare_idat = 0\n        frame_start = False\n        while True:\n            self.fp.read(4)  # CRC\n\n            try:\n                cid, pos, length = self.png.read()\n            except (struct.error, SyntaxError):\n                break\n\n            if cid == b\"IEND\":\n                raise EOFError(\"No more images in APNG file\")\n            if cid == b\"fcTL\":\n                if frame_start:\n                    # there must be at least one fdAT chunk between fcTL chunks\n                    raise SyntaxError(\"APNG missing frame data\")\n                frame_start = True\n\n            try:\n                self.png.call(cid, pos, length)\n            except UnicodeDecodeError:\n                break\n            except EOFError:\n                if cid == b\"fdAT\":\n                    length -= 4\n                    if frame_start:\n                        self.__prepare_idat = length\n                        break\n                ImageFile._safe_read(self.fp, length)\n            except AttributeError:\n                logger.debug(\"%r %s %s (unknown)\", cid, pos, length)\n                ImageFile._safe_read(self.fp, length)\n\n        self.__frame = frame\n        self.tile = self.png.im_tile\n        self.dispose_op = self.info.get(\"disposal\")\n        self.blend_op = self.info.get(\"blend\")\n        self.dispose_extent = self.info.get(\"bbox\")\n\n        if not self.tile:\n            raise EOFError\n\n    def tell(self):\n        return self.__frame\n\n    def load_prepare(self):\n        \"\"\"internal: prepare to read PNG file\"\"\"\n\n        if self.info.get(\"interlace\"):\n            self.decoderconfig = self.decoderconfig + (1,)\n\n        self.__idat = self.__prepare_idat  # used by load_read()\n        ImageFile.ImageFile.load_prepare(self)\n\n    def load_read(self, read_bytes):\n        \"\"\"internal: read more image data\"\"\"\n\n        while self.__idat == 0:\n            # end of chunk, skip forward to next one\n\n            self.fp.read(4)  # CRC\n\n            cid, pos, length = self.png.read()\n\n            if cid not in [b\"IDAT\", b\"DDAT\", b\"fdAT\"]:\n                self.png.push(cid, pos, length)\n                return b\"\"\n\n            if cid == b\"fdAT\":\n                try:\n                    self.png.call(cid, pos, length)\n                except EOFError:\n                    pass\n                self.__idat = length - 4  # sequence_num has already been read\n            else:\n                self.__idat = length  # empty chunks are allowed\n\n        # read more data from this chunk\n        if read_bytes <= 0:\n            read_bytes = self.__idat\n        else:\n            read_bytes = min(read_bytes, self.__idat)\n\n        self.__idat = self.__idat - read_bytes\n\n        return self.fp.read(read_bytes)\n\n    def load_end(self):\n        \"\"\"internal: finished reading image data\"\"\"\n        while True:\n            self.fp.read(4)  # CRC\n\n            try:\n                cid, pos, length = self.png.read()\n            except (struct.error, SyntaxError):\n                break\n\n            if cid == b\"IEND\":\n                break\n            elif cid == b\"fcTL\" and self.is_animated:\n                # start of the next frame, stop reading\n                self.__prepare_idat = 0\n                self.png.push(cid, pos, length)\n                break\n\n            try:\n                self.png.call(cid, pos, length)\n            except UnicodeDecodeError:\n                break\n            except EOFError:\n                if cid == b\"fdAT\":\n                    length -= 4\n                ImageFile._safe_read(self.fp, length)\n            except AttributeError:\n                logger.debug(\"%r %s %s (unknown)\", cid, pos, length)\n                ImageFile._safe_read(self.fp, length)\n        self._text = self.png.im_text\n        if not self.is_animated:\n            self.png.close()\n            self.png = None\n        else:\n            # setup frame disposal (actual disposal done when needed in _seek())\n            if self._prev_im is None and self.dispose_op == APNG_DISPOSE_OP_PREVIOUS:\n                self.dispose_op = APNG_DISPOSE_OP_BACKGROUND\n\n            if self.dispose_op == APNG_DISPOSE_OP_PREVIOUS:\n                dispose = self._prev_im.copy()\n                dispose = self._crop(dispose, self.dispose_extent)\n            elif self.dispose_op == APNG_DISPOSE_OP_BACKGROUND:\n                dispose = Image.core.fill(\"RGBA\", self.size, (0, 0, 0, 0))\n                dispose = self._crop(dispose, self.dispose_extent)\n            else:\n                dispose = None\n\n            if self._prev_im and self.blend_op == APNG_BLEND_OP_OVER:\n                updated = self._crop(self.im, self.dispose_extent)\n                self._prev_im.paste(\n                    updated, self.dispose_extent, updated.convert(\"RGBA\")\n                )\n                self.im = self._prev_im\n                if self.pyaccess:\n                    self.pyaccess = None\n            self._prev_im = self.im.copy()\n\n            if dispose:\n                self._prev_im.paste(dispose, self.dispose_extent)\n\n    def _getexif(self):\n        if \"exif\" not in self.info:\n            self.load()\n        if \"exif\" not in self.info:\n            return None\n        return dict(self.getexif())\n\n    def getexif(self):\n        if \"exif\" not in self.info:\n            self.load()\n        return ImageFile.ImageFile.getexif(self)\n\n    def _close__fp(self):\n        try:\n            if self.__fp != self.fp:\n                self.__fp.close()\n        except AttributeError:\n            pass\n        finally:\n            self.__fp = None",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 629,
                            "end_lineno": 950,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "9b72f0513c89d448e9bdeb4fd11dc8cbc37246d5^",
    "new_commit_hash": "9b72f0513c89d448e9bdeb4fd11dc8cbc37246d5",
    "commit_message": "Adjust is_animated behavior\n\n- Make is_animated APNG behavior consistent with other Pillow formats\n- is_animated will be true when n_frames is greater than 1 (for APNG\n  this depends on animation frame count + presence or absence of a\n  default image)",
    "commit_date": "2020-02-23T15:14:06+11:00",
    "metadata": {}
}
{
    "repo_name": "pillow",
    "new_commit_hash": "9b72f0513c89d448e9bdeb4fd11dc8cbc37246d5",
    "test_file_codes": [
        "from PIL import Image, ImageSequence, PngImagePlugin\n\nimport pytest\n\nfrom .helper import PillowTestCase\n\n\nclass TestFilePng(PillowTestCase):\n\n    # APNG browser support tests and fixtures via:\n    # https://philip.html5.org/tests/apng/tests.html\n    # (referenced from https://wiki.mozilla.org/APNG_Specification)\n    def test_apng_basic(self):\n        with Image.open(\"Tests/images/apng/single_frame.png\") as im:\n            self.assertFalse(im.is_animated)\n            self.assertEqual(im.n_frames, 1)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertIsNone(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/single_frame_default.png\") as im:\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.n_frames, 2)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertTrue(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (255, 0, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (255, 0, 0, 255))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n            # test out of bounds seek\n            with self.assertRaises(EOFError):\n                im.seek(2)\n\n            # test rewind support\n            im.seek(0)\n            self.assertEqual(im.getpixel((0, 0)), (255, 0, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (255, 0, 0, 255))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_fdat(self):\n        with Image.open(\"Tests/images/apng/split_fdat.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/split_fdat_zero_chunk.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_dispose(self):\n        with Image.open(\"Tests/images/apng/dispose_op_none.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background_final.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_final.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_first.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n    def test_apng_dispose_region(self):\n        with Image.open(\"Tests/images/apng/dispose_op_none_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\n            \"Tests/images/apng/dispose_op_background_before_region.png\"\n        ) as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_background_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 255, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/dispose_op_previous_region.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_blend(self):\n        with Image.open(\"Tests/images/apng/blend_op_source_solid.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/blend_op_source_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        with Image.open(\"Tests/images/apng/blend_op_source_near_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 2))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 2))\n\n        with Image.open(\"Tests/images/apng/blend_op_over.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/blend_op_over_near_transparent.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 97))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_chunk_order(self):\n        with Image.open(\"Tests/images/apng/fctl_actl.png\") as im:\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_delay(self):\n        with Image.open(\"Tests/images/apng/delay.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_round.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_short_max.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_zero_denom.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        with Image.open(\"Tests/images/apng/delay_zero_numer.png\") as im:\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 0.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 0.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n    def test_apng_num_plays(self):\n        with Image.open(\"Tests/images/apng/num_plays.png\") as im:\n            self.assertEqual(im.info.get(\"loop\"), 0)\n\n        with Image.open(\"Tests/images/apng/num_plays_1.png\") as im:\n            self.assertEqual(im.info.get(\"loop\"), 1)\n\n    def test_apng_mode(self):\n        with Image.open(\"Tests/images/apng/mode_16bit.png\") as im:\n            self.assertEqual(im.mode, \"RGBA\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 128, 191))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 128, 191))\n\n        with Image.open(\"Tests/images/apng/mode_greyscale.png\") as im:\n            self.assertEqual(im.mode, \"L\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), 128)\n            self.assertEqual(im.getpixel((64, 32)), 255)\n\n        with Image.open(\"Tests/images/apng/mode_greyscale_alpha.png\") as im:\n            self.assertEqual(im.mode, \"LA\")\n            im.seek(im.n_frames - 1)\n            self.assertEqual(im.getpixel((0, 0)), (128, 191))\n            self.assertEqual(im.getpixel((64, 32)), (128, 191))\n\n        with Image.open(\"Tests/images/apng/mode_palette.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGB\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0))\n\n        with Image.open(\"Tests/images/apng/mode_palette_alpha.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGBA\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/mode_palette_1bit_alpha.png\") as im:\n            self.assertEqual(im.mode, \"P\")\n            im.seek(im.n_frames - 1)\n            im = im.convert(\"RGBA\")\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 255, 128))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 255, 128))\n\n    def test_apng_chunk_errors(self):\n        with Image.open(\"Tests/images/apng/chunk_no_actl.png\") as im:\n            self.assertFalse(im.is_animated)\n\n        def open():\n            with Image.open(\"Tests/images/apng/chunk_multi_actl.png\") as im:\n                im.load()\n            self.assertFalse(im.is_animated)\n\n        pytest.warns(UserWarning, open)\n\n        with Image.open(\"Tests/images/apng/chunk_actl_after_idat.png\") as im:\n            self.assertFalse(im.is_animated)\n\n        with Image.open(\"Tests/images/apng/chunk_no_fctl.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n        with Image.open(\"Tests/images/apng/chunk_repeat_fctl.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n        with Image.open(\"Tests/images/apng/chunk_no_fdat.png\") as im:\n            with self.assertRaises(SyntaxError):\n                im.seek(im.n_frames - 1)\n\n    def test_apng_syntax_errors(self):\n        def open_frames_zero():\n            with Image.open(\"Tests/images/apng/syntax_num_frames_zero.png\") as im:\n                self.assertFalse(im.is_animated)\n                with self.assertRaises(OSError):\n                    im.load()\n\n        pytest.warns(UserWarning, open_frames_zero)\n\n        def open_frames_zero_default():\n            with Image.open(\n                \"Tests/images/apng/syntax_num_frames_zero_default.png\"\n            ) as im:\n                self.assertFalse(im.is_animated)\n                im.load()\n\n        pytest.warns(UserWarning, open_frames_zero_default)\n\n        # we can handle this case gracefully\n        exception = None\n        with Image.open(\"Tests/images/apng/syntax_num_frames_low.png\") as im:\n            try:\n                im.seek(im.n_frames - 1)\n            except Exception as e:\n                exception = e\n            self.assertIsNone(exception)\n\n        with self.assertRaises(SyntaxError):\n            with Image.open(\"Tests/images/apng/syntax_num_frames_high.png\") as im:\n                im.seek(im.n_frames - 1)\n                im.load()\n\n        def open():\n            with Image.open(\"Tests/images/apng/syntax_num_frames_invalid.png\") as im:\n                self.assertFalse(im.is_animated)\n                im.load()\n\n        pytest.warns(UserWarning, open)\n\n    def test_apng_sequence_errors(self):\n        test_files = [\n            \"sequence_start.png\",\n            \"sequence_gap.png\",\n            \"sequence_repeat.png\",\n            \"sequence_repeat_chunk.png\",\n            \"sequence_reorder.png\",\n            \"sequence_reorder_chunk.png\",\n            \"sequence_fdat_fctl.png\",\n        ]\n        for f in test_files:\n            with self.assertRaises(SyntaxError):\n                with Image.open(\"Tests/images/apng/{0}\".format(f)) as im:\n                    im.seek(im.n_frames - 1)\n                    im.load()\n\n    def test_apng_save(self):\n        with Image.open(\"Tests/images/apng/single_frame.png\") as im:\n            test_file = self.tempfile(\"temp.png\")\n            im.save(test_file, save_all=True)\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertFalse(im.is_animated)\n            self.assertEqual(im.n_frames, 1)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertIsNone(im.info.get(\"default_image\"))\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        with Image.open(\"Tests/images/apng/single_frame_default.png\") as im:\n            frames = []\n            for frame_im in ImageSequence.Iterator(im):\n                frames.append(frame_im.copy())\n            frames[0].save(\n                test_file, save_all=True, default_image=True, append_images=frames[1:]\n            )\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertTrue(im.is_animated)\n            self.assertEqual(im.n_frames, 2)\n            self.assertEqual(im.get_format_mimetype(), \"image/apng\")\n            self.assertTrue(im.info.get(\"default_image\"))\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_save_split_fdat(self):\n        # test to make sure we do not generate sequence errors when writing\n        # frames with image data spanning multiple fdAT chunks (in this case\n        # both the default image and first animation frame will span multiple\n        # data chunks)\n        test_file = self.tempfile(\"temp.png\")\n        with Image.open(\"Tests/images/old-style-jpeg-compression.png\") as im:\n            frames = [im.copy(), Image.new(\"RGBA\", im.size, (255, 0, 0, 255))]\n            im.save(\n                test_file, save_all=True, default_image=True, append_images=frames,\n            )\n        with Image.open(test_file) as im:\n            exception = None\n            try:\n                im.seek(im.n_frames - 1)\n                im.load()\n            except Exception as e:\n                exception = e\n            self.assertIsNone(exception)\n\n    def test_apng_save_duration_loop(self):\n        test_file = self.tempfile(\"temp.png\")\n        with Image.open(\"Tests/images/apng/delay.png\") as im:\n            frames = []\n            durations = []\n            loop = im.info.get(\"loop\")\n            default_image = im.info.get(\"default_image\")\n            for i, frame_im in enumerate(ImageSequence.Iterator(im)):\n                frames.append(frame_im.copy())\n                if i != 0 or not default_image:\n                    durations.append(frame_im.info.get(\"duration\", 0))\n            frames[0].save(\n                test_file,\n                save_all=True,\n                default_image=default_image,\n                append_images=frames[1:],\n                duration=durations,\n                loop=loop,\n            )\n\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertEqual(im.info.get(\"loop\"), loop)\n            im.seek(1)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(2)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n            im.seek(3)\n            self.assertEqual(im.info.get(\"duration\"), 500.0)\n            im.seek(4)\n            self.assertEqual(im.info.get(\"duration\"), 1000.0)\n\n        # test removal of duplicated frames\n        frame = Image.new(\"RGBA\", (128, 64), (255, 0, 0, 255))\n        frame.save(test_file, save_all=True, append_images=[frame], duration=[500, 250])\n        with Image.open(test_file) as im:\n            im.load()\n            self.assertEqual(im.n_frames, 1)\n            self.assertEqual(im.info.get(\"duration\"), 750)\n\n    def test_apng_save_disposal(self):\n        test_file = self.tempfile(\"temp.png\")\n        size = (128, 64)\n        red = Image.new(\"RGBA\", size, (255, 0, 0, 255))\n        green = Image.new(\"RGBA\", size, (0, 255, 0, 255))\n        transparent = Image.new(\"RGBA\", size, (0, 0, 0, 0))\n\n        # test APNG_DISPOSE_OP_NONE\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, transparent],\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_DISPOSE_OP_BACKGROUND\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_BACKGROUND,\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, transparent],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_BACKGROUND,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_DISPOSE_OP_PREVIOUS\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_PREVIOUS,\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, red, transparent],\n            default_image=True,\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(3)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        disposal = [\n            PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            PngImagePlugin.APNG_DISPOSE_OP_PREVIOUS,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green],\n            disposal=disposal,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n    def test_apng_save_blend(self):\n        test_file = self.tempfile(\"temp.png\")\n        size = (128, 64)\n        red = Image.new(\"RGBA\", size, (255, 0, 0, 255))\n        green = Image.new(\"RGBA\", size, (0, 255, 0, 255))\n        transparent = Image.new(\"RGBA\", size, (0, 0, 0, 0))\n\n        # test APNG_BLEND_OP_SOURCE on solid color\n        blend = [\n            PngImagePlugin.APNG_BLEND_OP_OVER,\n            PngImagePlugin.APNG_BLEND_OP_SOURCE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, green],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=blend,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n\n        # test APNG_BLEND_OP_SOURCE on transparent color\n        blend = [\n            PngImagePlugin.APNG_BLEND_OP_OVER,\n            PngImagePlugin.APNG_BLEND_OP_SOURCE,\n        ]\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[red, transparent],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=blend,\n        )\n        with Image.open(test_file) as im:\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 0, 0, 0))\n            self.assertEqual(im.getpixel((64, 32)), (0, 0, 0, 0))\n\n        # test APNG_BLEND_OP_OVER\n        red.save(\n            test_file,\n            save_all=True,\n            append_images=[green, transparent],\n            default_image=True,\n            disposal=PngImagePlugin.APNG_DISPOSE_OP_NONE,\n            blend=PngImagePlugin.APNG_BLEND_OP_OVER,\n        )\n        with Image.open(test_file) as im:\n            im.seek(1)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n            im.seek(2)\n            self.assertEqual(im.getpixel((0, 0)), (0, 255, 0, 255))\n            self.assertEqual(im.getpixel((64, 32)), (0, 255, 0, 255))\n"
    ],
    "test_file_names": [
        "test_1.py"
    ],
    "setup_res_code": 0,
    "setup_res_stdout": "Starting Pillow installation attempts...\nVerifying Pillow installation...\n✅ Pillow installation successful!\nSuccessfully installed Pillow\n",
    "setup_res_stderr": "Using CPython 3.9.21\nCreating virtual environment at: .venv\nActivate with: source .venv/bin/activate\nResolved 12 packages in 15ms\nInstalled 12 packages in 234ms\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 662ms\nPrepared 1 package in 34.84s\nInstalled 1 package in 1ms\n + pillow==7.1.0.dev0 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/pillow_9b72f0513c89d448e9bdeb4fd11dc8cbc37246d5)\n",
    "new_commit_res_code": 0,
    "new_commit_res_stdout": "============================= test session starts ==============================\nplatform linux -- Python 3.9.21, pytest-8.3.4, pluggy-1.5.0\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/pillow_9b72f0513c89d448e9bdeb4fd11dc8cbc37246d5\nconfigfile: setup.cfg\nplugins: cov-6.0.0\ncollected 17 items\n\nr2e_tests/test_1.py .................                                    [100%]\n\n==================================== PASSES ====================================\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::TestFilePng::test_apng_basic\nPASSED r2e_tests/test_1.py::TestFilePng::test_apng_blend\nPASSED r2e_tests/test_1.py::TestFilePng::test_apng_chunk_errors\nPASSED r2e_tests/test_1.py::TestFilePng::test_apng_chunk_order\nPASSED r2e_tests/test_1.py::TestFilePng::test_apng_delay\nPASSED r2e_tests/test_1.py::TestFilePng::test_apng_dispose\nPASSED r2e_tests/test_1.py::TestFilePng::test_apng_dispose_region\nPASSED r2e_tests/test_1.py::TestFilePng::test_apng_fdat\nPASSED r2e_tests/test_1.py::TestFilePng::test_apng_mode\nPASSED r2e_tests/test_1.py::TestFilePng::test_apng_num_plays\nPASSED r2e_tests/test_1.py::TestFilePng::test_apng_save\nPASSED r2e_tests/test_1.py::TestFilePng::test_apng_save_blend\nPASSED r2e_tests/test_1.py::TestFilePng::test_apng_save_disposal\nPASSED r2e_tests/test_1.py::TestFilePng::test_apng_save_duration_loop\nPASSED r2e_tests/test_1.py::TestFilePng::test_apng_save_split_fdat\nPASSED r2e_tests/test_1.py::TestFilePng::test_apng_sequence_errors\nPASSED r2e_tests/test_1.py::TestFilePng::test_apng_syntax_errors\n============================== 17 passed in 1.78s ==============================\n",
    "new_commit_res_stderr": "",
    "old_commit_res_code": 1,
    "old_commit_res_stdout": "============================= test session starts ==============================\nplatform linux -- Python 3.9.21, pytest-8.3.4, pluggy-1.5.0\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/pillow_9b72f0513c89d448e9bdeb4fd11dc8cbc37246d5\nconfigfile: setup.cfg\nplugins: cov-6.0.0\ncollected 17 items\n\nr2e_tests/test_1.py F.........F......                                    [100%]\n\n=================================== FAILURES ===================================\n_________________________ TestFilePng.test_apng_basic __________________________\n\nself = <r2e_tests.test_1.TestFilePng testMethod=test_apng_basic>\n\n    def test_apng_basic(self):\n        with Image.open(\"Tests/images/apng/single_frame.png\") as im:\n>           self.assertFalse(im.is_animated)\nE           AssertionError: True is not false\n\nr2e_tests/test_1.py:15: AssertionError\n__________________________ TestFilePng.test_apng_save __________________________\n\nself = <r2e_tests.test_1.TestFilePng testMethod=test_apng_save>\n\n    def test_apng_save(self):\n        with Image.open(\"Tests/images/apng/single_frame.png\") as im:\n            test_file = self.tempfile(\"temp.png\")\n            im.save(test_file, save_all=True)\n    \n        with Image.open(test_file) as im:\n            im.load()\n>           self.assertFalse(im.is_animated)\nE           AssertionError: True is not false\n\nr2e_tests/test_1.py:316: AssertionError\n==================================== PASSES ====================================\n=========================== short test summary info ============================\nPASSED r2e_tests/test_1.py::TestFilePng::test_apng_blend\nPASSED r2e_tests/test_1.py::TestFilePng::test_apng_chunk_errors\nPASSED r2e_tests/test_1.py::TestFilePng::test_apng_chunk_order\nPASSED r2e_tests/test_1.py::TestFilePng::test_apng_delay\nPASSED r2e_tests/test_1.py::TestFilePng::test_apng_dispose\nPASSED r2e_tests/test_1.py::TestFilePng::test_apng_dispose_region\nPASSED r2e_tests/test_1.py::TestFilePng::test_apng_fdat\nPASSED r2e_tests/test_1.py::TestFilePng::test_apng_mode\nPASSED r2e_tests/test_1.py::TestFilePng::test_apng_num_plays\nPASSED r2e_tests/test_1.py::TestFilePng::test_apng_save_blend\nPASSED r2e_tests/test_1.py::TestFilePng::test_apng_save_disposal\nPASSED r2e_tests/test_1.py::TestFilePng::test_apng_save_duration_loop\nPASSED r2e_tests/test_1.py::TestFilePng::test_apng_save_split_fdat\nPASSED r2e_tests/test_1.py::TestFilePng::test_apng_sequence_errors\nPASSED r2e_tests/test_1.py::TestFilePng::test_apng_syntax_errors\nFAILED r2e_tests/test_1.py::TestFilePng::test_apng_basic - AssertionError: Tr...\nFAILED r2e_tests/test_1.py::TestFilePng::test_apng_save - AssertionError: Tru...\n========================= 2 failed, 15 passed in 1.75s =========================\n",
    "old_commit_res_stderr": ""
}
Tests/test_file_apng.py docs/handbook/image-file-formats.rst src/PIL/PngImagePlugin.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** `is_animated` Property Incorrectly Returns True for Single-Frame APNG Images

**Description:**
When loading a single-frame APNG image, the `is_animated` property incorrectly returns `True`. This behavior is inconsistent with other Pillow image formats and does not align with the expectation that `is_animated` should only be `True` when there are multiple frames.

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

with Image.open("Tests/images/apng/single_frame.png") as im:
    print(im.is_animated)  # Expected: False
    print(im.n_frames)     # Expected: 1
```

**Expected Behavior:**
For single-frame APNG images, `is_animated` should return `False`, and `n_frames` should be `1`. This ensures consistency across different image formats within Pillow.

**Actual Behavior:**
The `is_animated` property returns `True` even when `n_frames` is `1`, indicating that the image is animated when it is not. This leads to incorrect handling of single-frame APNG images in applications relying on this property.

[/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/PngImagePlugin.py
#
# The Python Imaging Library.
# $Id$
#
# PNG support code
#
# See "PNG (Portable Network Graphics) Specification, version 1.0;
# W3C Recommendation", 1996-10-01, Thomas Boutell (ed.).
#
# history:
# 1996-05-06 fl   Created (couldn't resist it)
# 1996-12-14 fl   Upgraded, added read and verify support (0.2)
# 1996-12-15 fl   Separate PNG stream parser
# 1996-12-29 fl   Added write support, added getchunks
# 1996-12-30 fl   Eliminated circular references in decoder (0.3)
# 1998-07-12 fl   Read/write 16-bit images as mode I (0.4)
# 2001-02-08 fl   Added transparency support (from Zircon) (0.5)
# 2001-04-16 fl   Don't close data source in "open" method (0.6)
# 2004-02-24 fl   Don't even pretend to support interlaced files (0.7)
# 2004-08-31 fl   Do basic sanity check on chunk identifiers (0.8)
# 2004-09-20 fl   Added PngInfo chunk container
# 2004-12-18 fl   Added DPI read support (based on code by Niki Spahiev)
# 2008-08-13 fl   Added tRNS support for RGB images
# 2009-03-06 fl   Support for preserving ICC profiles (by Florian Hoech)
# 2009-03-08 fl   Added zTXT support (from Lowell Alleman)
# 2009-03-29 fl   Read interlaced PNG files (from Conrado Porto Lopes Gouvua)
#
# Copyright (c) 1997-2009 by Secret Labs AB
# Copyright (c) 1996 by Fredrik Lundh
#
# See the README file for information on usage and redistribution.
#

import itertools
import logging
import re
import struct
import warnings
import zlib

from . import Image, ImageChops, ImageFile, ImagePalette, ImageSequence
from ._binary import i8, i16be as i16, i32be as i32, o8, o16be as o16, o32be as o32

logger = logging.getLogger(__name__)

is_cid = re.compile(br"\w\w\w\w").match


_MAGIC = b"\211PNG\r\n\032\n"


_MODES = {
    # supported bits/color combinations, and corresponding modes/rawmodes
    # Greyscale
    (1, 0): ("1", "1"),
    (2, 0): ("L", "L;2"),
    (4, 0): ("L", "L;4"),
    (8, 0): ("L", "L"),
    (16, 0): ("I", "I;16B"),
    # Truecolour
    (8, 2): ("RGB", "RGB"),
    (16, 2): ("RGB", "RGB;16B"),
    # Indexed-colour
    (1, 3): ("P", "P;1"),
    (2, 3): ("P", "P;2"),
    (4, 3): ("P", "P;4"),
    (8, 3): ("P", "P"),
    # Greyscale with alpha
    (8, 4): ("LA", "LA"),
    (16, 4): ("RGBA", "LA;16B"),  # LA;16B->LA not yet available
    # Truecolour with alpha
    (8, 6): ("RGBA", "RGBA"),
    (16, 6): ("RGBA", "RGBA;16B"),
}


_simple_palette = re.compile(b"^\xff*\x00\xff*$")

# Maximum decompressed size for a iTXt or zTXt chunk.
# Eliminates decompression bombs where compressed chunks can expand 1000x
MAX_TEXT_CHUNK = ImageFile.SAFEBLOCK
# Set the maximum total text chunk size.
MAX_TEXT_MEMORY = 64 * MAX_TEXT_CHUNK


# APNG frame disposal modes
APNG_DISPOSE_OP_NONE = 0
APNG_DISPOSE_OP_BACKGROUND = 1
APNG_DISPOSE_OP_PREVIOUS = 2

# APNG frame blend modes
APNG_BLEND_OP_SOURCE = 0
APNG_BLEND_OP_OVER = 1


def _safe_zlib_decompress(s):
    dobj = zlib.decompressobj()
    plaintext = dobj.decompress(s, MAX_TEXT_CHUNK)
    if dobj.unconsumed_tail:
        raise ValueError("Decompressed Data Too Large")
    return plaintext


def _crc32(data, seed=0):
    return zlib.crc32(data, seed) & 0xFFFFFFFF


# --------------------------------------------------------------------
# Support classes.  Suitable for PNG and related formats like MNG etc.


class ChunkStream:
    def __init__(self, fp):

        self.fp = fp
        self.queue = []

    def read(self):
        """Fetch a new chunk. Returns header information."""
        cid = None

        if self.queue:
            cid, pos, length = self.queue.pop()
            self.fp.seek(pos)
        else:
            s = self.fp.read(8)
            cid = s[4:]
            pos = self.fp.tell()
            length = i32(s)

        if not is_cid(cid):
            if not ImageFile.LOAD_TRUNCATED_IMAGES:
                raise SyntaxError("broken PNG file (chunk %s)" % repr(cid))

        return cid, pos, length

    def __enter__(self):
        return self

    def __exit__(self, *args):
        self.close()

    def close(self):
        self.queue = self.crc = self.fp = None

    def push(self, cid, pos, length):

        self.queue.append((cid, pos, length))

    def call(self, cid, pos, length):
        """Call the appropriate chunk handler"""

        logger.debug("STREAM %r %s %s", cid, pos, length)
        return getattr(self, "chunk_" + cid.decode("ascii"))(pos, length)

    def crc(self, cid, data):
        """Read and verify checksum"""

        # Skip CRC checks for ancillary chunks if allowed to load truncated
        # images
        # 5th byte of first char is 1 [specs, section 5.4]
        if ImageFile.LOAD_TRUNCATED_IMAGES and (i8(cid[0]) >> 5 & 1):
            self.crc_skip(cid, data)
            return

        try:
            crc1 = _crc32(data, _crc32(cid))
            crc2 = i32(self.fp.read(4))
            if crc1 != crc2:
                raise SyntaxError("broken PNG file (bad header checksum in %r)" % cid)
        except struct.error:
            raise SyntaxError("broken PNG file (incomplete checksum in %r)" % cid)

    def crc_skip(self, cid, data):
        """Read checksum.  Used if the C module is not present"""

        self.fp.read(4)

    def verify(self, endchunk=b"IEND"):

        # Simple approach; just calculate checksum for all remaining
        # blocks.  Must be called directly after open.

        cids = []

        while True:
            try:
                cid, pos, length = self.read()
            except struct.error:
                raise OSError("truncated PNG file")

            if cid == endchunk:
                break
            self.crc(cid, ImageFile._safe_read(self.fp, length))
            cids.append(cid)

        return cids


class iTXt(str):
    """
    Subclass of string to allow iTXt chunks to look like strings while
    keeping their extra information

    """

    @staticmethod
    def __new__(cls, text, lang=None, tkey=None):
        """
        :param cls: the class to use when creating the instance
        :param text: value for this key
        :param lang: language code
        :param tkey: UTF-8 version of the key name
        """

        self = str.__new__(cls, text)
        self.lang = lang
        self.tkey = tkey
        return self


class PngInfo:
    """
    PNG chunk container (for use with save(pnginfo=))

    """

    def __init__(self):
        self.chunks = []

    def add(self, cid, data):
        """Appends an arbitrary chunk. Use with caution.

        :param cid: a byte string, 4 bytes long.
        :param data: a byte string of the encoded data

        """

        self.chunks.append((cid, data))

    def add_itxt(self, key, value, lang="", tkey="", zip=False):
        """Appends an iTXt chunk.

        :param key: latin-1 encodable text key name
        :param value: value for this key
        :param lang: language code
        :param tkey: UTF-8 version of the key name
        :param zip: compression flag

        """

        if not isinstance(key, bytes):
            key = key.encode("latin-1", "strict")
        if not isinstance(value, bytes):
            value = value.encode("utf-8", "strict")
        if not isinstance(lang, bytes):
            lang = lang.encode("utf-8", "strict")
        if not isinstance(tkey, bytes):
            tkey = tkey.encode("utf-8", "strict")

        if zip:
            self.add(
                b"iTXt",
                key + b"\0\x01\0" + lang + b"\0" + tkey + b"\0" + zlib.compress(value),
            )
        else:
            self.add(b"iTXt", key + b"\0\0\0" + lang + b"\0" + tkey + b"\0" + value)

    def add_text(self, key, value, zip=False):
        """Appends a text chunk.

        :param key: latin-1 encodable text key name
        :param value: value for this key, text or an
           :py:class:`PIL.PngImagePlugin.iTXt` instance
        :param zip: compression flag

        """
        if isinstance(value, iTXt):
            return self.add_itxt(key, value, value.lang, value.tkey, zip=zip)

        # The tEXt chunk stores latin-1 text
        if not isinstance(value, bytes):
            try:
                value = value.encode("latin-1", "strict")
            except UnicodeError:
                return self.add_itxt(key, value, zip=zip)

        if not isinstance(key, bytes):
            key = key.encode("latin-1", "strict")

        if zip:
            self.add(b"zTXt", key + b"\0\0" + zlib.compress(value))
        else:
            self.add(b"tEXt", key + b"\0" + value)


# --------------------------------------------------------------------
# PNG image stream (IHDR/IEND)


class PngStream(ChunkStream):
    def __init__(self, fp):
        super().__init__(fp)

        # local copies of Image attributes
        self.im_info = {}
        self.im_text = {}
        self.im_size = (0, 0)
        self.im_mode = None
        self.im_tile = None
        self.im_palette = None
        self.im_custom_mimetype = None
        self.im_n_frames = None
        self._seq_num = None
        self.rewind_state = None

        self.text_memory = 0

    def check_text_memory(self, chunklen):
        self.text_memory += chunklen
        if self.text_memory > MAX_TEXT_MEMORY:
            raise ValueError(
                "Too much memory used in text chunks: %s>MAX_TEXT_MEMORY"
                % self.text_memory
            )

    def save_rewind(self):
        self.rewind_state = {
            "info": self.im_info.copy(),
            "tile": self.im_tile,
            "seq_num": self._seq_num,
        }

    def rewind(self):
        self.im_info = self.rewind_state["info"]
        self.im_tile = self.rewind_state["tile"]
        self._seq_num = self.rewind_state["seq_num"]

    def chunk_iCCP(self, pos, length):

        # ICC profile
        s = ImageFile._safe_read(self.fp, length)
        # according to PNG spec, the iCCP chunk contains:
        # Profile name  1-79 bytes (character string)
        # Null separator        1 byte (null character)
        # Compression method    1 byte (0)
        # Compressed profile    n bytes (zlib with deflate compression)
        i = s.find(b"\0")
        logger.debug("iCCP profile name %r", s[:i])
        logger.debug("Compression method %s", i8(s[i]))
        comp_method = i8(s[i])
        if comp_method != 0:
            raise SyntaxError(
                "Unknown compression method %s in iCCP chunk" % comp_method
            )
        try:
            icc_profile = _safe_zlib_decompress(s[i + 2 :])
        except ValueError:
            if ImageFile.LOAD_TRUNCATED_IMAGES:
                icc_profile = None
            else:
                raise
        except zlib.error:
            icc_profile = None  # FIXME
        self.im_info["icc_profile"] = icc_profile
        return s

    def chunk_IHDR(self, pos, length):

        # image header
        s = ImageFile._safe_read(self.fp, length)
        self.im_size = i32(s), i32(s[4:])
        try:
            self.im_mode, self.im_rawmode = _MODES[(i8(s[8]), i8(s[9]))]
        except Exception:
            pass
        if i8(s[12]):
            self.im_info["interlace"] = 1
        if i8(s[11]):
            raise SyntaxError("unknown filter category")
        return s

    def chunk_IDAT(self, pos, length):

        # image data
        if "bbox" in self.im_info:
            tile = [("zip", self.im_info["bbox"], pos, self.im_rawmode)]
        else:
            if self.im_n_frames is not None:
                self.im_info["default_image"] = True
            tile = [("zip", (0, 0) + self.im_size, pos, self.im_rawmode)]
        self.im_tile = tile
        self.im_idat = length
        raise EOFError

    def chunk_IEND(self, pos, length):

        # end of PNG image
        raise EOFError

    def chunk_PLTE(self, pos, length):

        # palette
        s = ImageFile._safe_read(self.fp, length)
        if self.im_mode == "P":
            self.im_palette = "RGB", s
        return s

    def chunk_tRNS(self, pos, length):

        # transparency
        s = ImageFile._safe_read(self.fp, length)
        if self.im_mode == "P":
            if _simple_palette.match(s):
                # tRNS contains only one full-transparent entry,
                # other entries are full opaque
                i = s.find(b"\0")
                if i >= 0:
                    self.im_info["transparency"] = i
            else:
                # otherwise, we have a byte string with one alpha value
                # for each palette entry
                self.im_info["transparency"] = s
        elif self.im_mode in ("1", "L", "I"):
            self.im_info["transparency"] = i16(s)
        elif self.im_mode == "RGB":
            self.im_info["transparency"] = i16(s), i16(s[2:]), i16(s[4:])
        return s

    def chunk_gAMA(self, pos, length):
        # gamma setting
        s = ImageFile._safe_read(self.fp, length)
        self.im_info["gamma"] = i32(s) / 100000.0
        return s

    def chunk_cHRM(self, pos, length):
        # chromaticity, 8 unsigned ints, actual value is scaled by 100,000
        # WP x,y, Red x,y, Green x,y Blue x,y

        s = ImageFile._safe_read(self.fp, length)
        raw_vals = struct.unpack(">%dI" % (len(s) // 4), s)
        self.im_info["chromaticity"] = tuple(elt / 100000.0 for elt in raw_vals)
        return s

    def chunk_sRGB(self, pos, length):
        # srgb rendering intent, 1 byte
        # 0 perceptual
        # 1 relative colorimetric
        # 2 saturation
        # 3 absolute colorimetric

        s = ImageFile._safe_read(self.fp, length)
        self.im_info["srgb"] = i8(s)
        return s

    def chunk_pHYs(self, pos, length):

        # pixels per unit
        s = ImageFile._safe_read(self.fp, length)
        px, py = i32(s), i32(s[4:])
        unit = i8(s[8])
        if unit == 1:  # meter
            dpi = int(px * 0.0254 + 0.5), int(py * 0.0254 + 0.5)
            self.im_info["dpi"] = dpi
        elif unit == 0:
            self.im_info["aspect"] = px, py
        return s

    def chunk_tEXt(self, pos, length):

        # text
        s = ImageFile._safe_read(self.fp, length)
        try:
            k, v = s.split(b"\0", 1)
        except ValueError:
            # fallback for broken tEXt tags
            k = s
            v = b""
        if k:
            k = k.decode("latin-1", "strict")
            v = v.decode("latin-1", "replace")

            self.im_info[k] = self.im_text[k] = v
            self.check_text_memory(len(v))

        return s

    def chunk_zTXt(self, pos, length):

        # compressed text
        s = ImageFile._safe_read(self.fp, length)
        try:
            k, v = s.split(b"\0", 1)
        except ValueError:
            k = s
            v = b""
        if v:
            comp_method = i8(v[0])
        else:
            comp_method = 0
        if comp_method != 0:
            raise SyntaxError(
                "Unknown compression method %s in zTXt chunk" % comp_method
            )
        try:
            v = _safe_zlib_decompress(v[1:])
        except ValueError:
            if ImageFile.LOAD_TRUNCATED_IMAGES:
                v = b""
            else:
                raise
        except zlib.error:
            v = b""

        if k:
            k = k.decode("latin-1", "strict")
            v = v.decode("latin-1", "replace")

            self.im_info[k] = self.im_text[k] = v
            self.check_text_memory(len(v))

        return s

    def chunk_iTXt(self, pos, length):

        # international text
        r = s = ImageFile._safe_read(self.fp, length)
        try:
            k, r = r.split(b"\0", 1)
        except ValueError:
            return s
        if len(r) < 2:
            return s
        cf, cm, r = i8(r[0]), i8(r[1]), r[2:]
        try:
            lang, tk, v = r.split(b"\0", 2)
        except ValueError:
            return s
        if cf != 0:
            if cm == 0:
                try:
                    v = _safe_zlib_decompress(v)
                except ValueError:
                    if ImageFile.LOAD_TRUNCATED_IMAGES:
                        return s
                    else:
                        raise
                except zlib.error:
                    return s
            else:
                return s
        try:
            k = k.decode("latin-1", "strict")
            lang = lang.decode("utf-8", "strict")
            tk = tk.decode("utf-8", "strict")
            v = v.decode("utf-8", "strict")
        except UnicodeError:
            return s

        self.im_info[k] = self.im_text[k] = iTXt(v, lang, tk)
        self.check_text_memory(len(v))

        return s

    def chunk_eXIf(self, pos, length):
        s = ImageFile._safe_read(self.fp, length)
        self.im_info["exif"] = b"Exif\x00\x00" + s
        return s

    # APNG chunks
    def chunk_acTL(self, pos, length):
        s = ImageFile._safe_read(self.fp, length)
        if self.im_n_frames is not None:
            self.im_n_frames = None
            warnings.warn("Invalid APNG, will use default PNG image if possible")
            return s
        n_frames = i32(s)
        if n_frames == 0 or n_frames > 0x80000000:
            warnings.warn("Invalid APNG, will use default PNG image if possible")
            return s
        self.im_n_frames = n_frames
        self.im_info["loop"] = i32(s[4:])
        self.im_custom_mimetype = "image/apng"
        return s

    def chunk_fcTL(self, pos, length):
        s = ImageFile._safe_read(self.fp, length)
        seq = i32(s)
        if (self._seq_num is None and seq != 0) or (
            self._seq_num is not None and self._seq_num != seq - 1
        ):
            raise SyntaxError("APNG contains frame sequence errors")
        self._seq_num = seq
        width, height = i32(s[4:]), i32(s[8:])
        px, py = i32(s[12:]), i32(s[16:])
        im_w, im_h = self.im_size
        if px + width > im_w or py + height > im_h:
            raise SyntaxError("APNG contains invalid frames")
        self.im_info["bbox"] = (px, py, px + width, py + height)
        delay_num, delay_den = i16(s[20:]), i16(s[22:])
        if delay_den == 0:
            delay_den = 100
        self.im_info["duration"] = float(delay_num) / float(delay_den) * 1000
        self.im_info["disposal"] = i8(s[24])
        self.im_info["blend"] = i8(s[25])
        return s

    def chunk_fdAT(self, pos, length):
        s = ImageFile._safe_read(self.fp, 4)
        seq = i32(s)
        if self._seq_num != seq - 1:
            raise SyntaxError("APNG contains frame sequence errors")
        self._seq_num = seq
        return self.chunk_IDAT(pos + 4, length - 4)


# --------------------------------------------------------------------
# PNG reader


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


##
# Image plugin for PNG images.


class PngImageFile(ImageFile.ImageFile):

    format = "PNG"
    format_description = "Portable network graphics"

    def _open(self):

        if self.fp.read(8) != _MAGIC:
            raise SyntaxError("not a PNG file")
        self.__fp = self.fp

        #
        # Parse headers up to the first IDAT or fDAT chunk

        self.png = PngStream(self.fp)

        while True:

            #
            # get next chunk

            cid, pos, length = self.png.read()

            try:
                s = self.png.call(cid, pos, length)
            except EOFError:
                break
            except AttributeError:
                logger.debug("%r %s %s (unknown)", cid, pos, length)
                s = ImageFile._safe_read(self.fp, length)

            self.png.crc(cid, s)

        #
        # Copy relevant attributes from the PngStream.  An alternative
        # would be to let the PngStream class modify these attributes
        # directly, but that introduces circular references which are
        # difficult to break if things go wrong in the decoder...
        # (believe me, I've tried ;-)

        self.mode = self.png.im_mode
        self._size = self.png.im_size
        self.info = self.png.im_info
        self._text = None
        self.tile = self.png.im_tile
        self.custom_mimetype = self.png.im_custom_mimetype
        self._n_frames = self.png.im_n_frames
        self.default_image = self.info.get("default_image", False)

        if self.png.im_palette:
            rawmode, data = self.png.im_palette
            self.palette = ImagePalette.raw(rawmode, data)

        if cid == b"fdAT":
            self.__prepare_idat = length - 4
        else:
            self.__prepare_idat = length  # used by load_prepare()

        if self._n_frames is not None:
            self._close_exclusive_fp_after_loading = False
            self.png.save_rewind()
            self.__rewind_idat = self.__prepare_idat
            self.__rewind = self.__fp.tell()
            if self.default_image:
                # IDAT chunk contains default image and not first animation frame
                self._n_frames += 1
            self._seek(0)

    @property
    def text(self):
        # experimental
        if self._text is None:
            # iTxt, tEXt and zTXt chunks may appear at the end of the file
            # So load the file to ensure that they are read
            if self.is_animated:
                frame = self.__frame
                # for APNG, seek to the final frame before loading
                self.seek(self.n_frames - 1)
            self.load()
            if self.is_animated:
                self.seek(frame)
        return self._text

    @property
    def n_frames(self):
        if self._n_frames is None:
            return 1
        return self._n_frames

    @property
    def is_animated(self):
        return self._n_frames is not None

    def verify(self):
        """Verify PNG file"""

        if self.fp is None:
            raise RuntimeError("verify must be called directly after open")

        # back up to beginning of IDAT block
        self.fp.seek(self.tile[0][2] - 8)

        self.png.verify()
        self.png.close()

        if self._exclusive_fp:
            self.fp.close()
        self.fp = None

    def seek(self, frame):
        if not self._seek_check(frame):
            return
        if frame < self.__frame:
            self._seek(0, True)

        last_frame = self.__frame
        for f in range(self.__frame + 1, frame + 1):
            try:
                self._seek(f)
            except EOFError:
                self.seek(last_frame)
                raise EOFError("no more images in APNG file")

    def _seek(self, frame, rewind=False):
        if frame == 0:
            if rewind:
                self.__fp.seek(self.__rewind)
                self.png.rewind()
                self.__prepare_idat = self.__rewind_idat
                self.im = None
                if self.pyaccess:
                    self.pyaccess = None
                self.info = self.png.im_info
                self.tile = self.png.im_tile
                self.fp = self.__fp
            self._prev_im = None
            self.dispose = None
            self.default_image = self.info.get("default_image", False)
            self.dispose_op = self.info.get("disposal")
            self.blend_op = self.info.get("blend")
            self.dispose_extent = self.info.get("bbox")
            self.__frame = 0
            return
        else:
            if frame != self.__frame + 1:
                raise ValueError("cannot seek to frame %d" % frame)

        # ensure previous frame was loaded
        self.load()

        self.fp = self.__fp

        # advance to the next frame
        if self.__prepare_idat:
            ImageFile._safe_read(self.fp, self.__prepare_idat)
            self.__prepare_idat = 0
        frame_start = False
        while True:
            self.fp.read(4)  # CRC

            try:
                cid, pos, length = self.png.read()
            except (struct.error, SyntaxError):
                break

            if cid == b"IEND":
                raise EOFError("No more images in APNG file")
            if cid == b"fcTL":
                if frame_start:
                    # there must be at least one fdAT chunk between fcTL chunks
                    raise SyntaxError("APNG missing frame data")
                frame_start = True

            try:
                self.png.call(cid, pos, length)
            except UnicodeDecodeError:
                break
            except EOFError:
                if cid == b"fdAT":
                    length -= 4
                    if frame_start:
                        self.__prepare_idat = length
                        break
                ImageFile._safe_read(self.fp, length)
            except AttributeError:
                logger.debug("%r %s %s (unknown)", cid, pos, length)
                ImageFile._safe_read(self.fp, length)

        self.__frame = frame
        self.tile = self.png.im_tile
        self.dispose_op = self.info.get("disposal")
        self.blend_op = self.info.get("blend")
        self.dispose_extent = self.info.get("bbox")

        if not self.tile:
            raise EOFError

    def tell(self):
        return self.__frame

    def load_prepare(self):
        """internal: prepare to read PNG file"""

        if self.info.get("interlace"):
            self.decoderconfig = self.decoderconfig + (1,)

        self.__idat = self.__prepare_idat  # used by load_read()
        ImageFile.ImageFile.load_prepare(self)

    def load_read(self, read_bytes):
        """internal: read more image data"""

        while self.__idat == 0:
            # end of chunk, skip forward to next one

            self.fp.read(4)  # CRC

            cid, pos, length = self.png.read()

            if cid not in [b"IDAT", b"DDAT", b"fdAT"]:
                self.png.push(cid, pos, length)
                return b""

            if cid == b"fdAT":
                try:
                    self.png.call(cid, pos, length)
                except EOFError:
                    pass
                self.__idat = length - 4  # sequence_num has already been read
            else:
                self.__idat = length  # empty chunks are allowed

        # read more data from this chunk
        if read_bytes <= 0:
            read_bytes = self.__idat
        else:
            read_bytes = min(read_bytes, self.__idat)

        self.__idat = self.__idat - read_bytes

        return self.fp.read(read_bytes)

    def load_end(self):
        """internal: finished reading image data"""
        while True:
            self.fp.read(4)  # CRC

            try:
                cid, pos, length = self.png.read()
            except (struct.error, SyntaxError):
                break

            if cid == b"IEND":
                break
            elif cid == b"fcTL" and self.is_animated:
                # start of the next frame, stop reading
                self.__prepare_idat = 0
                self.png.push(cid, pos, length)
                break

            try:
                self.png.call(cid, pos, length)
            except UnicodeDecodeError:
                break
            except EOFError:
                if cid == b"fdAT":
                    length -= 4
                ImageFile._safe_read(self.fp, length)
            except AttributeError:
                logger.debug("%r %s %s (unknown)", cid, pos, length)
                ImageFile._safe_read(self.fp, length)
        self._text = self.png.im_text
        if not self.is_animated:
            self.png.close()
            self.png = None
        else:
            # setup frame disposal (actual disposal done when needed in _seek())
            if self._prev_im is None and self.dispose_op == APNG_DISPOSE_OP_PREVIOUS:
                self.dispose_op = APNG_DISPOSE_OP_BACKGROUND

            if self.dispose_op == APNG_DISPOSE_OP_PREVIOUS:
                dispose = self._prev_im.copy()
                dispose = self._crop(dispose, self.dispose_extent)
            elif self.dispose_op == APNG_DISPOSE_OP_BACKGROUND:
                dispose = Image.core.fill("RGBA", self.size, (0, 0, 0, 0))
                dispose = self._crop(dispose, self.dispose_extent)
            else:
                dispose = None

            if self._prev_im and self.blend_op == APNG_BLEND_OP_OVER:
                updated = self._crop(self.im, self.dispose_extent)
                self._prev_im.paste(
                    updated, self.dispose_extent, updated.convert("RGBA")
                )
                self.im = self._prev_im
                if self.pyaccess:
                    self.pyaccess = None
            self._prev_im = self.im.copy()

            if dispose:
                self._prev_im.paste(dispose, self.dispose_extent)

    def _getexif(self):
        if "exif" not in self.info:
            self.load()
        if "exif" not in self.info:
            return None
        return dict(self.getexif())

    def getexif(self):
        if "exif" not in self.info:
            self.load()
        return ImageFile.ImageFile.getexif(self)

    def _close__fp(self):
        try:
            if self.__fp != self.fp:
                self.__fp.close()
        except AttributeError:
            pass
        finally:
            self.__fp = None


# --------------------------------------------------------------------
# PNG writer

_OUTMODES = {
    # supported PIL modes, and corresponding rawmodes/bits/color combinations
    "1": ("1", b"\x01\x00"),
    "L;1": ("L;1", b"\x01\x00"),
    "L;2": ("L;2", b"\x02\x00"),
    "L;4": ("L;4", b"\x04\x00"),
    "L": ("L", b"\x08\x00"),
    "LA": ("LA", b"\x08\x04"),
    "I": ("I;16B", b"\x10\x00"),
    "I;16": ("I;16B", b"\x10\x00"),
    "P;1": ("P;1", b"\x01\x03"),
    "P;2": ("P;2", b"\x02\x03"),
    "P;4": ("P;4", b"\x04\x03"),
    "P": ("P", b"\x08\x03"),
    "RGB": ("RGB", b"\x08\x02"),
    "RGBA": ("RGBA", b"\x08\x06"),
}


def putchunk(fp, cid, *data):
    """Write a PNG chunk (including CRC field)"""

    data = b"".join(data)

    fp.write(o32(len(data)) + cid)
    fp.write(data)
    crc = _crc32(data, _crc32(cid))
    fp.write(o32(crc))


class _idat:
    # wrap output from the encoder in IDAT chunks

    def __init__(self, fp, chunk):
        self.fp = fp
        self.chunk = chunk

    def write(self, data):
        self.chunk(self.fp, b"IDAT", data)


class _fdat:
    # wrap encoder output in fdAT chunks

    def __init__(self, fp, chunk, seq_num):
        self.fp = fp
        self.chunk = chunk
        self.seq_num = seq_num

    def write(self, data):
        self.chunk(self.fp, b"fdAT", o32(self.seq_num), data)
        self.seq_num += 1


def _write_multiple_frames(im, fp, chunk, rawmode):
    default_image = im.encoderinfo.get("default_image", im.info.get("default_image"))
    duration = im.encoderinfo.get("duration", im.info.get("duration", 0))
    loop = im.encoderinfo.get("loop", im.info.get("loop", 0))
    disposal = im.encoderinfo.get("disposal", im.info.get("disposal"))
    blend = im.encoderinfo.get("blend", im.info.get("blend"))

    if default_image:
        chain = itertools.chain(im.encoderinfo.get("append_images", []))
    else:
        chain = itertools.chain([im], im.encoderinfo.get("append_images", []))

    im_frames = []
    frame_count = 0
    for im_seq in chain:
        for im_frame in ImageSequence.Iterator(im_seq):
            im_frame = im_frame.copy()
            if im_frame.mode != im.mode:
                if im.mode == "P":
                    im_frame = im_frame.convert(im.mode, palette=im.palette)
                else:
                    im_frame = im_frame.convert(im.mode)
            encoderinfo = im.encoderinfo.copy()
            if isinstance(duration, (list, tuple)):
                encoderinfo["duration"] = duration[frame_count]
            if isinstance(disposal, (list, tuple)):
                encoderinfo["disposal"] = disposal[frame_count]
            if isinstance(blend, (list, tuple)):
                encoderinfo["blend"] = blend[frame_count]
            frame_count += 1

            if im_frames:
                previous = im_frames[-1]
                prev_disposal = previous["encoderinfo"].get("disposal")
                prev_blend = previous["encoderinfo"].get("blend")
                if prev_disposal == APNG_DISPOSE_OP_PREVIOUS and len(im_frames) < 2:
                    prev_disposal == APNG_DISPOSE_OP_BACKGROUND

                if prev_disposal == APNG_DISPOSE_OP_BACKGROUND:
                    base_im = previous["im"]
                    dispose = Image.core.fill("RGBA", im.size, (0, 0, 0, 0))
                    bbox = previous["bbox"]
                    if bbox:
                        dispose = dispose.crop(bbox)
                    else:
                        bbox = (0, 0) + im.size
                    base_im.paste(dispose, bbox)
                elif prev_disposal == APNG_DISPOSE_OP_PREVIOUS:
                    base_im = im_frames[-2]["im"]
                else:
                    base_im = previous["im"]
                delta = ImageChops.subtract_modulo(im_frame, base_im)
                bbox = delta.getbbox()
                if (
                    not bbox
                    and prev_disposal == encoderinfo.get("disposal")
                    and prev_blend == encoderinfo.get("blend")
                ):
                    duration = encoderinfo.get("duration", 0)
                    if duration:
                        if "duration" in previous["encoderinfo"]:
                            previous["encoderinfo"]["duration"] += duration
                        else:
                            previous["encoderinfo"]["duration"] = duration
                    continue
            else:
                bbox = None
            im_frames.append({"im": im_frame, "bbox": bbox, "encoderinfo": encoderinfo})

    # animation control
    chunk(
        fp, b"acTL", o32(len(im_frames)), o32(loop),  # 0: num_frames  # 4: num_plays
    )

    # default image IDAT (if it exists)
    if default_image:
        ImageFile._save(im, _idat(fp, chunk), [("zip", (0, 0) + im.size, 0, rawmode)])

    seq_num = 0
    for frame, frame_data in enumerate(im_frames):
        im_frame = frame_data["im"]
        if not frame_data["bbox"]:
            bbox = (0, 0) + im_frame.size
        else:
            bbox = frame_data["bbox"]
            im_frame = im_frame.crop(bbox)
        size = im_frame.size
        duration = int(round(frame_data["encoderinfo"].get("duration", 0)))
        disposal = frame_data["encoderinfo"].get("disposal", APNG_DISPOSE_OP_NONE)
        blend = frame_data["encoderinfo"].get("blend", APNG_BLEND_OP_SOURCE)
        # frame control
        chunk(
            fp,
            b"fcTL",
            o32(seq_num),  # sequence_number
            o32(size[0]),  # width
            o32(size[1]),  # height
            o32(bbox[0]),  # x_offset
            o32(bbox[1]),  # y_offset
            o16(duration),  # delay_numerator
            o16(1000),  # delay_denominator
            o8(disposal),  # dispose_op
            o8(blend),  # blend_op
        )
        seq_num += 1
        # frame data
        if frame == 0 and not default_image:
            # first frame must be in IDAT chunks for backwards compatibility
            ImageFile._save(
                im_frame,
                _idat(fp, chunk),
                [("zip", (0, 0) + im_frame.size, 0, rawmode)],
            )
        else:
            fdat_chunks = _fdat(fp, chunk, seq_num)
            ImageFile._save(
                im_frame, fdat_chunks, [("zip", (0, 0) + im_frame.size, 0, rawmode)],
            )
            seq_num = fdat_chunks.seq_num


def _save_all(im, fp, filename):
    _save(im, fp, filename, save_all=True)


def _save(im, fp, filename, chunk=putchunk, save_all=False):
    # save an image to disk (called by the save method)

    mode = im.mode

    if mode == "P":

        #
        # attempt to minimize storage requirements for palette images
        if "bits" in im.encoderinfo:
            # number of bits specified by user
            colors = 1 << im.encoderinfo["bits"]
        else:
            # check palette contents
            if im.palette:
                colors = max(min(len(im.palette.getdata()[1]) // 3, 256), 2)
            else:
                colors = 256

        if colors <= 2:
            bits = 1
        elif colors <= 4:
            bits = 2
        elif colors <= 16:
            bits = 4
        else:
            bits = 8
        if bits != 8:
            mode = "%s;%d" % (mode, bits)

    # encoder options
    im.encoderconfig = (
        im.encoderinfo.get("optimize", False),
        im.encoderinfo.get("compress_level", -1),
        im.encoderinfo.get("compress_type", -1),
        im.encoderinfo.get("dictionary", b""),
    )

    # get the corresponding PNG mode
    try:
        rawmode, mode = _OUTMODES[mode]
    except KeyError:
        raise OSError("cannot write mode %s as PNG" % mode)

    #
    # write minimal PNG file

    fp.write(_MAGIC)

    chunk(
        fp,
        b"IHDR",
        o32(im.size[0]),  # 0: size
        o32(im.size[1]),
        mode,  # 8: depth/type
        b"\0",  # 10: compression
        b"\0",  # 11: filter category
        b"\0",  # 12: interlace flag
    )

    chunks = [b"cHRM", b"gAMA", b"sBIT", b"sRGB", b"tIME"]

    icc = im.encoderinfo.get("icc_profile", im.info.get("icc_profile"))
    if icc:
        # ICC profile
        # according to PNG spec, the iCCP chunk contains:
        # Profile name  1-79 bytes (character string)
        # Null separator        1 byte (null character)
        # Compression method    1 byte (0)
        # Compressed profile    n bytes (zlib with deflate compression)
        name = b"ICC Profile"
        data = name + b"\0\0" + zlib.compress(icc)
        chunk(fp, b"iCCP", data)

        # You must either have sRGB or iCCP.
        # Disallow sRGB chunks when an iCCP-chunk has been emitted.
        chunks.remove(b"sRGB")

    info = im.encoderinfo.get("pnginfo")
    if info:
        chunks_multiple_allowed = [b"sPLT", b"iTXt", b"tEXt", b"zTXt"]
        for cid, data in info.chunks:
            if cid in chunks:
                chunks.remove(cid)
                chunk(fp, cid, data)
            elif cid in chunks_multiple_allowed:
                chunk(fp, cid, data)

    if im.mode == "P":
        palette_byte_number = (2 ** bits) * 3
        palette_bytes = im.im.getpalette("RGB")[:palette_byte_number]
        while len(palette_bytes) < palette_byte_number:
            palette_bytes += b"\0"
        chunk(fp, b"PLTE", palette_bytes)

    transparency = im.encoderinfo.get("transparency", im.info.get("transparency", None))

    if transparency or transparency == 0:
        if im.mode == "P":
            # limit to actual palette size
            alpha_bytes = 2 ** bits
            if isinstance(transparency, bytes):
                chunk(fp, b"tRNS", transparency[:alpha_bytes])
            else:
                transparency = max(0, min(255, transparency))
                alpha = b"\xFF" * transparency + b"\0"
                chunk(fp, b"tRNS", alpha[:alpha_bytes])
        elif im.mode in ("1", "L", "I"):
            transparency = max(0, min(65535, transparency))
            chunk(fp, b"tRNS", o16(transparency))
        elif im.mode == "RGB":
            red, green, blue = transparency
            chunk(fp, b"tRNS", o16(red) + o16(green) + o16(blue))
        else:
            if "transparency" in im.encoderinfo:
                # don't bother with transparency if it's an RGBA
                # and it's in the info dict. It's probably just stale.
                raise OSError("cannot use transparency for this mode")
    else:
        if im.mode == "P" and im.im.getpalettemode() == "RGBA":
            alpha = im.im.getpalette("RGBA", "A")
            alpha_bytes = 2 ** bits
            chunk(fp, b"tRNS", alpha[:alpha_bytes])

    dpi = im.encoderinfo.get("dpi")
    if dpi:
        chunk(
            fp,
            b"pHYs",
            o32(int(dpi[0] / 0.0254 + 0.5)),
            o32(int(dpi[1] / 0.0254 + 0.5)),
            b"\x01",
        )

    if info:
        chunks = [b"bKGD", b"hIST"]
        for cid, data in info.chunks:
            if cid in chunks:
                chunks.remove(cid)
                chunk(fp, cid, data)

    exif = im.encoderinfo.get("exif", im.info.get("exif"))
    if exif:
        if isinstance(exif, Image.Exif):
            exif = exif.tobytes(8)
        if exif.startswith(b"Exif\x00\x00"):
            exif = exif[6:]
        chunk(fp, b"eXIf", exif)

    if save_all:
        _write_multiple_frames(im, fp, chunk, rawmode)
    else:
        ImageFile._save(im, _idat(fp, chunk), [("zip", (0, 0) + im.size, 0, rawmode)])

    chunk(fp, b"IEND", b"")

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


# --------------------------------------------------------------------
# PNG chunk converter


def getchunks(im, **params):
    """Return a list of PNG chunks representing this image."""

    class collector:
        data = []

        def write(self, data):
            pass

        def append(self, chunk):
            self.data.append(chunk)

    def append(fp, cid, *data):
        data = b"".join(data)
        crc = o32(_crc32(data, _crc32(cid)))
        fp.append((cid, data, crc))

    fp = collector()

    try:
        im.encoderinfo = params
        _save(im, fp, None, append)
    finally:
        del im.encoderinfo

    return fp.data


# --------------------------------------------------------------------
# Registry

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

Image.register_extensions(PngImageFile.format, [".png", ".apng"])

Image.register_mime(PngImageFile.format, "image/png")

```
--- END FILE ---

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

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

Here is an example:

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

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
[ISSUE]
**Title:** `is_animated` Property Incorrectly Returns True for Single-Frame APNG Images

**Description:**
When loading a single-frame APNG image, the `is_animated` property incorrectly returns `True`. This behavior is inconsistent with other Pillow image formats and does not align with the expectation that `is_animated` should only be `True` when there are multiple frames.

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

with Image.open("Tests/images/apng/single_frame.png") as im:
    print(im.is_animated)  # Expected: False
    print(im.n_frames)     # Expected: 1
```

**Expected Behavior:**
For single-frame APNG images, `is_animated` should return `False`, and `n_frames` should be `1`. This ensures consistency across different image formats within Pillow.

**Actual Behavior:**
The `is_animated` property returns `True` even when `n_frames` is `1`, indicating that the image is animated when it is not. This leads to incorrect handling of single-frame APNG images in applications relying on this property.

[/ISSUE]
{
    "TestFilePng.test_apng_basic": "PASSED",
    "TestFilePng.test_apng_blend": "PASSED",
    "TestFilePng.test_apng_chunk_errors": "PASSED",
    "TestFilePng.test_apng_chunk_order": "PASSED",
    "TestFilePng.test_apng_delay": "PASSED",
    "TestFilePng.test_apng_dispose": "PASSED",
    "TestFilePng.test_apng_dispose_region": "PASSED",
    "TestFilePng.test_apng_fdat": "PASSED",
    "TestFilePng.test_apng_mode": "PASSED",
    "TestFilePng.test_apng_num_plays": "PASSED",
    "TestFilePng.test_apng_save": "PASSED",
    "TestFilePng.test_apng_save_blend": "PASSED",
    "TestFilePng.test_apng_save_disposal": "PASSED",
    "TestFilePng.test_apng_save_duration_loop": "PASSED",
    "TestFilePng.test_apng_save_split_fdat": "PASSED",
    "TestFilePng.test_apng_sequence_errors": "PASSED",
    "TestFilePng.test_apng_syntax_errors": "PASSED"
}
diff --git a/src/PIL/PngImagePlugin.py b/src/PIL/PngImagePlugin.py
index 398eade3c..dd3673b53 100644
--- a/src/PIL/PngImagePlugin.py
+++ b/src/PIL/PngImagePlugin.py
@@ -717,7 +717,7 @@ class PngImageFile(ImageFile.ImageFile):
 
     @property
     def is_animated(self):
-        return self._n_frames is not None
+        return self._n_frames is not None and self._n_frames > 1
 
     def verify(self):
         """Verify PNG file"""
 

{"src/PIL/PngImagePlugin.py": "#\n# The Python Imaging Library.\n# $Id$\n#\n# PNG support code\n#\n# See \"PNG (Portable Network Graphics) Specification, version 1.0;\n# W3C Recommendation\", 1996-10-01, Thomas Boutell (ed.).\n#\n# history:\n# 1996-05-06 fl   Created (couldn't resist it)\n# 1996-12-14 fl   Upgraded, added read and verify support (0.2)\n# 1996-12-15 fl   Separate PNG stream parser\n# 1996-12-29 fl   Added write support, added getchunks\n# 1996-12-30 fl   Eliminated circular references in decoder (0.3)\n# 1998-07-12 fl   Read/write 16-bit images as mode I (0.4)\n# 2001-02-08 fl   Added transparency support (from Zircon) (0.5)\n# 2001-04-16 fl   Don't close data source in \"open\" method (0.6)\n# 2004-02-24 fl   Don't even pretend to support interlaced files (0.7)\n# 2004-08-31 fl   Do basic sanity check on chunk identifiers (0.8)\n# 2004-09-20 fl   Added PngInfo chunk container\n# 2004-12-18 fl   Added DPI read support (based on code by Niki Spahiev)\n# 2008-08-13 fl   Added tRNS support for RGB images\n# 2009-03-06 fl   Support for preserving ICC profiles (by Florian Hoech)\n# 2009-03-08 fl   Added zTXT support (from Lowell Alleman)\n# 2009-03-29 fl   Read interlaced PNG files (from Conrado Porto Lopes Gouvua)\n#\n# Copyright (c) 1997-2009 by Secret Labs AB\n# Copyright (c) 1996 by Fredrik Lundh\n#\n# See the README file for information on usage and redistribution.\n#\n\nimport itertools\nimport logging\nimport re\nimport struct\nimport warnings\nimport zlib\n\nfrom . import Image, ImageChops, ImageFile, ImagePalette, ImageSequence\nfrom ._binary import i8, i16be as i16, i32be as i32, o8, o16be as o16, o32be as o32\n\nlogger = logging.getLogger(__name__)\n\nis_cid = re.compile(br\"\\w\\w\\w\\w\").match\n\n\n_MAGIC = b\"\\211PNG\\r\\n\\032\\n\"\n\n\n_MODES = {\n    # supported bits/color combinations, and corresponding modes/rawmodes\n    # Greyscale\n    (1, 0): (\"1\", \"1\"),\n    (2, 0): (\"L\", \"L;2\"),\n    (4, 0): (\"L\", \"L;4\"),\n    (8, 0): (\"L\", \"L\"),\n    (16, 0): (\"I\", \"I;16B\"),\n    # Truecolour\n    (8, 2): (\"RGB\", \"RGB\"),\n    (16, 2): (\"RGB\", \"RGB;16B\"),\n    # Indexed-colour\n    (1, 3): (\"P\", \"P;1\"),\n    (2, 3): (\"P\", \"P;2\"),\n    (4, 3): (\"P\", \"P;4\"),\n    (8, 3): (\"P\", \"P\"),\n    # Greyscale with alpha\n    (8, 4): (\"LA\", \"LA\"),\n    (16, 4): (\"RGBA\", \"LA;16B\"),  # LA;16B->LA not yet available\n    # Truecolour with alpha\n    (8, 6): (\"RGBA\", \"RGBA\"),\n    (16, 6): (\"RGBA\", \"RGBA;16B\"),\n}\n\n\n_simple_palette = re.compile(b\"^\\xff*\\x00\\xff*$\")\n\n# Maximum decompressed size for a iTXt or zTXt chunk.\n# Eliminates decompression bombs where compressed chunks can expand 1000x\nMAX_TEXT_CHUNK = ImageFile.SAFEBLOCK\n# Set the maximum total text chunk size.\nMAX_TEXT_MEMORY = 64 * MAX_TEXT_CHUNK\n\n\n# APNG frame disposal modes\nAPNG_DISPOSE_OP_NONE = 0\nAPNG_DISPOSE_OP_BACKGROUND = 1\nAPNG_DISPOSE_OP_PREVIOUS = 2\n\n# APNG frame blend modes\nAPNG_BLEND_OP_SOURCE = 0\nAPNG_BLEND_OP_OVER = 1\n\n\ndef _safe_zlib_decompress(s):\n    dobj = zlib.decompressobj()\n    plaintext = dobj.decompress(s, MAX_TEXT_CHUNK)\n    if dobj.unconsumed_tail:\n        raise ValueError(\"Decompressed Data Too Large\")\n    return plaintext\n\n\ndef _crc32(data, seed=0):\n    return zlib.crc32(data, seed) & 0xFFFFFFFF\n\n\n# --------------------------------------------------------------------\n# Support classes.  Suitable for PNG and related formats like MNG etc.\n\n\nclass ChunkStream:\n    def __init__(self, fp):\n\n        self.fp = fp\n        self.queue = []\n\n    def read(self):\n        \"\"\"Fetch a new chunk. Returns header information.\"\"\"\n        cid = None\n\n        if self.queue:\n            cid, pos, length = self.queue.pop()\n            self.fp.seek(pos)\n        else:\n            s = self.fp.read(8)\n            cid = s[4:]\n            pos = self.fp.tell()\n            length = i32(s)\n\n        if not is_cid(cid):\n            if not ImageFile.LOAD_TRUNCATED_IMAGES:\n                raise SyntaxError(\"broken PNG file (chunk %s)\" % repr(cid))\n\n        return cid, pos, length\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, *args):\n        self.close()\n\n    def close(self):\n        self.queue = self.crc = self.fp = None\n\n    def push(self, cid, pos, length):\n\n        self.queue.append((cid, pos, length))\n\n    def call(self, cid, pos, length):\n        \"\"\"Call the appropriate chunk handler\"\"\"\n\n        logger.debug(\"STREAM %r %s %s\", cid, pos, length)\n        return getattr(self, \"chunk_\" + cid.decode(\"ascii\"))(pos, length)\n\n    def crc(self, cid, data):\n        \"\"\"Read and verify checksum\"\"\"\n\n        # Skip CRC checks for ancillary chunks if allowed to load truncated\n        # images\n        # 5th byte of first char is 1 [specs, section 5.4]\n        if ImageFile.LOAD_TRUNCATED_IMAGES and (i8(cid[0]) >> 5 & 1):\n            self.crc_skip(cid, data)\n            return\n\n        try:\n            crc1 = _crc32(data, _crc32(cid))\n            crc2 = i32(self.fp.read(4))\n            if crc1 != crc2:\n                raise SyntaxError(\"broken PNG file (bad header checksum in %r)\" % cid)\n        except struct.error:\n            raise SyntaxError(\"broken PNG file (incomplete checksum in %r)\" % cid)\n\n    def crc_skip(self, cid, data):\n        \"\"\"Read checksum.  Used if the C module is not present\"\"\"\n\n        self.fp.read(4)\n\n    def verify(self, endchunk=b\"IEND\"):\n\n        # Simple approach; just calculate checksum for all remaining\n        # blocks.  Must be called directly after open.\n\n        cids = []\n\n        while True:\n            try:\n                cid, pos, length = self.read()\n            except struct.error:\n                raise OSError(\"truncated PNG file\")\n\n            if cid == endchunk:\n                break\n            self.crc(cid, ImageFile._safe_read(self.fp, length))\n            cids.append(cid)\n\n        return cids\n\n\nclass iTXt(str):\n    \"\"\"\n    Subclass of string to allow iTXt chunks to look like strings while\n    keeping their extra information\n\n    \"\"\"\n\n    @staticmethod\n    def __new__(cls, text, lang=None, tkey=None):\n        \"\"\"\n        :param cls: the class to use when creating the instance\n        :param text: value for this key\n        :param lang: language code\n        :param tkey: UTF-8 version of the key name\n        \"\"\"\n\n        self = str.__new__(cls, text)\n        self.lang = lang\n        self.tkey = tkey\n        return self\n\n\nclass PngInfo:\n    \"\"\"\n    PNG chunk container (for use with save(pnginfo=))\n\n    \"\"\"\n\n    def __init__(self):\n        self.chunks = []\n\n    def add(self, cid, data):\n        \"\"\"Appends an arbitrary chunk. Use with caution.\n\n        :param cid: a byte string, 4 bytes long.\n        :param data: a byte string of the encoded data\n\n        \"\"\"\n\n        self.chunks.append((cid, data))\n\n    def add_itxt(self, key, value, lang=\"\", tkey=\"\", zip=False):\n        \"\"\"Appends an iTXt chunk.\n\n        :param key: latin-1 encodable text key name\n        :param value: value for this key\n        :param lang: language code\n        :param tkey: UTF-8 version of the key name\n        :param zip: compression flag\n\n        \"\"\"\n\n        if not isinstance(key, bytes):\n            key = key.encode(\"latin-1\", \"strict\")\n        if not isinstance(value, bytes):\n            value = value.encode(\"utf-8\", \"strict\")\n        if not isinstance(lang, bytes):\n            lang = lang.encode(\"utf-8\", \"strict\")\n        if not isinstance(tkey, bytes):\n            tkey = tkey.encode(\"utf-8\", \"strict\")\n\n        if zip:\n            self.add(\n                b\"iTXt\",\n                key + b\"\\0\\x01\\0\" + lang + b\"\\0\" + tkey + b\"\\0\" + zlib.compress(value),\n            )\n        else:\n            self.add(b\"iTXt\", key + b\"\\0\\0\\0\" + lang + b\"\\0\" + tkey + b\"\\0\" + value)\n\n    def add_text(self, key, value, zip=False):\n        \"\"\"Appends a text chunk.\n\n        :param key: latin-1 encodable text key name\n        :param value: value for this key, text or an\n           :py:class:`PIL.PngImagePlugin.iTXt` instance\n        :param zip: compression flag\n\n        \"\"\"\n        if isinstance(value, iTXt):\n            return self.add_itxt(key, value, value.lang, value.tkey, zip=zip)\n\n        # The tEXt chunk stores latin-1 text\n        if not isinstance(value, bytes):\n            try:\n                value = value.encode(\"latin-1\", \"strict\")\n            except UnicodeError:\n                return self.add_itxt(key, value, zip=zip)\n\n        if not isinstance(key, bytes):\n            key = key.encode(\"latin-1\", \"strict\")\n\n        if zip:\n            self.add(b\"zTXt\", key + b\"\\0\\0\" + zlib.compress(value))\n        else:\n            self.add(b\"tEXt\", key + b\"\\0\" + value)\n\n\n# --------------------------------------------------------------------\n# PNG image stream (IHDR/IEND)\n\n\nclass PngStream(ChunkStream):\n    def __init__(self, fp):\n        super().__init__(fp)\n\n        # local copies of Image attributes\n        self.im_info = {}\n        self.im_text = {}\n        self.im_size = (0, 0)\n        self.im_mode = None\n        self.im_tile = None\n        self.im_palette = None\n        self.im_custom_mimetype = None\n        self.im_n_frames = None\n        self._seq_num = None\n        self.rewind_state = None\n\n        self.text_memory = 0\n\n    def check_text_memory(self, chunklen):\n        self.text_memory += chunklen\n        if self.text_memory > MAX_TEXT_MEMORY:\n            raise ValueError(\n                \"Too much memory used in text chunks: %s>MAX_TEXT_MEMORY\"\n                % self.text_memory\n            )\n\n    def save_rewind(self):\n        self.rewind_state = {\n            \"info\": self.im_info.copy(),\n            \"tile\": self.im_tile,\n            \"seq_num\": self._seq_num,\n        }\n\n    def rewind(self):\n        self.im_info = self.rewind_state[\"info\"]\n        self.im_tile = self.rewind_state[\"tile\"]\n        self._seq_num = self.rewind_state[\"seq_num\"]\n\n    def chunk_iCCP(self, pos, length):\n\n        # ICC profile\n        s = ImageFile._safe_read(self.fp, length)\n        # according to PNG spec, the iCCP chunk contains:\n        # Profile name  1-79 bytes (character string)\n        # Null separator        1 byte (null character)\n        # Compression method    1 byte (0)\n        # Compressed profile    n bytes (zlib with deflate compression)\n        i = s.find(b\"\\0\")\n        logger.debug(\"iCCP profile name %r\", s[:i])\n        logger.debug(\"Compression method %s\", i8(s[i]))\n        comp_method = i8(s[i])\n        if comp_method != 0:\n            raise SyntaxError(\n                \"Unknown compression method %s in iCCP chunk\" % comp_method\n            )\n        try:\n            icc_profile = _safe_zlib_decompress(s[i + 2 :])\n        except ValueError:\n            if ImageFile.LOAD_TRUNCATED_IMAGES:\n                icc_profile = None\n            else:\n                raise\n        except zlib.error:\n            icc_profile = None  # FIXME\n        self.im_info[\"icc_profile\"] = icc_profile\n        return s\n\n    def chunk_IHDR(self, pos, length):\n\n        # image header\n        s = ImageFile._safe_read(self.fp, length)\n        self.im_size = i32(s), i32(s[4:])\n        try:\n            self.im_mode, self.im_rawmode = _MODES[(i8(s[8]), i8(s[9]))]\n        except Exception:\n            pass\n        if i8(s[12]):\n            self.im_info[\"interlace\"] = 1\n        if i8(s[11]):\n            raise SyntaxError(\"unknown filter category\")\n        return s\n\n    def chunk_IDAT(self, pos, length):\n\n        # image data\n        if \"bbox\" in self.im_info:\n            tile = [(\"zip\", self.im_info[\"bbox\"], pos, self.im_rawmode)]\n        else:\n            if self.im_n_frames is not None:\n                self.im_info[\"default_image\"] = True\n            tile = [(\"zip\", (0, 0) + self.im_size, pos, self.im_rawmode)]\n        self.im_tile = tile\n        self.im_idat = length\n        raise EOFError\n\n    def chunk_IEND(self, pos, length):\n\n        # end of PNG image\n        raise EOFError\n\n    def chunk_PLTE(self, pos, length):\n\n        # palette\n        s = ImageFile._safe_read(self.fp, length)\n        if self.im_mode == \"P\":\n            self.im_palette = \"RGB\", s\n        return s\n\n    def chunk_tRNS(self, pos, length):\n\n        # transparency\n        s = ImageFile._safe_read(self.fp, length)\n        if self.im_mode == \"P\":\n            if _simple_palette.match(s):\n                # tRNS contains only one full-transparent entry,\n                # other entries are full opaque\n                i = s.find(b\"\\0\")\n                if i >= 0:\n                    self.im_info[\"transparency\"] = i\n            else:\n                # otherwise, we have a byte string with one alpha value\n                # for each palette entry\n                self.im_info[\"transparency\"] = s\n        elif self.im_mode in (\"1\", \"L\", \"I\"):\n            self.im_info[\"transparency\"] = i16(s)\n        elif self.im_mode == \"RGB\":\n            self.im_info[\"transparency\"] = i16(s), i16(s[2:]), i16(s[4:])\n        return s\n\n    def chunk_gAMA(self, pos, length):\n        # gamma setting\n        s = ImageFile._safe_read(self.fp, length)\n        self.im_info[\"gamma\"] = i32(s) / 100000.0\n        return s\n\n    def chunk_cHRM(self, pos, length):\n        # chromaticity, 8 unsigned ints, actual value is scaled by 100,000\n        # WP x,y, Red x,y, Green x,y Blue x,y\n\n        s = ImageFile._safe_read(self.fp, length)\n        raw_vals = struct.unpack(\">%dI\" % (len(s) // 4), s)\n        self.im_info[\"chromaticity\"] = tuple(elt / 100000.0 for elt in raw_vals)\n        return s\n\n    def chunk_sRGB(self, pos, length):\n        # srgb rendering intent, 1 byte\n        # 0 perceptual\n        # 1 relative colorimetric\n        # 2 saturation\n        # 3 absolute colorimetric\n\n        s = ImageFile._safe_read(self.fp, length)\n        self.im_info[\"srgb\"] = i8(s)\n        return s\n\n    def chunk_pHYs(self, pos, length):\n\n        # pixels per unit\n        s = ImageFile._safe_read(self.fp, length)\n        px, py = i32(s), i32(s[4:])\n        unit = i8(s[8])\n        if unit == 1:  # meter\n            dpi = int(px * 0.0254 + 0.5), int(py * 0.0254 + 0.5)\n            self.im_info[\"dpi\"] = dpi\n        elif unit == 0:\n            self.im_info[\"aspect\"] = px, py\n        return s\n\n    def chunk_tEXt(self, pos, length):\n\n        # text\n        s = ImageFile._safe_read(self.fp, length)\n        try:\n            k, v = s.split(b\"\\0\", 1)\n        except ValueError:\n            # fallback for broken tEXt tags\n            k = s\n            v = b\"\"\n        if k:\n            k = k.decode(\"latin-1\", \"strict\")\n            v = v.decode(\"latin-1\", \"replace\")\n\n            self.im_info[k] = self.im_text[k] = v\n            self.check_text_memory(len(v))\n\n        return s\n\n    def chunk_zTXt(self, pos, length):\n\n        # compressed text\n        s = ImageFile._safe_read(self.fp, length)\n        try:\n            k, v = s.split(b\"\\0\", 1)\n        except ValueError:\n            k = s\n            v = b\"\"\n        if v:\n            comp_method = i8(v[0])\n        else:\n            comp_method = 0\n        if comp_method != 0:\n            raise SyntaxError(\n                \"Unknown compression method %s in zTXt chunk\" % comp_method\n            )\n        try:\n            v = _safe_zlib_decompress(v[1:])\n        except ValueError:\n            if ImageFile.LOAD_TRUNCATED_IMAGES:\n                v = b\"\"\n            else:\n                raise\n        except zlib.error:\n            v = b\"\"\n\n        if k:\n            k = k.decode(\"latin-1\", \"strict\")\n            v = v.decode(\"latin-1\", \"replace\")\n\n            self.im_info[k] = self.im_text[k] = v\n            self.check_text_memory(len(v))\n\n        return s\n\n    def chunk_iTXt(self, pos, length):\n\n        # international text\n        r = s = ImageFile._safe_read(self.fp, length)\n        try:\n            k, r = r.split(b\"\\0\", 1)\n        except ValueError:\n            return s\n        if len(r) < 2:\n            return s\n        cf, cm, r = i8(r[0]), i8(r[1]), r[2:]\n        try:\n            lang, tk, v = r.split(b\"\\0\", 2)\n        except ValueError:\n            return s\n        if cf != 0:\n            if cm == 0:\n                try:\n                    v = _safe_zlib_decompress(v)\n                except ValueError:\n                    if ImageFile.LOAD_TRUNCATED_IMAGES:\n                        return s\n                    else:\n                        raise\n                except zlib.error:\n                    return s\n            else:\n                return s\n        try:\n            k = k.decode(\"latin-1\", \"strict\")\n            lang = lang.decode(\"utf-8\", \"strict\")\n            tk = tk.decode(\"utf-8\", \"strict\")\n            v = v.decode(\"utf-8\", \"strict\")\n        except UnicodeError:\n            return s\n\n        self.im_info[k] = self.im_text[k] = iTXt(v, lang, tk)\n        self.check_text_memory(len(v))\n\n        return s\n\n    def chunk_eXIf(self, pos, length):\n        s = ImageFile._safe_read(self.fp, length)\n        self.im_info[\"exif\"] = b\"Exif\\x00\\x00\" + s\n        return s\n\n    # APNG chunks\n    def chunk_acTL(self, pos, length):\n        s = ImageFile._safe_read(self.fp, length)\n        if self.im_n_frames is not None:\n            self.im_n_frames = None\n            warnings.warn(\"Invalid APNG, will use default PNG image if possible\")\n            return s\n        n_frames = i32(s)\n        if n_frames == 0 or n_frames > 0x80000000:\n            warnings.warn(\"Invalid APNG, will use default PNG image if possible\")\n            return s\n        self.im_n_frames = n_frames\n        self.im_info[\"loop\"] = i32(s[4:])\n        self.im_custom_mimetype = \"image/apng\"\n        return s\n\n    def chunk_fcTL(self, pos, length):\n        s = ImageFile._safe_read(self.fp, length)\n        seq = i32(s)\n        if (self._seq_num is None and seq != 0) or (\n            self._seq_num is not None and self._seq_num != seq - 1\n        ):\n            raise SyntaxError(\"APNG contains frame sequence errors\")\n        self._seq_num = seq\n        width, height = i32(s[4:]), i32(s[8:])\n        px, py = i32(s[12:]), i32(s[16:])\n        im_w, im_h = self.im_size\n        if px + width > im_w or py + height > im_h:\n            raise SyntaxError(\"APNG contains invalid frames\")\n        self.im_info[\"bbox\"] = (px, py, px + width, py + height)\n        delay_num, delay_den = i16(s[20:]), i16(s[22:])\n        if delay_den == 0:\n            delay_den = 100\n        self.im_info[\"duration\"] = float(delay_num) / float(delay_den) * 1000\n        self.im_info[\"disposal\"] = i8(s[24])\n        self.im_info[\"blend\"] = i8(s[25])\n        return s\n\n    def chunk_fdAT(self, pos, length):\n        s = ImageFile._safe_read(self.fp, 4)\n        seq = i32(s)\n        if self._seq_num != seq - 1:\n            raise SyntaxError(\"APNG contains frame sequence errors\")\n        self._seq_num = seq\n        return self.chunk_IDAT(pos + 4, length - 4)\n\n\n# --------------------------------------------------------------------\n# PNG reader\n\n\ndef _accept(prefix):\n    return prefix[:8] == _MAGIC\n\n\n##\n# Image plugin for PNG images.\n\n\nclass PngImageFile(ImageFile.ImageFile):\n\n    format = \"PNG\"\n    format_description = \"Portable network graphics\"\n\n    def _open(self):\n\n        if self.fp.read(8) != _MAGIC:\n            raise SyntaxError(\"not a PNG file\")\n        self.__fp = self.fp\n\n        #\n        # Parse headers up to the first IDAT or fDAT chunk\n\n        self.png = PngStream(self.fp)\n\n        while True:\n\n            #\n            # get next chunk\n\n            cid, pos, length = self.png.read()\n\n            try:\n                s = self.png.call(cid, pos, length)\n            except EOFError:\n                break\n            except AttributeError:\n                logger.debug(\"%r %s %s (unknown)\", cid, pos, length)\n                s = ImageFile._safe_read(self.fp, length)\n\n            self.png.crc(cid, s)\n\n        #\n        # Copy relevant attributes from the PngStream.  An alternative\n        # would be to let the PngStream class modify these attributes\n        # directly, but that introduces circular references which are\n        # difficult to break if things go wrong in the decoder...\n        # (believe me, I've tried ;-)\n\n        self.mode = self.png.im_mode\n        self._size = self.png.im_size\n        self.info = self.png.im_info\n        self._text = None\n        self.tile = self.png.im_tile\n        self.custom_mimetype = self.png.im_custom_mimetype\n        self._n_frames = self.png.im_n_frames\n        self.default_image = self.info.get(\"default_image\", False)\n\n        if self.png.im_palette:\n            rawmode, data = self.png.im_palette\n            self.palette = ImagePalette.raw(rawmode, data)\n\n        if cid == b\"fdAT\":\n            self.__prepare_idat = length - 4\n        else:\n            self.__prepare_idat = length  # used by load_prepare()\n\n        if self._n_frames is not None:\n            self._close_exclusive_fp_after_loading = False\n            self.png.save_rewind()\n            self.__rewind_idat = self.__prepare_idat\n            self.__rewind = self.__fp.tell()\n            if self.default_image:\n                # IDAT chunk contains default image and not first animation frame\n                self._n_frames += 1\n            self._seek(0)\n\n    @property\n    def text(self):\n        # experimental\n        if self._text is None:\n            # iTxt, tEXt and zTXt chunks may appear at the end of the file\n            # So load the file to ensure that they are read\n            if self.is_animated:\n                frame = self.__frame\n                # for APNG, seek to the final frame before loading\n                self.seek(self.n_frames - 1)\n            self.load()\n            if self.is_animated:\n                self.seek(frame)\n        return self._text\n\n    @property\n    def n_frames(self):\n        if self._n_frames is None:\n            return 1\n        return self._n_frames\n\n    @property\n    def is_animated(self):\n        return self._n_frames is not None\n\n    def verify(self):\n        \"\"\"Verify PNG file\"\"\"\n\n        if self.fp is None:\n            raise RuntimeError(\"verify must be called directly after open\")\n\n        # back up to beginning of IDAT block\n        self.fp.seek(self.tile[0][2] - 8)\n\n        self.png.verify()\n        self.png.close()\n\n        if self._exclusive_fp:\n            self.fp.close()\n        self.fp = None\n\n    def seek(self, frame):\n        if not self._seek_check(frame):\n            return\n        if frame < self.__frame:\n            self._seek(0, True)\n\n        last_frame = self.__frame\n        for f in range(self.__frame + 1, frame + 1):\n            try:\n                self._seek(f)\n            except EOFError:\n                self.seek(last_frame)\n                raise EOFError(\"no more images in APNG file\")\n\n    def _seek(self, frame, rewind=False):\n        if frame == 0:\n            if rewind:\n                self.__fp.seek(self.__rewind)\n                self.png.rewind()\n                self.__prepare_idat = self.__rewind_idat\n                self.im = None\n                if self.pyaccess:\n                    self.pyaccess = None\n                self.info = self.png.im_info\n                self.tile = self.png.im_tile\n                self.fp = self.__fp\n            self._prev_im = None\n            self.dispose = None\n            self.default_image = self.info.get(\"default_image\", False)\n            self.dispose_op = self.info.get(\"disposal\")\n            self.blend_op = self.info.get(\"blend\")\n            self.dispose_extent = self.info.get(\"bbox\")\n            self.__frame = 0\n            return\n        else:\n            if frame != self.__frame + 1:\n                raise ValueError(\"cannot seek to frame %d\" % frame)\n\n        # ensure previous frame was loaded\n        self.load()\n\n        self.fp = self.__fp\n\n        # advance to the next frame\n        if self.__prepare_idat:\n            ImageFile._safe_read(self.fp, self.__prepare_idat)\n            self.__prepare_idat = 0\n        frame_start = False\n        while True:\n            self.fp.read(4)  # CRC\n\n            try:\n                cid, pos, length = self.png.read()\n            except (struct.error, SyntaxError):\n                break\n\n            if cid == b\"IEND\":\n                raise EOFError(\"No more images in APNG file\")\n            if cid == b\"fcTL\":\n                if frame_start:\n                    # there must be at least one fdAT chunk between fcTL chunks\n                    raise SyntaxError(\"APNG missing frame data\")\n                frame_start = True\n\n            try:\n                self.png.call(cid, pos, length)\n            except UnicodeDecodeError:\n                break\n            except EOFError:\n                if cid == b\"fdAT\":\n                    length -= 4\n                    if frame_start:\n                        self.__prepare_idat = length\n                        break\n                ImageFile._safe_read(self.fp, length)\n            except AttributeError:\n                logger.debug(\"%r %s %s (unknown)\", cid, pos, length)\n                ImageFile._safe_read(self.fp, length)\n\n        self.__frame = frame\n        self.tile = self.png.im_tile\n        self.dispose_op = self.info.get(\"disposal\")\n        self.blend_op = self.info.get(\"blend\")\n        self.dispose_extent = self.info.get(\"bbox\")\n\n        if not self.tile:\n            raise EOFError\n\n    def tell(self):\n        return self.__frame\n\n    def load_prepare(self):\n        \"\"\"internal: prepare to read PNG file\"\"\"\n\n        if self.info.get(\"interlace\"):\n            self.decoderconfig = self.decoderconfig + (1,)\n\n        self.__idat = self.__prepare_idat  # used by load_read()\n        ImageFile.ImageFile.load_prepare(self)\n\n    def load_read(self, read_bytes):\n        \"\"\"internal: read more image data\"\"\"\n\n        while self.__idat == 0:\n            # end of chunk, skip forward to next one\n\n            self.fp.read(4)  # CRC\n\n            cid, pos, length = self.png.read()\n\n            if cid not in [b\"IDAT\", b\"DDAT\", b\"fdAT\"]:\n                self.png.push(cid, pos, length)\n                return b\"\"\n\n            if cid == b\"fdAT\":\n                try:\n                    self.png.call(cid, pos, length)\n                except EOFError:\n                    pass\n                self.__idat = length - 4  # sequence_num has already been read\n            else:\n                self.__idat = length  # empty chunks are allowed\n\n        # read more data from this chunk\n        if read_bytes <= 0:\n            read_bytes = self.__idat\n        else:\n            read_bytes = min(read_bytes, self.__idat)\n\n        self.__idat = self.__idat - read_bytes\n\n        return self.fp.read(read_bytes)\n\n    def load_end(self):\n        \"\"\"internal: finished reading image data\"\"\"\n        while True:\n            self.fp.read(4)  # CRC\n\n            try:\n                cid, pos, length = self.png.read()\n            except (struct.error, SyntaxError):\n                break\n\n            if cid == b\"IEND\":\n                break\n            elif cid == b\"fcTL\" and self.is_animated:\n                # start of the next frame, stop reading\n                self.__prepare_idat = 0\n                self.png.push(cid, pos, length)\n                break\n\n            try:\n                self.png.call(cid, pos, length)\n            except UnicodeDecodeError:\n                break\n            except EOFError:\n                if cid == b\"fdAT\":\n                    length -= 4\n                ImageFile._safe_read(self.fp, length)\n            except AttributeError:\n                logger.debug(\"%r %s %s (unknown)\", cid, pos, length)\n                ImageFile._safe_read(self.fp, length)\n        self._text = self.png.im_text\n        if not self.is_animated:\n            self.png.close()\n            self.png = None\n        else:\n            # setup frame disposal (actual disposal done when needed in _seek())\n            if self._prev_im is None and self.dispose_op == APNG_DISPOSE_OP_PREVIOUS:\n                self.dispose_op = APNG_DISPOSE_OP_BACKGROUND\n\n            if self.dispose_op == APNG_DISPOSE_OP_PREVIOUS:\n                dispose = self._prev_im.copy()\n                dispose = self._crop(dispose, self.dispose_extent)\n            elif self.dispose_op == APNG_DISPOSE_OP_BACKGROUND:\n                dispose = Image.core.fill(\"RGBA\", self.size, (0, 0, 0, 0))\n                dispose = self._crop(dispose, self.dispose_extent)\n            else:\n                dispose = None\n\n            if self._prev_im and self.blend_op == APNG_BLEND_OP_OVER:\n                updated = self._crop(self.im, self.dispose_extent)\n                self._prev_im.paste(\n                    updated, self.dispose_extent, updated.convert(\"RGBA\")\n                )\n                self.im = self._prev_im\n                if self.pyaccess:\n                    self.pyaccess = None\n            self._prev_im = self.im.copy()\n\n            if dispose:\n                self._prev_im.paste(dispose, self.dispose_extent)\n\n    def _getexif(self):\n        if \"exif\" not in self.info:\n            self.load()\n        if \"exif\" not in self.info:\n            return None\n        return dict(self.getexif())\n\n    def getexif(self):\n        if \"exif\" not in self.info:\n            self.load()\n        return ImageFile.ImageFile.getexif(self)\n\n    def _close__fp(self):\n        try:\n            if self.__fp != self.fp:\n                self.__fp.close()\n        except AttributeError:\n            pass\n        finally:\n            self.__fp = None\n\n\n# --------------------------------------------------------------------\n# PNG writer\n\n_OUTMODES = {\n    # supported PIL modes, and corresponding rawmodes/bits/color combinations\n    \"1\": (\"1\", b\"\\x01\\x00\"),\n    \"L;1\": (\"L;1\", b\"\\x01\\x00\"),\n    \"L;2\": (\"L;2\", b\"\\x02\\x00\"),\n    \"L;4\": (\"L;4\", b\"\\x04\\x00\"),\n    \"L\": (\"L\", b\"\\x08\\x00\"),\n    \"LA\": (\"LA\", b\"\\x08\\x04\"),\n    \"I\": (\"I;16B\", b\"\\x10\\x00\"),\n    \"I;16\": (\"I;16B\", b\"\\x10\\x00\"),\n    \"P;1\": (\"P;1\", b\"\\x01\\x03\"),\n    \"P;2\": (\"P;2\", b\"\\x02\\x03\"),\n    \"P;4\": (\"P;4\", b\"\\x04\\x03\"),\n    \"P\": (\"P\", b\"\\x08\\x03\"),\n    \"RGB\": (\"RGB\", b\"\\x08\\x02\"),\n    \"RGBA\": (\"RGBA\", b\"\\x08\\x06\"),\n}\n\n\ndef putchunk(fp, cid, *data):\n    \"\"\"Write a PNG chunk (including CRC field)\"\"\"\n\n    data = b\"\".join(data)\n\n    fp.write(o32(len(data)) + cid)\n    fp.write(data)\n    crc = _crc32(data, _crc32(cid))\n    fp.write(o32(crc))\n\n\nclass _idat:\n    # wrap output from the encoder in IDAT chunks\n\n    def __init__(self, fp, chunk):\n        self.fp = fp\n        self.chunk = chunk\n\n    def write(self, data):\n        self.chunk(self.fp, b\"IDAT\", data)\n\n\nclass _fdat:\n    # wrap encoder output in fdAT chunks\n\n    def __init__(self, fp, chunk, seq_num):\n        self.fp = fp\n        self.chunk = chunk\n        self.seq_num = seq_num\n\n    def write(self, data):\n        self.chunk(self.fp, b\"fdAT\", o32(self.seq_num), data)\n        self.seq_num += 1\n\n\ndef _write_multiple_frames(im, fp, chunk, rawmode):\n    default_image = im.encoderinfo.get(\"default_image\", im.info.get(\"default_image\"))\n    duration = im.encoderinfo.get(\"duration\", im.info.get(\"duration\", 0))\n    loop = im.encoderinfo.get(\"loop\", im.info.get(\"loop\", 0))\n    disposal = im.encoderinfo.get(\"disposal\", im.info.get(\"disposal\"))\n    blend = im.encoderinfo.get(\"blend\", im.info.get(\"blend\"))\n\n    if default_image:\n        chain = itertools.chain(im.encoderinfo.get(\"append_images\", []))\n    else:\n        chain = itertools.chain([im], im.encoderinfo.get(\"append_images\", []))\n\n    im_frames = []\n    frame_count = 0\n    for im_seq in chain:\n        for im_frame in ImageSequence.Iterator(im_seq):\n            im_frame = im_frame.copy()\n            if im_frame.mode != im.mode:\n                if im.mode == \"P\":\n                    im_frame = im_frame.convert(im.mode, palette=im.palette)\n                else:\n                    im_frame = im_frame.convert(im.mode)\n            encoderinfo = im.encoderinfo.copy()\n            if isinstance(duration, (list, tuple)):\n                encoderinfo[\"duration\"] = duration[frame_count]\n            if isinstance(disposal, (list, tuple)):\n                encoderinfo[\"disposal\"] = disposal[frame_count]\n            if isinstance(blend, (list, tuple)):\n                encoderinfo[\"blend\"] = blend[frame_count]\n            frame_count += 1\n\n            if im_frames:\n                previous = im_frames[-1]\n                prev_disposal = previous[\"encoderinfo\"].get(\"disposal\")\n                prev_blend = previous[\"encoderinfo\"].get(\"blend\")\n                if prev_disposal == APNG_DISPOSE_OP_PREVIOUS and len(im_frames) < 2:\n                    prev_disposal == APNG_DISPOSE_OP_BACKGROUND\n\n                if prev_disposal == APNG_DISPOSE_OP_BACKGROUND:\n                    base_im = previous[\"im\"]\n                    dispose = Image.core.fill(\"RGBA\", im.size, (0, 0, 0, 0))\n                    bbox = previous[\"bbox\"]\n                    if bbox:\n                        dispose = dispose.crop(bbox)\n                    else:\n                        bbox = (0, 0) + im.size\n                    base_im.paste(dispose, bbox)\n                elif prev_disposal == APNG_DISPOSE_OP_PREVIOUS:\n                    base_im = im_frames[-2][\"im\"]\n                else:\n                    base_im = previous[\"im\"]\n                delta = ImageChops.subtract_modulo(im_frame, base_im)\n                bbox = delta.getbbox()\n                if (\n                    not bbox\n                    and prev_disposal == encoderinfo.get(\"disposal\")\n                    and prev_blend == encoderinfo.get(\"blend\")\n                ):\n                    duration = encoderinfo.get(\"duration\", 0)\n                    if duration:\n                        if \"duration\" in previous[\"encoderinfo\"]:\n                            previous[\"encoderinfo\"][\"duration\"] += duration\n                        else:\n                            previous[\"encoderinfo\"][\"duration\"] = duration\n                    continue\n            else:\n                bbox = None\n            im_frames.append({\"im\": im_frame, \"bbox\": bbox, \"encoderinfo\": encoderinfo})\n\n    # animation control\n    chunk(\n        fp, b\"acTL\", o32(len(im_frames)), o32(loop),  # 0: num_frames  # 4: num_plays\n    )\n\n    # default image IDAT (if it exists)\n    if default_image:\n        ImageFile._save(im, _idat(fp, chunk), [(\"zip\", (0, 0) + im.size, 0, rawmode)])\n\n    seq_num = 0\n    for frame, frame_data in enumerate(im_frames):\n        im_frame = frame_data[\"im\"]\n        if not frame_data[\"bbox\"]:\n            bbox = (0, 0) + im_frame.size\n        else:\n            bbox = frame_data[\"bbox\"]\n            im_frame = im_frame.crop(bbox)\n        size = im_frame.size\n        duration = int(round(frame_data[\"encoderinfo\"].get(\"duration\", 0)))\n        disposal = frame_data[\"encoderinfo\"].get(\"disposal\", APNG_DISPOSE_OP_NONE)\n        blend = frame_data[\"encoderinfo\"].get(\"blend\", APNG_BLEND_OP_SOURCE)\n        # frame control\n        chunk(\n            fp,\n            b\"fcTL\",\n            o32(seq_num),  # sequence_number\n            o32(size[0]),  # width\n            o32(size[1]),  # height\n            o32(bbox[0]),  # x_offset\n            o32(bbox[1]),  # y_offset\n            o16(duration),  # delay_numerator\n            o16(1000),  # delay_denominator\n            o8(disposal),  # dispose_op\n            o8(blend),  # blend_op\n        )\n        seq_num += 1\n        # frame data\n        if frame == 0 and not default_image:\n            # first frame must be in IDAT chunks for backwards compatibility\n            ImageFile._save(\n                im_frame,\n                _idat(fp, chunk),\n                [(\"zip\", (0, 0) + im_frame.size, 0, rawmode)],\n            )\n        else:\n            fdat_chunks = _fdat(fp, chunk, seq_num)\n            ImageFile._save(\n                im_frame, fdat_chunks, [(\"zip\", (0, 0) + im_frame.size, 0, rawmode)],\n            )\n            seq_num = fdat_chunks.seq_num\n\n\ndef _save_all(im, fp, filename):\n    _save(im, fp, filename, save_all=True)\n\n\ndef _save(im, fp, filename, chunk=putchunk, save_all=False):\n    # save an image to disk (called by the save method)\n\n    mode = im.mode\n\n    if mode == \"P\":\n\n        #\n        # attempt to minimize storage requirements for palette images\n        if \"bits\" in im.encoderinfo:\n            # number of bits specified by user\n            colors = 1 << im.encoderinfo[\"bits\"]\n        else:\n            # check palette contents\n            if im.palette:\n                colors = max(min(len(im.palette.getdata()[1]) // 3, 256), 2)\n            else:\n                colors = 256\n\n        if colors <= 2:\n            bits = 1\n        elif colors <= 4:\n            bits = 2\n        elif colors <= 16:\n            bits = 4\n        else:\n            bits = 8\n        if bits != 8:\n            mode = \"%s;%d\" % (mode, bits)\n\n    # encoder options\n    im.encoderconfig = (\n        im.encoderinfo.get(\"optimize\", False),\n        im.encoderinfo.get(\"compress_level\", -1),\n        im.encoderinfo.get(\"compress_type\", -1),\n        im.encoderinfo.get(\"dictionary\", b\"\"),\n    )\n\n    # get the corresponding PNG mode\n    try:\n        rawmode, mode = _OUTMODES[mode]\n    except KeyError:\n        raise OSError(\"cannot write mode %s as PNG\" % mode)\n\n    #\n    # write minimal PNG file\n\n    fp.write(_MAGIC)\n\n    chunk(\n        fp,\n        b\"IHDR\",\n        o32(im.size[0]),  # 0: size\n        o32(im.size[1]),\n        mode,  # 8: depth/type\n        b\"\\0\",  # 10: compression\n        b\"\\0\",  # 11: filter category\n        b\"\\0\",  # 12: interlace flag\n    )\n\n    chunks = [b\"cHRM\", b\"gAMA\", b\"sBIT\", b\"sRGB\", b\"tIME\"]\n\n    icc = im.encoderinfo.get(\"icc_profile\", im.info.get(\"icc_profile\"))\n    if icc:\n        # ICC profile\n        # according to PNG spec, the iCCP chunk contains:\n        # Profile name  1-79 bytes (character string)\n        # Null separator        1 byte (null character)\n        # Compression method    1 byte (0)\n        # Compressed profile    n bytes (zlib with deflate compression)\n        name = b\"ICC Profile\"\n        data = name + b\"\\0\\0\" + zlib.compress(icc)\n        chunk(fp, b\"iCCP\", data)\n\n        # You must either have sRGB or iCCP.\n        # Disallow sRGB chunks when an iCCP-chunk has been emitted.\n        chunks.remove(b\"sRGB\")\n\n    info = im.encoderinfo.get(\"pnginfo\")\n    if info:\n        chunks_multiple_allowed = [b\"sPLT\", b\"iTXt\", b\"tEXt\", b\"zTXt\"]\n        for cid, data in info.chunks:\n            if cid in chunks:\n                chunks.remove(cid)\n                chunk(fp, cid, data)\n            elif cid in chunks_multiple_allowed:\n                chunk(fp, cid, data)\n\n    if im.mode == \"P\":\n        palette_byte_number = (2 ** bits) * 3\n        palette_bytes = im.im.getpalette(\"RGB\")[:palette_byte_number]\n        while len(palette_bytes) < palette_byte_number:\n            palette_bytes += b\"\\0\"\n        chunk(fp, b\"PLTE\", palette_bytes)\n\n    transparency = im.encoderinfo.get(\"transparency\", im.info.get(\"transparency\", None))\n\n    if transparency or transparency == 0:\n        if im.mode == \"P\":\n            # limit to actual palette size\n            alpha_bytes = 2 ** bits\n            if isinstance(transparency, bytes):\n                chunk(fp, b\"tRNS\", transparency[:alpha_bytes])\n            else:\n                transparency = max(0, min(255, transparency))\n                alpha = b\"\\xFF\" * transparency + b\"\\0\"\n                chunk(fp, b\"tRNS\", alpha[:alpha_bytes])\n        elif im.mode in (\"1\", \"L\", \"I\"):\n            transparency = max(0, min(65535, transparency))\n            chunk(fp, b\"tRNS\", o16(transparency))\n        elif im.mode == \"RGB\":\n            red, green, blue = transparency\n            chunk(fp, b\"tRNS\", o16(red) + o16(green) + o16(blue))\n        else:\n            if \"transparency\" in im.encoderinfo:\n                # don't bother with transparency if it's an RGBA\n                # and it's in the info dict. It's probably just stale.\n                raise OSError(\"cannot use transparency for this mode\")\n    else:\n        if im.mode == \"P\" and im.im.getpalettemode() == \"RGBA\":\n            alpha = im.im.getpalette(\"RGBA\", \"A\")\n            alpha_bytes = 2 ** bits\n            chunk(fp, b\"tRNS\", alpha[:alpha_bytes])\n\n    dpi = im.encoderinfo.get(\"dpi\")\n    if dpi:\n        chunk(\n            fp,\n            b\"pHYs\",\n            o32(int(dpi[0] / 0.0254 + 0.5)),\n            o32(int(dpi[1] / 0.0254 + 0.5)),\n            b\"\\x01\",\n        )\n\n    if info:\n        chunks = [b\"bKGD\", b\"hIST\"]\n        for cid, data in info.chunks:\n            if cid in chunks:\n                chunks.remove(cid)\n                chunk(fp, cid, data)\n\n    exif = im.encoderinfo.get(\"exif\", im.info.get(\"exif\"))\n    if exif:\n        if isinstance(exif, Image.Exif):\n            exif = exif.tobytes(8)\n        if exif.startswith(b\"Exif\\x00\\x00\"):\n            exif = exif[6:]\n        chunk(fp, b\"eXIf\", exif)\n\n    if save_all:\n        _write_multiple_frames(im, fp, chunk, rawmode)\n    else:\n        ImageFile._save(im, _idat(fp, chunk), [(\"zip\", (0, 0) + im.size, 0, rawmode)])\n\n    chunk(fp, b\"IEND\", b\"\")\n\n    if hasattr(fp, \"flush\"):\n        fp.flush()\n\n\n# --------------------------------------------------------------------\n# PNG chunk converter\n\n\ndef getchunks(im, **params):\n    \"\"\"Return a list of PNG chunks representing this image.\"\"\"\n\n    class collector:\n        data = []\n\n        def write(self, data):\n            pass\n\n        def append(self, chunk):\n            self.data.append(chunk)\n\n    def append(fp, cid, *data):\n        data = b\"\".join(data)\n        crc = o32(_crc32(data, _crc32(cid)))\n        fp.append((cid, data, crc))\n\n    fp = collector()\n\n    try:\n        im.encoderinfo = params\n        _save(im, fp, None, append)\n    finally:\n        del im.encoderinfo\n\n    return fp.data\n\n\n# --------------------------------------------------------------------\n# Registry\n\nImage.register_open(PngImageFile.format, PngImageFile, _accept)\nImage.register_save(PngImageFile.format, _save)\nImage.register_save_all(PngImageFile.format, _save_all)\n\nImage.register_extensions(PngImageFile.format, [\".png\", \".apng\"])\n\nImage.register_mime(PngImageFile.format, \"image/png\")\n"}
A user will ask you to solve a task. You should first draft your thinking process (inner monologue). Then, generate the solution.

Your response format must follow the template below:
<think>
Your thoughts or/and draft, like working through an exercise on scratch paper. Be as casual and as long as you want until you are confident to generate a correct solution.
</think>
<solution>
Final solution presented to the user.
</solution>
system
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** `is_animated` Property Incorrectly Returns True for Single-Frame APNG Images

**Description:**
When loading a single-frame APNG image, the `is_animated` property incorrectly returns `True`. This behavior is inconsistent with other Pillow image formats and does not align with the expectation that `is_animated` should only be `True` when there are multiple frames.

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

with Image.open("Tests/images/apng/single_frame.png") as im:
    print(im.is_animated)  # Expected: False
    print(im.n_frames)     # Expected: 1
```

**Expected Behavior:**
For single-frame APNG images, `is_animated` should return `False`, and `n_frames` should be `1`. This ensures consistency across different image formats within Pillow.

**Actual Behavior:**
The `is_animated` property returns `True` even when `n_frames` is `1`, indicating that the image is animated when it is not. This leads to incorrect handling of single-frame APNG images in applications relying on this property.

[/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/PngImagePlugin.py
#
# The Python Imaging Library.
# $Id$
#
# PNG support code
#
# See "PNG (Portable Network Graphics) Specification, version 1.0;
# W3C Recommendation", 1996-10-01, Thomas Boutell (ed.).
#
# history:
# 1996-05-06 fl   Created (couldn't resist it)
# 1996-12-14 fl   Upgraded, added read and verify support (0.2)
# 1996-12-15 fl   Separate PNG stream parser
# 1996-12-29 fl   Added write support, added getchunks
# 1996-12-30 fl   Eliminated circular references in decoder (0.3)
# 1998-07-12 fl   Read/write 16-bit images as mode I (0.4)
# 2001-02-08 fl   Added transparency support (from Zircon) (0.5)
# 2001-04-16 fl   Don't close data source in "open" method (0.6)
# 2004-02-24 fl   Don't even pretend to support interlaced files (0.7)
# 2004-08-31 fl   Do basic sanity check on chunk identifiers (0.8)
# 2004-09-20 fl   Added PngInfo chunk container
# 2004-12-18 fl   Added DPI read support (based on code by Niki Spahiev)
# 2008-08-13 fl   Added tRNS support for RGB images
# 2009-03-06 fl   Support for preserving ICC profiles (by Florian Hoech)
# 2009-03-08 fl   Added zTXT support (from Lowell Alleman)
# 2009-03-29 fl   Read interlaced PNG files (from Conrado Porto Lopes Gouvua)
#
# Copyright (c) 1997-2009 by Secret Labs AB
# Copyright (c) 1996 by Fredrik Lundh
#
# See the README file for information on usage and redistribution.
#

import itertools
import logging
import re
import struct
import warnings
import zlib

from . import Image, ImageChops, ImageFile, ImagePalette, ImageSequence
from ._binary import i8, i16be as i16, i32be as i32, o8, o16be as o16, o32be as o32

logger = logging.getLogger(__name__)

is_cid = re.compile(br"\w\w\w\w").match


_MAGIC = b"\211PNG\r\n\032\n"


_MODES = {
    # supported bits/color combinations, and corresponding modes/rawmodes
    # Greyscale
    (1, 0): ("1", "1"),
    (2, 0): ("L", "L;2"),
    (4, 0): ("L", "L;4"),
    (8, 0): ("L", "L"),
    (16, 0): ("I", "I;16B"),
    # Truecolour
    (8, 2): ("RGB", "RGB"),
    (16, 2): ("RGB", "RGB;16B"),
    # Indexed-colour
    (1, 3): ("P", "P;1"),
    (2, 3): ("P", "P;2"),
    (4, 3): ("P", "P;4"),
    (8, 3): ("P", "P"),
    # Greyscale with alpha
    (8, 4): ("LA", "LA"),
    (16, 4): ("RGBA", "LA;16B"),  # LA;16B->LA not yet available
    # Truecolour with alpha
    (8, 6): ("RGBA", "RGBA"),
    (16, 6): ("RGBA", "RGBA;16B"),
}


_simple_palette = re.compile(b"^\xff*\x00\xff*$")

# Maximum decompressed size for a iTXt or zTXt chunk.
# Eliminates decompression bombs where compressed chunks can expand 1000x
MAX_TEXT_CHUNK = ImageFile.SAFEBLOCK
# Set the maximum total text chunk size.
MAX_TEXT_MEMORY = 64 * MAX_TEXT_CHUNK


# APNG frame disposal modes
APNG_DISPOSE_OP_NONE = 0
APNG_DISPOSE_OP_BACKGROUND = 1
APNG_DISPOSE_OP_PREVIOUS = 2

# APNG frame blend modes
APNG_BLEND_OP_SOURCE = 0
APNG_BLEND_OP_OVER = 1


def _safe_zlib_decompress(s):
    dobj = zlib.decompressobj()
    plaintext = dobj.decompress(s, MAX_TEXT_CHUNK)
    if dobj.unconsumed_tail:
        raise ValueError("Decompressed Data Too Large")
    return plaintext


def _crc32(data, seed=0):
    return zlib.crc32(data, seed) & 0xFFFFFFFF


# --------------------------------------------------------------------
# Support classes.  Suitable for PNG and related formats like MNG etc.


class ChunkStream:
    def __init__(self, fp):

        self.fp = fp
        self.queue = []

    def read(self):
        """Fetch a new chunk. Returns header information."""
        cid = None

        if self.queue:
            cid, pos, length = self.queue.pop()
            self.fp.seek(pos)
        else:
            s = self.fp.read(8)
            cid = s[4:]
            pos = self.fp.tell()
            length = i32(s)

        if not is_cid(cid):
            if not ImageFile.LOAD_TRUNCATED_IMAGES:
                raise SyntaxError("broken PNG file (chunk %s)" % repr(cid))

        return cid, pos, length

    def __enter__(self):
        return self

    def __exit__(self, *args):
        self.close()

    def close(self):
        self.queue = self.crc = self.fp = None

    def push(self, cid, pos, length):

        self.queue.append((cid, pos, length))

    def call(self, cid, pos, length):
        """Call the appropriate chunk handler"""

        logger.debug("STREAM %r %s %s", cid, pos, length)
        return getattr(self, "chunk_" + cid.decode("ascii"))(pos, length)

    def crc(self, cid, data):
        """Read and verify checksum"""

        # Skip CRC checks for ancillary chunks if allowed to load truncated
        # images
        # 5th byte of first char is 1 [specs, section 5.4]
        if ImageFile.LOAD_TRUNCATED_IMAGES and (i8(cid[0]) >> 5 & 1):
            self.crc_skip(cid, data)
            return

        try:
            crc1 = _crc32(data, _crc32(cid))
            crc2 = i32(self.fp.read(4))
            if crc1 != crc2:
                raise SyntaxError("broken PNG file (bad header checksum in %r)" % cid)
        except struct.error:
            raise SyntaxError("broken PNG file (incomplete checksum in %r)" % cid)

    def crc_skip(self, cid, data):
        """Read checksum.  Used if the C module is not present"""

        self.fp.read(4)

    def verify(self, endchunk=b"IEND"):

        # Simple approach; just calculate checksum for all remaining
        # blocks.  Must be called directly after open.

        cids = []

        while True:
            try:
                cid, pos, length = self.read()
            except struct.error:
                raise OSError("truncated PNG file")

            if cid == endchunk:
                break
            self.crc(cid, ImageFile._safe_read(self.fp, length))
            cids.append(cid)

        return cids


class iTXt(str):
    """
    Subclass of string to allow iTXt chunks to look like strings while
    keeping their extra information

    """

    @staticmethod
    def __new__(cls, text, lang=None, tkey=None):
        """
        :param cls: the class to use when creating the instance
        :param text: value for this key
        :param lang: language code
        :param tkey: UTF-8 version of the key name
        """

        self = str.__new__(cls, text)
        self.lang = lang
        self.tkey = tkey
        return self


class PngInfo:
    """
    PNG chunk container (for use with save(pnginfo=))

    """

    def __init__(self):
        self.chunks = []

    def add(self, cid, data):
        """Appends an arbitrary chunk. Use with caution.

        :param cid: a byte string, 4 bytes long.
        :param data: a byte string of the encoded data

        """

        self.chunks.append((cid, data))

    def add_itxt(self, key, value, lang="", tkey="", zip=False):
        """Appends an iTXt chunk.

        :param key: latin-1 encodable text key name
        :param value: value for this key
        :param lang: language code
        :param tkey: UTF-8 version of the key name
        :param zip: compression flag

        """

        if not isinstance(key, bytes):
            key = key.encode("latin-1", "strict")
        if not isinstance(value, bytes):
            value = value.encode("utf-8", "strict")
        if not isinstance(lang, bytes):
            lang = lang.encode("utf-8", "strict")
        if not isinstance(tkey, bytes):
            tkey = tkey.encode("utf-8", "strict")

        if zip:
            self.add(
                b"iTXt",
                key + b"\0\x01\0" + lang + b"\0" + tkey + b"\0" + zlib.compress(value),
            )
        else:
            self.add(b"iTXt", key + b"\0\0\0" + lang + b"\0" + tkey + b"\0" + value)

    def add_text(self, key, value, zip=False):
        """Appends a text chunk.

        :param key: latin-1 encodable text key name
        :param value: value for this key, text or an
           :py:class:`PIL.PngImagePlugin.iTXt` instance
        :param zip: compression flag

        """
        if isinstance(value, iTXt):
            return self.add_itxt(key, value, value.lang, value.tkey, zip=zip)

        # The tEXt chunk stores latin-1 text
        if not isinstance(value, bytes):
            try:
                value = value.encode("latin-1", "strict")
            except UnicodeError:
                return self.add_itxt(key, value, zip=zip)

        if not isinstance(key, bytes):
            key = key.encode("latin-1", "strict")

        if zip:
            self.add(b"zTXt", key + b"\0\0" + zlib.compress(value))
        else:
            self.add(b"tEXt", key + b"\0" + value)


# --------------------------------------------------------------------
# PNG image stream (IHDR/IEND)


class PngStream(ChunkStream):
    def __init__(self, fp):
        super().__init__(fp)

        # local copies of Image attributes
        self.im_info = {}
        self.im_text = {}
        self.im_size = (0, 0)
        self.im_mode = None
        self.im_tile = None
        self.im_palette = None
        self.im_custom_mimetype = None
        self.im_n_frames = None
        self._seq_num = None
        self.rewind_state = None

        self.text_memory = 0

    def check_text_memory(self, chunklen):
        self.text_memory += chunklen
        if self.text_memory > MAX_TEXT_MEMORY:
            raise ValueError(
                "Too much memory used in text chunks: %s>MAX_TEXT_MEMORY"
                % self.text_memory
            )

    def save_rewind(self):
        self.rewind_state = {
            "info": self.im_info.copy(),
            "tile": self.im_tile,
            "seq_num": self._seq_num,
        }

    def rewind(self):
        self.im_info = self.rewind_state["info"]
        self.im_tile = self.rewind_state["tile"]
        self._seq_num = self.rewind_state["seq_num"]

    def chunk_iCCP(self, pos, length):

        # ICC profile
        s = ImageFile._safe_read(self.fp, length)
        # according to PNG spec, the iCCP chunk contains:
        # Profile name  1-79 bytes (character string)
        # Null separator        1 byte (null character)
        # Compression method    1 byte (0)
        # Compressed profile    n bytes (zlib with deflate compression)
        i = s.find(b"\0")
        logger.debug("iCCP profile name %r", s[:i])
        logger.debug("Compression method %s", i8(s[i]))
        comp_method = i8(s[i])
        if comp_method != 0:
            raise SyntaxError(
                "Unknown compression method %s in iCCP chunk" % comp_method
            )
        try:
            icc_profile = _safe_zlib_decompress(s[i + 2 :])
        except ValueError:
            if ImageFile.LOAD_TRUNCATED_IMAGES:
                icc_profile = None
            else:
                raise
        except zlib.error:
            icc_profile = None  # FIXME
        self.im_info["icc_profile"] = icc_profile
        return s

    def chunk_IHDR(self, pos, length):

        # image header
        s = ImageFile._safe_read(self.fp, length)
        self.im_size = i32(s), i32(s[4:])
        try:
            self.im_mode, self.im_rawmode = _MODES[(i8(s[8]), i8(s[9]))]
        except Exception:
            pass
        if i8(s[12]):
            self.im_info["interlace"] = 1
        if i8(s[11]):
            raise SyntaxError("unknown filter category")
        return s

    def chunk_IDAT(self, pos, length):

        # image data
        if "bbox" in self.im_info:
            tile = [("zip", self.im_info["bbox"], pos, self.im_rawmode)]
        else:
            if self.im_n_frames is not None:
                self.im_info["default_image"] = True
            tile = [("zip", (0, 0) + self.im_size, pos, self.im_rawmode)]
        self.im_tile = tile
        self.im_idat = length
        raise EOFError

    def chunk_IEND(self, pos, length):

        # end of PNG image
        raise EOFError

    def chunk_PLTE(self, pos, length):

        # palette
        s = ImageFile._safe_read(self.fp, length)
        if self.im_mode == "P":
            self.im_palette = "RGB", s
        return s

    def chunk_tRNS(self, pos, length):

        # transparency
        s = ImageFile._safe_read(self.fp, length)
        if self.im_mode == "P":
            if _simple_palette.match(s):
                # tRNS contains only one full-transparent entry,
                # other entries are full opaque
                i = s.find(b"\0")
                if i >= 0:
                    self.im_info["transparency"] = i
            else:
                # otherwise, we have a byte string with one alpha value
                # for each palette entry
                self.im_info["transparency"] = s
        elif self.im_mode in ("1", "L", "I"):
            self.im_info["transparency"] = i16(s)
        elif self.im_mode == "RGB":
            self.im_info["transparency"] = i16(s), i16(s[2:]), i16(s[4:])
        return s

    def chunk_gAMA(self, pos, length):
        # gamma setting
        s = ImageFile._safe_read(self.fp, length)
        self.im_info["gamma"] = i32(s) / 100000.0
        return s

    def chunk_cHRM(self, pos, length):
        # chromaticity, 8 unsigned ints, actual value is scaled by 100,000
        # WP x,y, Red x,y, Green x,y Blue x,y

        s = ImageFile._safe_read(self.fp, length)
        raw_vals = struct.unpack(">%dI" % (len(s) // 4), s)
        self.im_info["chromaticity"] = tuple(elt / 100000.0 for elt in raw_vals)
        return s

    def chunk_sRGB(self, pos, length):
        # srgb rendering intent, 1 byte
        # 0 perceptual
        # 1 relative colorimetric
        # 2 saturation
        # 3 absolute colorimetric

        s = ImageFile._safe_read(self.fp, length)
        self.im_info["srgb"] = i8(s)
        return s

    def chunk_pHYs(self, pos, length):

        # pixels per unit
        s = ImageFile._safe_read(self.fp, length)
        px, py = i32(s), i32(s[4:])
        unit = i8(s[8])
        if unit == 1:  # meter
            dpi = int(px * 0.0254 + 0.5), int(py * 0.0254 + 0.5)
            self.im_info["dpi"] = dpi
        elif unit == 0:
            self.im_info["aspect"] = px, py
        return s

    def chunk_tEXt(self, pos, length):

        # text
        s = ImageFile._safe_read(self.fp, length)
        try:
            k, v = s.split(b"\0", 1)
        except ValueError:
            # fallback for broken tEXt tags
            k = s
            v = b""
        if k:
            k = k.decode("latin-1", "strict")
            v = v.decode("latin-1", "replace")

            self.im_info[k] = self.im_text[k] = v
            self.check_text_memory(len(v))

        return s

    def chunk_zTXt(self, pos, length):

        # compressed text
        s = ImageFile._safe_read(self.fp, length)
        try:
            k, v = s.split(b"\0", 1)
        except ValueError:
            k = s
            v = b""
        if v:
            comp_method = i8(v[0])
        else:
            comp_method = 0
        if comp_method != 0:
            raise SyntaxError(
                "Unknown compression method %s in zTXt chunk" % comp_method
            )
        try:
            v = _safe_zlib_decompress(v[1:])
        except ValueError:
            if ImageFile.LOAD_TRUNCATED_IMAGES:
                v = b""
            else:
                raise
        except zlib.error:
            v = b""

        if k:
            k = k.decode("latin-1", "strict")
            v = v.decode("latin-1", "replace")

            self.im_info[k] = self.im_text[k] = v
            self.check_text_memory(len(v))

        return s

    def chunk_iTXt(self, pos, length):

        # international text
        r = s = ImageFile._safe_read(self.fp, length)
        try:
            k, r = r.split(b"\0", 1)
        except ValueError:
            return s
        if len(r) < 2:
            return s
        cf, cm, r = i8(r[0]), i8(r[1]), r[2:]
        try:
            lang, tk, v = r.split(b"\0", 2)
        except ValueError:
            return s
        if cf != 0:
            if cm == 0:
                try:
                    v = _safe_zlib_decompress(v)
                except ValueError:
                    if ImageFile.LOAD_TRUNCATED_IMAGES:
                        return s
                    else:
                        raise
                except zlib.error:
                    return s
            else:
                return s
        try:
            k = k.decode("latin-1", "strict")
            lang = lang.decode("utf-8", "strict")
            tk = tk.decode("utf-8", "strict")
            v = v.decode("utf-8", "strict")
        except UnicodeError:
            return s

        self.im_info[k] = self.im_text[k] = iTXt(v, lang, tk)
        self.check_text_memory(len(v))

        return s

    def chunk_eXIf(self, pos, length):
        s = ImageFile._safe_read(self.fp, length)
        self.im_info["exif"] = b"Exif\x00\x00" + s
        return s

    # APNG chunks
    def chunk_acTL(self, pos, length):
        s = ImageFile._safe_read(self.fp, length)
        if self.im_n_frames is not None:
            self.im_n_frames = None
            warnings.warn("Invalid APNG, will use default PNG image if possible")
            return s
        n_frames = i32(s)
        if n_frames == 0 or n_frames > 0x80000000:
            warnings.warn("Invalid APNG, will use default PNG image if possible")
            return s
        self.im_n_frames = n_frames
        self.im_info["loop"] = i32(s[4:])
        self.im_custom_mimetype = "image/apng"
        return s

    def chunk_fcTL(self, pos, length):
        s = ImageFile._safe_read(self.fp, length)
        seq = i32(s)
        if (self._seq_num is None and seq != 0) or (
            self._seq_num is not None and self._seq_num != seq - 1
        ):
            raise SyntaxError("APNG contains frame sequence errors")
        self._seq_num = seq
        width, height = i32(s[4:]), i32(s[8:])
        px, py = i32(s[12:]), i32(s[16:])
        im_w, im_h = self.im_size
        if px + width > im_w or py + height > im_h:
            raise SyntaxError("APNG contains invalid frames")
        self.im_info["bbox"] = (px, py, px + width, py + height)
        delay_num, delay_den = i16(s[20:]), i16(s[22:])
        if delay_den == 0:
            delay_den = 100
        self.im_info["duration"] = float(delay_num) / float(delay_den) * 1000
        self.im_info["disposal"] = i8(s[24])
        self.im_info["blend"] = i8(s[25])
        return s

    def chunk_fdAT(self, pos, length):
        s = ImageFile._safe_read(self.fp, 4)
        seq = i32(s)
        if self._seq_num != seq - 1:
            raise SyntaxError("APNG contains frame sequence errors")
        self._seq_num = seq
        return self.chunk_IDAT(pos + 4, length - 4)


# --------------------------------------------------------------------
# PNG reader


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


##
# Image plugin for PNG images.


class PngImageFile(ImageFile.ImageFile):

    format = "PNG"
    format_description = "Portable network graphics"

    def _open(self):

        if self.fp.read(8) != _MAGIC:
            raise SyntaxError("not a PNG file")
        self.__fp = self.fp

        #
        # Parse headers up to the first IDAT or fDAT chunk

        self.png = PngStream(self.fp)

        while True:

            #
            # get next chunk

            cid, pos, length = self.png.read()

            try:
                s = self.png.call(cid, pos, length)
            except EOFError:
                break
            except AttributeError:
                logger.debug("%r %s %s (unknown)", cid, pos, length)
                s = ImageFile._safe_read(self.fp, length)

            self.png.crc(cid, s)

        #
        # Copy relevant attributes from the PngStream.  An alternative
        # would be to let the PngStream class modify these attributes
        # directly, but that introduces circular references which are
        # difficult to break if things go wrong in the decoder...
        # (believe me, I've tried ;-)

        self.mode = self.png.im_mode
        self._size = self.png.im_size
        self.info = self.png.im_info
        self._text = None
        self.tile = self.png.im_tile
        self.custom_mimetype = self.png.im_custom_mimetype
        self._n_frames = self.png.im_n_frames
        self.default_image = self.info.get("default_image", False)

        if self.png.im_palette:
            rawmode, data = self.png.im_palette
            self.palette = ImagePalette.raw(rawmode, data)

        if cid == b"fdAT":
            self.__prepare_idat = length - 4
        else:
            self.__prepare_idat = length  # used by load_prepare()

        if self._n_frames is not None:
            self._close_exclusive_fp_after_loading = False
            self.png.save_rewind()
            self.__rewind_idat = self.__prepare_idat
            self.__rewind = self.__fp.tell()
            if self.default_image:
                # IDAT chunk contains default image and not first animation frame
                self._n_frames += 1
            self._seek(0)

    @property
    def text(self):
        # experimental
        if self._text is None:
            # iTxt, tEXt and zTXt chunks may appear at the end of the file
            # So load the file to ensure that they are read
            if self.is_animated:
                frame = self.__frame
                # for APNG, seek to the final frame before loading
                self.seek(self.n_frames - 1)
            self.load()
            if self.is_animated:
                self.seek(frame)
        return self._text

    @property
    def n_frames(self):
        if self._n_frames is None:
            return 1
        return self._n_frames

    @property
    def is_animated(self):
        return self._n_frames is not None

    def verify(self):
        """Verify PNG file"""

        if self.fp is None:
            raise RuntimeError("verify must be called directly after open")

        # back up to beginning of IDAT block
        self.fp.seek(self.tile[0][2] - 8)

        self.png.verify()
        self.png.close()

        if self._exclusive_fp:
            self.fp.close()
        self.fp = None

    def seek(self, frame):
        if not self._seek_check(frame):
            return
        if frame < self.__frame:
            self._seek(0, True)

        last_frame = self.__frame
        for f in range(self.__frame + 1, frame + 1):
            try:
                self._seek(f)
            except EOFError:
                self.seek(last_frame)
                raise EOFError("no more images in APNG file")

    def _seek(self, frame, rewind=False):
        if frame == 0:
            if rewind:
                self.__fp.seek(self.__rewind)
                self.png.rewind()
                self.__prepare_idat = self.__rewind_idat
                self.im = None
                if self.pyaccess:
                    self.pyaccess = None
                self.info = self.png.im_info
                self.tile = self.png.im_tile
                self.fp = self.__fp
            self._prev_im = None
            self.dispose = None
            self.default_image = self.info.get("default_image", False)
            self.dispose_op = self.info.get("disposal")
            self.blend_op = self.info.get("blend")
            self.dispose_extent = self.info.get("bbox")
            self.__frame = 0
            return
        else:
            if frame != self.__frame + 1:
                raise ValueError("cannot seek to frame %d" % frame)

        # ensure previous frame was loaded
        self.load()

        self.fp = self.__fp

        # advance to the next frame
        if self.__prepare_idat:
            ImageFile._safe_read(self.fp, self.__prepare_idat)
            self.__prepare_idat = 0
        frame_start = False
        while True:
            self.fp.read(4)  # CRC

            try:
                cid, pos, length = self.png.read()
            except (struct.error, SyntaxError):
                break

            if cid == b"IEND":
                raise EOFError("No more images in APNG file")
            if cid == b"fcTL":
                if frame_start:
                    # there must be at least one fdAT chunk between fcTL chunks
                    raise SyntaxError("APNG missing frame data")
                frame_start = True

            try:
                self.png.call(cid, pos, length)
            except UnicodeDecodeError:
                break
            except EOFError:
                if cid == b"fdAT":
                    length -= 4
                    if frame_start:
                        self.__prepare_idat = length
                        break
                ImageFile._safe_read(self.fp, length)
            except AttributeError:
                logger.debug("%r %s %s (unknown)", cid, pos, length)
                ImageFile._safe_read(self.fp, length)

        self.__frame = frame
        self.tile = self.png.im_tile
        self.dispose_op = self.info.get("disposal")
        self.blend_op = self.info.get("blend")
        self.dispose_extent = self.info.get("bbox")

        if not self.tile:
            raise EOFError

    def tell(self):
        return self.__frame

    def load_prepare(self):
        """internal: prepare to read PNG file"""

        if self.info.get("interlace"):
            self.decoderconfig = self.decoderconfig + (1,)

        self.__idat = self.__prepare_idat  # used by load_read()
        ImageFile.ImageFile.load_prepare(self)

    def load_read(self, read_bytes):
        """internal: read more image data"""

        while self.__idat == 0:
            # end of chunk, skip forward to next one

            self.fp.read(4)  # CRC

            cid, pos, length = self.png.read()

            if cid not in [b"IDAT", b"DDAT", b"fdAT"]:
                self.png.push(cid, pos, length)
                return b""

            if cid == b"fdAT":
                try:
                    self.png.call(cid, pos, length)
                except EOFError:
                    pass
                self.__idat = length - 4  # sequence_num has already been read
            else:
                self.__idat = length  # empty chunks are allowed

        # read more data from this chunk
        if read_bytes <= 0:
            read_bytes = self.__idat
        else:
            read_bytes = min(read_bytes, self.__idat)

        self.__idat = self.__idat - read_bytes

        return self.fp.read(read_bytes)

    def load_end(self):
        """internal: finished reading image data"""
        while True:
            self.fp.read(4)  # CRC

            try:
                cid, pos, length = self.png.read()
            except (struct.error, SyntaxError):
                break

            if cid == b"IEND":
                break
            elif cid == b"fcTL" and self.is_animated:
                # start of the next frame, stop reading
                self.__prepare_idat = 0
                self.png.push(cid, pos, length)
                break

            try:
                self.png.call(cid, pos, length)
            except UnicodeDecodeError:
                break
            except EOFError:
                if cid == b"fdAT":
                    length -= 4
                ImageFile._safe_read(self.fp, length)
            except AttributeError:
                logger.debug("%r %s %s (unknown)", cid, pos, length)
                ImageFile._safe_read(self.fp, length)
        self._text = self.png.im_text
        if not self.is_animated:
            self.png.close()
            self.png = None
        else:
            # setup frame disposal (actual disposal done when needed in _seek())
            if self._prev_im is None and self.dispose_op == APNG_DISPOSE_OP_PREVIOUS:
                self.dispose_op = APNG_DISPOSE_OP_BACKGROUND

            if self.dispose_op == APNG_DISPOSE_OP_PREVIOUS:
                dispose = self._prev_im.copy()
                dispose = self._crop(dispose, self.dispose_extent)
            elif self.dispose_op == APNG_DISPOSE_OP_BACKGROUND:
                dispose = Image.core.fill("RGBA", self.size, (0, 0, 0, 0))
                dispose = self._crop(dispose, self.dispose_extent)
            else:
                dispose = None

            if self._prev_im and self.blend_op == APNG_BLEND_OP_OVER:
                updated = self._crop(self.im, self.dispose_extent)
                self._prev_im.paste(
                    updated, self.dispose_extent, updated.convert("RGBA")
                )
                self.im = self._prev_im
                if self.pyaccess:
                    self.pyaccess = None
            self._prev_im = self.im.copy()

            if dispose:
                self._prev_im.paste(dispose, self.dispose_extent)

    def _getexif(self):
        if "exif" not in self.info:
            self.load()
        if "exif" not in self.info:
            return None
        return dict(self.getexif())

    def getexif(self):
        if "exif" not in self.info:
            self.load()
        return ImageFile.ImageFile.getexif(self)

    def _close__fp(self):
        try:
            if self.__fp != self.fp:
                self.__fp.close()
        except AttributeError:
            pass
        finally:
            self.__fp = None


# --------------------------------------------------------------------
# PNG writer

_OUTMODES = {
    # supported PIL modes, and corresponding rawmodes/bits/color combinations
    "1": ("1", b"\x01\x00"),
    "L;1": ("L;1", b"\x01\x00"),
    "L;2": ("L;2", b"\x02\x00"),
    "L;4": ("L;4", b"\x04\x00"),
    "L": ("L", b"\x08\x00"),
    "LA": ("LA", b"\x08\x04"),
    "I": ("I;16B", b"\x10\x00"),
    "I;16": ("I;16B", b"\x10\x00"),
    "P;1": ("P;1", b"\x01\x03"),
    "P;2": ("P;2", b"\x02\x03"),
    "P;4": ("P;4", b"\x04\x03"),
    "P": ("P", b"\x08\x03"),
    "RGB": ("RGB", b"\x08\x02"),
    "RGBA": ("RGBA", b"\x08\x06"),
}


def putchunk(fp, cid, *data):
    """Write a PNG chunk (including CRC field)"""

    data = b"".join(data)

    fp.write(o32(len(data)) + cid)
    fp.write(data)
    crc = _crc32(data, _crc32(cid))
    fp.write(o32(crc))


class _idat:
    # wrap output from the encoder in IDAT chunks

    def __init__(self, fp, chunk):
        self.fp = fp
        self.chunk = chunk

    def write(self, data):
        self.chunk(self.fp, b"IDAT", data)


class _fdat:
    # wrap encoder output in fdAT chunks

    def __init__(self, fp, chunk, seq_num):
        self.fp = fp
        self.chunk = chunk
        self.seq_num = seq_num

    def write(self, data):
        self.chunk(self.fp, b"fdAT", o32(self.seq_num), data)
        self.seq_num += 1


def _write_multiple_frames(im, fp, chunk, rawmode):
    default_image = im.encoderinfo.get("default_image", im.info.get("default_image"))
    duration = im.encoderinfo.get("duration", im.info.get("duration", 0))
    loop = im.encoderinfo.get("loop", im.info.get("loop", 0))
    disposal = im.encoderinfo.get("disposal", im.info.get("disposal"))
    blend = im.encoderinfo.get("blend", im.info.get("blend"))

    if default_image:
        chain = itertools.chain(im.encoderinfo.get("append_images", []))
    else:
        chain = itertools.chain([im], im.encoderinfo.get("append_images", []))

    im_frames = []
    frame_count = 0
    for im_seq in chain:
        for im_frame in ImageSequence.Iterator(im_seq):
            im_frame = im_frame.copy()
            if im_frame.mode != im.mode:
                if im.mode == "P":
                    im_frame = im_frame.convert(im.mode, palette=im.palette)
                else:
                    im_frame = im_frame.convert(im.mode)
            encoderinfo = im.encoderinfo.copy()
            if isinstance(duration, (list, tuple)):
                encoderinfo["duration"] = duration[frame_count]
            if isinstance(disposal, (list, tuple)):
                encoderinfo["disposal"] = disposal[frame_count]
            if isinstance(blend, (list, tuple)):
                encoderinfo["blend"] = blend[frame_count]
            frame_count += 1

            if im_frames:
                previous = im_frames[-1]
                prev_disposal = previous["encoderinfo"].get("disposal")
                prev_blend = previous["encoderinfo"].get("blend")
                if prev_disposal == APNG_DISPOSE_OP_PREVIOUS and len(im_frames) < 2:
                    prev_disposal == APNG_DISPOSE_OP_BACKGROUND

                if prev_disposal == APNG_DISPOSE_OP_BACKGROUND:
                    base_im = previous["im"]
                    dispose = Image.core.fill("RGBA", im.size, (0, 0, 0, 0))
                    bbox = previous["bbox"]
                    if bbox:
                        dispose = dispose.crop(bbox)
                    else:
                        bbox = (0, 0) + im.size
                    base_im.paste(dispose, bbox)
                elif prev_disposal == APNG_DISPOSE_OP_PREVIOUS:
                    base_im = im_frames[-2]["im"]
                else:
                    base_im = previous["im"]
                delta = ImageChops.subtract_modulo(im_frame, base_im)
                bbox = delta.getbbox()
                if (
                    not bbox
                    and prev_disposal == encoderinfo.get("disposal")
                    and prev_blend == encoderinfo.get("blend")
                ):
                    duration = encoderinfo.get("duration", 0)
                    if duration:
                        if "duration" in previous["encoderinfo"]:
                            previous["encoderinfo"]["duration"] += duration
                        else:
                            previous["encoderinfo"]["duration"] = duration
                    continue
            else:
                bbox = None
            im_frames.append({"im": im_frame, "bbox": bbox, "encoderinfo": encoderinfo})

    # animation control
    chunk(
        fp, b"acTL", o32(len(im_frames)), o32(loop),  # 0: num_frames  # 4: num_plays
    )

    # default image IDAT (if it exists)
    if default_image:
        ImageFile._save(im, _idat(fp, chunk), [("zip", (0, 0) + im.size, 0, rawmode)])

    seq_num = 0
    for frame, frame_data in enumerate(im_frames):
        im_frame = frame_data["im"]
        if not frame_data["bbox"]:
            bbox = (0, 0) + im_frame.size
        else:
            bbox = frame_data["bbox"]
            im_frame = im_frame.crop(bbox)
        size = im_frame.size
        duration = int(round(frame_data["encoderinfo"].get("duration", 0)))
        disposal = frame_data["encoderinfo"].get("disposal", APNG_DISPOSE_OP_NONE)
        blend = frame_data["encoderinfo"].get("blend", APNG_BLEND_OP_SOURCE)
        # frame control
        chunk(
            fp,
            b"fcTL",
            o32(seq_num),  # sequence_number
            o32(size[0]),  # width
            o32(size[1]),  # height
            o32(bbox[0]),  # x_offset
            o32(bbox[1]),  # y_offset
            o16(duration),  # delay_numerator
            o16(1000),  # delay_denominator
            o8(disposal),  # dispose_op
            o8(blend),  # blend_op
        )
        seq_num += 1
        # frame data
        if frame == 0 and not default_image:
            # first frame must be in IDAT chunks for backwards compatibility
            ImageFile._save(
                im_frame,
                _idat(fp, chunk),
                [("zip", (0, 0) + im_frame.size, 0, rawmode)],
            )
        else:
            fdat_chunks = _fdat(fp, chunk, seq_num)
            ImageFile._save(
                im_frame, fdat_chunks, [("zip", (0, 0) + im_frame.size, 0, rawmode)],
            )
            seq_num = fdat_chunks.seq_num


def _save_all(im, fp, filename):
    _save(im, fp, filename, save_all=True)


def _save(im, fp, filename, chunk=putchunk, save_all=False):
    # save an image to disk (called by the save method)

    mode = im.mode

    if mode == "P":

        #
        # attempt to minimize storage requirements for palette images
        if "bits" in im.encoderinfo:
            # number of bits specified by user
            colors = 1 << im.encoderinfo["bits"]
        else:
            # check palette contents
            if im.palette:
                colors = max(min(len(im.palette.getdata()[1]) // 3, 256), 2)
            else:
                colors = 256

        if colors <= 2:
            bits = 1
        elif colors <= 4:
            bits = 2
        elif colors <= 16:
            bits = 4
        else:
            bits = 8
        if bits != 8:
            mode = "%s;%d" % (mode, bits)

    # encoder options
    im.encoderconfig = (
        im.encoderinfo.get("optimize", False),
        im.encoderinfo.get("compress_level", -1),
        im.encoderinfo.get("compress_type", -1),
        im.encoderinfo.get("dictionary", b""),
    )

    # get the corresponding PNG mode
    try:
        rawmode, mode = _OUTMODES[mode]
    except KeyError:
        raise OSError("cannot write mode %s as PNG" % mode)

    #
    # write minimal PNG file

    fp.write(_MAGIC)

    chunk(
        fp,
        b"IHDR",
        o32(im.size[0]),  # 0: size
        o32(im.size[1]),
        mode,  # 8: depth/type
        b"\0",  # 10: compression
        b"\0",  # 11: filter category
        b"\0",  # 12: interlace flag
    )

    chunks = [b"cHRM", b"gAMA", b"sBIT", b"sRGB", b"tIME"]

    icc = im.encoderinfo.get("icc_profile", im.info.get("icc_profile"))
    if icc:
        # ICC profile
        # according to PNG spec, the iCCP chunk contains:
        # Profile name  1-79 bytes (character string)
        # Null separator        1 byte (null character)
        # Compression method    1 byte (0)
        # Compressed profile    n bytes (zlib with deflate compression)
        name = b"ICC Profile"
        data = name + b"\0\0" + zlib.compress(icc)
        chunk(fp, b"iCCP", data)

        # You must either have sRGB or iCCP.
        # Disallow sRGB chunks when an iCCP-chunk has been emitted.
        chunks.remove(b"sRGB")

    info = im.encoderinfo.get("pnginfo")
    if info:
        chunks_multiple_allowed = [b"sPLT", b"iTXt", b"tEXt", b"zTXt"]
        for cid, data in info.chunks:
            if cid in chunks:
                chunks.remove(cid)
                chunk(fp, cid, data)
            elif cid in chunks_multiple_allowed:
                chunk(fp, cid, data)

    if im.mode == "P":
        palette_byte_number = (2 ** bits) * 3
        palette_bytes = im.im.getpalette("RGB")[:palette_byte_number]
        while len(palette_bytes) < palette_byte_number:
            palette_bytes += b"\0"
        chunk(fp, b"PLTE", palette_bytes)

    transparency = im.encoderinfo.get("transparency", im.info.get("transparency", None))

    if transparency or transparency == 0:
        if im.mode == "P":
            # limit to actual palette size
            alpha_bytes = 2 ** bits
            if isinstance(transparency, bytes):
                chunk(fp, b"tRNS", transparency[:alpha_bytes])
            else:
                transparency = max(0, min(255, transparency))
                alpha = b"\xFF" * transparency + b"\0"
                chunk(fp, b"tRNS", alpha[:alpha_bytes])
        elif im.mode in ("1", "L", "I"):
            transparency = max(0, min(65535, transparency))
            chunk(fp, b"tRNS", o16(transparency))
        elif im.mode == "RGB":
            red, green, blue = transparency
            chunk(fp, b"tRNS", o16(red) + o16(green) + o16(blue))
        else:
            if "transparency" in im.encoderinfo:
                # don't bother with transparency if it's an RGBA
                # and it's in the info dict. It's probably just stale.
                raise OSError("cannot use transparency for this mode")
    else:
        if im.mode == "P" and im.im.getpalettemode() == "RGBA":
            alpha = im.im.getpalette("RGBA", "A")
            alpha_bytes = 2 ** bits
            chunk(fp, b"tRNS", alpha[:alpha_bytes])

    dpi = im.encoderinfo.get("dpi")
    if dpi:
        chunk(
            fp,
            b"pHYs",
            o32(int(dpi[0] / 0.0254 + 0.5)),
            o32(int(dpi[1] / 0.0254 + 0.5)),
            b"\x01",
        )

    if info:
        chunks = [b"bKGD", b"hIST"]
        for cid, data in info.chunks:
            if cid in chunks:
                chunks.remove(cid)
                chunk(fp, cid, data)

    exif = im.encoderinfo.get("exif", im.info.get("exif"))
    if exif:
        if isinstance(exif, Image.Exif):
            exif = exif.tobytes(8)
        if exif.startswith(b"Exif\x00\x00"):
            exif = exif[6:]
        chunk(fp, b"eXIf", exif)

    if save_all:
        _write_multiple_frames(im, fp, chunk, rawmode)
    else:
        ImageFile._save(im, _idat(fp, chunk), [("zip", (0, 0) + im.size, 0, rawmode)])

    chunk(fp, b"IEND", b"")

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


# --------------------------------------------------------------------
# PNG chunk converter


def getchunks(im, **params):
    """Return a list of PNG chunks representing this image."""

    class collector:
        data = []

        def write(self, data):
            pass

        def append(self, chunk):
            self.data.append(chunk)

    def append(fp, cid, *data):
        data = b"".join(data)
        crc = o32(_crc32(data, _crc32(cid)))
        fp.append((cid, data, crc))

    fp = collector()

    try:
        im.encoderinfo = params
        _save(im, fp, None, append)
    finally:
        del im.encoderinfo

    return fp.data


# --------------------------------------------------------------------
# Registry

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

Image.register_extensions(PngImageFile.format, [".png", ".apng"])

Image.register_mime(PngImageFile.format, "image/png")

```
--- END FILE ---

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

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

Here is an example:

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

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