{
    "file_diffs": [
        {
            "old_file_content": "import os\nfrom glob import glob\nfrom itertools import product\n\nimport pytest\n\nfrom PIL import Image\n\nfrom .helper import assert_image_equal, assert_image_equal_tofile, hopper\n\n_TGA_DIR = os.path.join(\"Tests\", \"images\", \"tga\")\n_TGA_DIR_COMMON = os.path.join(_TGA_DIR, \"common\")\n\n\n_MODES = (\"L\", \"LA\", \"P\", \"RGB\", \"RGBA\")\n_ORIGINS = (\"tl\", \"bl\")\n\n_ORIGIN_TO_ORIENTATION = {\"tl\": 1, \"bl\": -1}\n\n\ndef test_sanity(tmp_path):\n    for mode in _MODES:\n\n        def roundtrip(original_im):\n            out = str(tmp_path / \"temp.tga\")\n\n            original_im.save(out, rle=rle)\n            with Image.open(out) as saved_im:\n                if rle:\n                    assert (\n                        saved_im.info[\"compression\"] == original_im.info[\"compression\"]\n                    )\n                assert saved_im.info[\"orientation\"] == original_im.info[\"orientation\"]\n                if mode == \"P\":\n                    assert saved_im.getpalette() == original_im.getpalette()\n\n                assert_image_equal(saved_im, original_im)\n\n        png_paths = glob(os.path.join(_TGA_DIR_COMMON, f\"*x*_{mode.lower()}.png\"))\n\n        for png_path in png_paths:\n            with Image.open(png_path) as reference_im:\n                assert reference_im.mode == mode\n\n                path_no_ext = os.path.splitext(png_path)[0]\n                for origin, rle in product(_ORIGINS, (True, False)):\n                    tga_path = \"{}_{}_{}.tga\".format(\n                        path_no_ext, origin, \"rle\" if rle else \"raw\"\n                    )\n\n                    with Image.open(tga_path) as original_im:\n                        assert original_im.format == \"TGA\"\n                        assert original_im.get_format_mimetype() == \"image/x-tga\"\n                        if rle:\n                            assert original_im.info[\"compression\"] == \"tga_rle\"\n                        assert (\n                            original_im.info[\"orientation\"]\n                            == _ORIGIN_TO_ORIENTATION[origin]\n                        )\n                        if mode == \"P\":\n                            assert original_im.getpalette() == reference_im.getpalette()\n\n                        assert_image_equal(original_im, reference_im)\n\n                        roundtrip(original_im)\n\n\ndef test_palette_depth_16(tmp_path):\n    with Image.open(\"Tests/images/p_16.tga\") as im:\n        assert_image_equal_tofile(im.convert(\"RGB\"), \"Tests/images/p_16.png\")\n\n        out = str(tmp_path / \"temp.png\")\n        im.save(out)\n        with Image.open(out) as reloaded:\n            assert_image_equal_tofile(reloaded.convert(\"RGB\"), \"Tests/images/p_16.png\")\n\n\ndef test_id_field():\n    # tga file with id field\n    test_file = \"Tests/images/tga_id_field.tga\"\n\n    # Act\n    with Image.open(test_file) as im:\n\n        # Assert\n        assert im.size == (100, 100)\n\n\ndef test_id_field_rle():\n    # tga file with id field\n    test_file = \"Tests/images/rgb32rle.tga\"\n\n    # Act\n    with Image.open(test_file) as im:\n\n        # Assert\n        assert im.size == (199, 199)\n\n\ndef test_cross_scan_line():\n    with Image.open(\"Tests/images/cross_scan_line.tga\") as im:\n        assert_image_equal_tofile(im, \"Tests/images/cross_scan_line.png\")\n\n    with Image.open(\"Tests/images/cross_scan_line_truncated.tga\") as im:\n        with pytest.raises(OSError):\n            im.load()\n\n\ndef test_save(tmp_path):\n    test_file = \"Tests/images/tga_id_field.tga\"\n    with Image.open(test_file) as im:\n        out = str(tmp_path / \"temp.tga\")\n\n        # Save\n        im.save(out)\n        with Image.open(out) as test_im:\n            assert test_im.size == (100, 100)\n            assert test_im.info[\"id_section\"] == im.info[\"id_section\"]\n\n        # RGBA save\n        im.convert(\"RGBA\").save(out)\n    with Image.open(out) as test_im:\n        assert test_im.size == (100, 100)\n\n\ndef test_save_wrong_mode(tmp_path):\n    im = hopper(\"PA\")\n    out = str(tmp_path / \"temp.tga\")\n\n    with pytest.raises(OSError):\n        im.save(out)\n\n\ndef test_save_mapdepth():\n    # This image has been manually hexedited from 200x32_p_bl_raw.tga\n    # to include an origin\n    test_file = \"Tests/images/200x32_p_bl_raw_origin.tga\"\n    with Image.open(test_file) as im:\n        assert_image_equal_tofile(im, \"Tests/images/tga/common/200x32_p.png\")\n\n\ndef test_save_id_section(tmp_path):\n    test_file = \"Tests/images/rgb32rle.tga\"\n    with Image.open(test_file) as im:\n        out = str(tmp_path / \"temp.tga\")\n\n        # Check there is no id section\n        im.save(out)\n    with Image.open(out) as test_im:\n        assert \"id_section\" not in test_im.info\n\n    # Save with custom id section\n    im.save(out, id_section=b\"Test content\")\n    with Image.open(out) as test_im:\n        assert test_im.info[\"id_section\"] == b\"Test content\"\n\n    # Save with custom id section greater than 255 characters\n    id_section = b\"Test content\" * 25\n    pytest.warns(UserWarning, lambda: im.save(out, id_section=id_section))\n    with Image.open(out) as test_im:\n        assert test_im.info[\"id_section\"] == id_section[:255]\n\n    test_file = \"Tests/images/tga_id_field.tga\"\n    with Image.open(test_file) as im:\n\n        # Save with no id section\n        im.save(out, id_section=\"\")\n    with Image.open(out) as test_im:\n        assert \"id_section\" not in test_im.info\n\n\ndef test_save_orientation(tmp_path):\n    test_file = \"Tests/images/rgb32rle.tga\"\n    out = str(tmp_path / \"temp.tga\")\n    with Image.open(test_file) as im:\n        assert im.info[\"orientation\"] == -1\n\n        im.save(out, orientation=1)\n    with Image.open(out) as test_im:\n        assert test_im.info[\"orientation\"] == 1\n\n\ndef test_horizontal_orientations():\n    # These images have been manually hexedited to have the relevant orientations\n    with Image.open(\"Tests/images/rgb32rle_top_right.tga\") as im:\n        assert im.load()[90, 90][:3] == (0, 0, 0)\n\n    with Image.open(\"Tests/images/rgb32rle_bottom_right.tga\") as im:\n        assert im.load()[90, 90][:3] == (0, 255, 0)\n\n\ndef test_save_rle(tmp_path):\n    test_file = \"Tests/images/rgb32rle.tga\"\n    with Image.open(test_file) as im:\n        assert im.info[\"compression\"] == \"tga_rle\"\n\n        out = str(tmp_path / \"temp.tga\")\n\n        # Save\n        im.save(out)\n    with Image.open(out) as test_im:\n        assert test_im.size == (199, 199)\n        assert test_im.info[\"compression\"] == \"tga_rle\"\n\n    # Save without compression\n    im.save(out, compression=None)\n    with Image.open(out) as test_im:\n        assert \"compression\" not in test_im.info\n\n    # RGBA save\n    im.convert(\"RGBA\").save(out)\n    with Image.open(out) as test_im:\n        assert test_im.size == (199, 199)\n\n    test_file = \"Tests/images/tga_id_field.tga\"\n    with Image.open(test_file) as im:\n        assert \"compression\" not in im.info\n\n        # Save with compression\n        im.save(out, compression=\"tga_rle\")\n    with Image.open(out) as test_im:\n        assert test_im.info[\"compression\"] == \"tga_rle\"\n\n\ndef test_save_l_transparency(tmp_path):\n    # There are 559 transparent pixels in la.tga.\n    num_transparent = 559\n\n    in_file = \"Tests/images/la.tga\"\n    with Image.open(in_file) as im:\n        assert im.mode == \"LA\"\n        assert im.getchannel(\"A\").getcolors()[0][0] == num_transparent\n\n        out = str(tmp_path / \"temp.tga\")\n        im.save(out)\n\n    with Image.open(out) as test_im:\n        assert test_im.mode == \"LA\"\n        assert test_im.getchannel(\"A\").getcolors()[0][0] == num_transparent\n\n        assert_image_equal(im, test_im)\n",
            "new_file_content": "import os\nfrom glob import glob\nfrom itertools import product\n\nimport pytest\n\nfrom PIL import Image\n\nfrom .helper import assert_image_equal, assert_image_equal_tofile, hopper\n\n_TGA_DIR = os.path.join(\"Tests\", \"images\", \"tga\")\n_TGA_DIR_COMMON = os.path.join(_TGA_DIR, \"common\")\n\n\n_MODES = (\"L\", \"LA\", \"P\", \"RGB\", \"RGBA\")\n_ORIGINS = (\"tl\", \"bl\")\n\n_ORIGIN_TO_ORIENTATION = {\"tl\": 1, \"bl\": -1}\n\n\ndef test_sanity(tmp_path):\n    for mode in _MODES:\n\n        def roundtrip(original_im):\n            out = str(tmp_path / \"temp.tga\")\n\n            original_im.save(out, rle=rle)\n            with Image.open(out) as saved_im:\n                if rle:\n                    assert (\n                        saved_im.info[\"compression\"] == original_im.info[\"compression\"]\n                    )\n                assert saved_im.info[\"orientation\"] == original_im.info[\"orientation\"]\n                if mode == \"P\":\n                    assert saved_im.getpalette() == original_im.getpalette()\n\n                assert_image_equal(saved_im, original_im)\n\n        png_paths = glob(os.path.join(_TGA_DIR_COMMON, f\"*x*_{mode.lower()}.png\"))\n\n        for png_path in png_paths:\n            with Image.open(png_path) as reference_im:\n                assert reference_im.mode == mode\n\n                path_no_ext = os.path.splitext(png_path)[0]\n                for origin, rle in product(_ORIGINS, (True, False)):\n                    tga_path = \"{}_{}_{}.tga\".format(\n                        path_no_ext, origin, \"rle\" if rle else \"raw\"\n                    )\n\n                    with Image.open(tga_path) as original_im:\n                        assert original_im.format == \"TGA\"\n                        assert original_im.get_format_mimetype() == \"image/x-tga\"\n                        if rle:\n                            assert original_im.info[\"compression\"] == \"tga_rle\"\n                        assert (\n                            original_im.info[\"orientation\"]\n                            == _ORIGIN_TO_ORIENTATION[origin]\n                        )\n                        if mode == \"P\":\n                            assert original_im.getpalette() == reference_im.getpalette()\n\n                        assert_image_equal(original_im, reference_im)\n\n                        roundtrip(original_im)\n\n\ndef test_palette_depth_16(tmp_path):\n    with Image.open(\"Tests/images/p_16.tga\") as im:\n        assert_image_equal_tofile(im.convert(\"RGB\"), \"Tests/images/p_16.png\")\n\n        out = str(tmp_path / \"temp.png\")\n        im.save(out)\n        with Image.open(out) as reloaded:\n            assert_image_equal_tofile(reloaded.convert(\"RGB\"), \"Tests/images/p_16.png\")\n\n\ndef test_id_field():\n    # tga file with id field\n    test_file = \"Tests/images/tga_id_field.tga\"\n\n    # Act\n    with Image.open(test_file) as im:\n\n        # Assert\n        assert im.size == (100, 100)\n\n\ndef test_id_field_rle():\n    # tga file with id field\n    test_file = \"Tests/images/rgb32rle.tga\"\n\n    # Act\n    with Image.open(test_file) as im:\n\n        # Assert\n        assert im.size == (199, 199)\n\n\ndef test_cross_scan_line():\n    with Image.open(\"Tests/images/cross_scan_line.tga\") as im:\n        assert_image_equal_tofile(im, \"Tests/images/cross_scan_line.png\")\n\n    with Image.open(\"Tests/images/cross_scan_line_truncated.tga\") as im:\n        with pytest.raises(OSError):\n            im.load()\n\n\ndef test_save(tmp_path):\n    test_file = \"Tests/images/tga_id_field.tga\"\n    with Image.open(test_file) as im:\n        out = str(tmp_path / \"temp.tga\")\n\n        # Save\n        im.save(out)\n        with Image.open(out) as test_im:\n            assert test_im.size == (100, 100)\n            assert test_im.info[\"id_section\"] == im.info[\"id_section\"]\n\n        # RGBA save\n        im.convert(\"RGBA\").save(out)\n    with Image.open(out) as test_im:\n        assert test_im.size == (100, 100)\n\n\ndef test_small_palette(tmp_path):\n    im = Image.new(\"P\", (1, 1))\n    colors = [0, 0, 0]\n    im.putpalette(colors)\n\n    out = str(tmp_path / \"temp.tga\")\n    im.save(out)\n\n    with Image.open(out) as reloaded:\n        assert reloaded.getpalette() == colors\n\n\ndef test_save_wrong_mode(tmp_path):\n    im = hopper(\"PA\")\n    out = str(tmp_path / \"temp.tga\")\n\n    with pytest.raises(OSError):\n        im.save(out)\n\n\ndef test_save_mapdepth():\n    # This image has been manually hexedited from 200x32_p_bl_raw.tga\n    # to include an origin\n    test_file = \"Tests/images/200x32_p_bl_raw_origin.tga\"\n    with Image.open(test_file) as im:\n        assert_image_equal_tofile(im, \"Tests/images/tga/common/200x32_p.png\")\n\n\ndef test_save_id_section(tmp_path):\n    test_file = \"Tests/images/rgb32rle.tga\"\n    with Image.open(test_file) as im:\n        out = str(tmp_path / \"temp.tga\")\n\n        # Check there is no id section\n        im.save(out)\n    with Image.open(out) as test_im:\n        assert \"id_section\" not in test_im.info\n\n    # Save with custom id section\n    im.save(out, id_section=b\"Test content\")\n    with Image.open(out) as test_im:\n        assert test_im.info[\"id_section\"] == b\"Test content\"\n\n    # Save with custom id section greater than 255 characters\n    id_section = b\"Test content\" * 25\n    pytest.warns(UserWarning, lambda: im.save(out, id_section=id_section))\n    with Image.open(out) as test_im:\n        assert test_im.info[\"id_section\"] == id_section[:255]\n\n    test_file = \"Tests/images/tga_id_field.tga\"\n    with Image.open(test_file) as im:\n\n        # Save with no id section\n        im.save(out, id_section=\"\")\n    with Image.open(out) as test_im:\n        assert \"id_section\" not in test_im.info\n\n\ndef test_save_orientation(tmp_path):\n    test_file = \"Tests/images/rgb32rle.tga\"\n    out = str(tmp_path / \"temp.tga\")\n    with Image.open(test_file) as im:\n        assert im.info[\"orientation\"] == -1\n\n        im.save(out, orientation=1)\n    with Image.open(out) as test_im:\n        assert test_im.info[\"orientation\"] == 1\n\n\ndef test_horizontal_orientations():\n    # These images have been manually hexedited to have the relevant orientations\n    with Image.open(\"Tests/images/rgb32rle_top_right.tga\") as im:\n        assert im.load()[90, 90][:3] == (0, 0, 0)\n\n    with Image.open(\"Tests/images/rgb32rle_bottom_right.tga\") as im:\n        assert im.load()[90, 90][:3] == (0, 255, 0)\n\n\ndef test_save_rle(tmp_path):\n    test_file = \"Tests/images/rgb32rle.tga\"\n    with Image.open(test_file) as im:\n        assert im.info[\"compression\"] == \"tga_rle\"\n\n        out = str(tmp_path / \"temp.tga\")\n\n        # Save\n        im.save(out)\n    with Image.open(out) as test_im:\n        assert test_im.size == (199, 199)\n        assert test_im.info[\"compression\"] == \"tga_rle\"\n\n    # Save without compression\n    im.save(out, compression=None)\n    with Image.open(out) as test_im:\n        assert \"compression\" not in test_im.info\n\n    # RGBA save\n    im.convert(\"RGBA\").save(out)\n    with Image.open(out) as test_im:\n        assert test_im.size == (199, 199)\n\n    test_file = \"Tests/images/tga_id_field.tga\"\n    with Image.open(test_file) as im:\n        assert \"compression\" not in im.info\n\n        # Save with compression\n        im.save(out, compression=\"tga_rle\")\n    with Image.open(out) as test_im:\n        assert test_im.info[\"compression\"] == \"tga_rle\"\n\n\ndef test_save_l_transparency(tmp_path):\n    # There are 559 transparent pixels in la.tga.\n    num_transparent = 559\n\n    in_file = \"Tests/images/la.tga\"\n    with Image.open(in_file) as im:\n        assert im.mode == \"LA\"\n        assert im.getchannel(\"A\").getcolors()[0][0] == num_transparent\n\n        out = str(tmp_path / \"temp.tga\")\n        im.save(out)\n\n    with Image.open(out) as test_im:\n        assert test_im.mode == \"LA\"\n        assert test_im.getchannel(\"A\").getcolors()[0][0] == num_transparent\n\n        assert_image_equal(im, test_im)\n",
            "header": {
                "file": {
                    "path": "Tests/test_file_tga.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "0c8c9f304",
                "new_commit_hash": "fff127421",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/Tests/test_file_tga.py"
            },
            "plus_file": {
                "path": "b/Tests/test_file_tga.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 123,
                            "length": 6
                        },
                        "new_range": {
                            "start": 123,
                            "length": 18
                        },
                        "section": "def test_save(tmp_path):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        assert test_im.size == (100, 100)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "def test_small_palette(tmp_path):",
                                "type": "added"
                            },
                            {
                                "content": "    im = Image.new(\"P\", (1, 1))",
                                "type": "added"
                            },
                            {
                                "content": "    colors = [0, 0, 0]",
                                "type": "added"
                            },
                            {
                                "content": "    im.putpalette(colors)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    out = str(tmp_path / \"temp.tga\")",
                                "type": "added"
                            },
                            {
                                "content": "    im.save(out)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    with Image.open(out) as reloaded:",
                                "type": "added"
                            },
                            {
                                "content": "        assert reloaded.getpalette() == colors",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "def test_save_wrong_mode(tmp_path):",
                                "type": "context"
                            },
                            {
                                "content": "    im = hopper(\"PA\")",
                                "type": "context"
                            },
                            {
                                "content": "    out = str(tmp_path / \"temp.tga\")",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "Tests/test_file_tga.py",
                            "type": "function",
                            "name": "test_small_palette",
                            "content": "def test_small_palette(tmp_path):\n    im = Image.new(\"P\", (1, 1))\n    colors = [0, 0, 0]\n    im.putpalette(colors)\n\n    out = str(tmp_path / \"temp.tga\")\n    im.save(out)\n\n    with Image.open(out) as reloaded:\n        assert reloaded.getpalette() == colors",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 126,
                            "end_lineno": 135,
                            "parent": null
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "#\n# The Python Imaging Library.\n# $Id$\n#\n# TGA file handling\n#\n# History:\n# 95-09-01 fl   created (reads 24-bit files only)\n# 97-01-04 fl   support more TGA versions, including compressed images\n# 98-07-04 fl   fixed orientation and alpha layer bugs\n# 98-09-11 fl   fixed orientation for runlength decoder\n#\n# Copyright (c) Secret Labs AB 1997-98.\n# Copyright (c) Fredrik Lundh 1995-97.\n#\n# See the README file for information on usage and redistribution.\n#\n\n\nimport warnings\n\nfrom . import Image, ImageFile, ImagePalette\nfrom ._binary import i16le as i16\nfrom ._binary import o8\nfrom ._binary import o16le as o16\n\n#\n# --------------------------------------------------------------------\n# Read RGA file\n\n\nMODES = {\n    # map imagetype/depth to rawmode\n    (1, 8): \"P\",\n    (3, 1): \"1\",\n    (3, 8): \"L\",\n    (3, 16): \"LA\",\n    (2, 16): \"BGR;5\",\n    (2, 24): \"BGR\",\n    (2, 32): \"BGRA\",\n}\n\n\n##\n# Image plugin for Targa files.\n\n\nclass TgaImageFile(ImageFile.ImageFile):\n\n    format = \"TGA\"\n    format_description = \"Targa\"\n\n    def _open(self):\n\n        # process header\n        s = self.fp.read(18)\n\n        id_len = s[0]\n\n        colormaptype = s[1]\n        imagetype = s[2]\n\n        depth = s[16]\n\n        flags = s[17]\n\n        self._size = i16(s, 12), i16(s, 14)\n\n        # validate header fields\n        if (\n            colormaptype not in (0, 1)\n            or self.size[0] <= 0\n            or self.size[1] <= 0\n            or depth not in (1, 8, 16, 24, 32)\n        ):\n            raise SyntaxError(\"not a TGA file\")\n\n        # image mode\n        if imagetype in (3, 11):\n            self.mode = \"L\"\n            if depth == 1:\n                self.mode = \"1\"  # ???\n            elif depth == 16:\n                self.mode = \"LA\"\n        elif imagetype in (1, 9):\n            self.mode = \"P\"\n        elif imagetype in (2, 10):\n            self.mode = \"RGB\"\n            if depth == 32:\n                self.mode = \"RGBA\"\n        else:\n            raise SyntaxError(\"unknown TGA mode\")\n\n        # orientation\n        orientation = flags & 0x30\n        self._flip_horizontally = orientation in [0x10, 0x30]\n        if orientation in [0x20, 0x30]:\n            orientation = 1\n        elif orientation in [0, 0x10]:\n            orientation = -1\n        else:\n            raise SyntaxError(\"unknown TGA orientation\")\n\n        self.info[\"orientation\"] = orientation\n\n        if imagetype & 8:\n            self.info[\"compression\"] = \"tga_rle\"\n\n        if id_len:\n            self.info[\"id_section\"] = self.fp.read(id_len)\n\n        if colormaptype:\n            # read palette\n            start, size, mapdepth = i16(s, 3), i16(s, 5), s[7]\n            if mapdepth == 16:\n                self.palette = ImagePalette.raw(\n                    \"BGR;15\", b\"\\0\" * 2 * start + self.fp.read(2 * size)\n                )\n            elif mapdepth == 24:\n                self.palette = ImagePalette.raw(\n                    \"BGR\", b\"\\0\" * 3 * start + self.fp.read(3 * size)\n                )\n            elif mapdepth == 32:\n                self.palette = ImagePalette.raw(\n                    \"BGRA\", b\"\\0\" * 4 * start + self.fp.read(4 * size)\n                )\n\n        # setup tile descriptor\n        try:\n            rawmode = MODES[(imagetype & 7, depth)]\n            if imagetype & 8:\n                # compressed\n                self.tile = [\n                    (\n                        \"tga_rle\",\n                        (0, 0) + self.size,\n                        self.fp.tell(),\n                        (rawmode, orientation, depth),\n                    )\n                ]\n            else:\n                self.tile = [\n                    (\n                        \"raw\",\n                        (0, 0) + self.size,\n                        self.fp.tell(),\n                        (rawmode, 0, orientation),\n                    )\n                ]\n        except KeyError:\n            pass  # cannot decode\n\n    def load_end(self):\n        if self._flip_horizontally:\n            self.im = self.im.transpose(Image.Transpose.FLIP_LEFT_RIGHT)\n\n\n#\n# --------------------------------------------------------------------\n# Write TGA file\n\n\nSAVE = {\n    \"1\": (\"1\", 1, 0, 3),\n    \"L\": (\"L\", 8, 0, 3),\n    \"LA\": (\"LA\", 16, 0, 3),\n    \"P\": (\"P\", 8, 1, 1),\n    \"RGB\": (\"BGR\", 24, 0, 2),\n    \"RGBA\": (\"BGRA\", 32, 0, 2),\n}\n\n\ndef _save(im, fp, filename):\n\n    try:\n        rawmode, bits, colormaptype, imagetype = SAVE[im.mode]\n    except KeyError as e:\n        raise OSError(f\"cannot write mode {im.mode} as TGA\") from e\n\n    if \"rle\" in im.encoderinfo:\n        rle = im.encoderinfo[\"rle\"]\n    else:\n        compression = im.encoderinfo.get(\"compression\", im.info.get(\"compression\"))\n        rle = compression == \"tga_rle\"\n    if rle:\n        imagetype += 8\n\n    id_section = im.encoderinfo.get(\"id_section\", im.info.get(\"id_section\", \"\"))\n    id_len = len(id_section)\n    if id_len > 255:\n        id_len = 255\n        id_section = id_section[:255]\n        warnings.warn(\"id_section has been trimmed to 255 characters\")\n\n    if colormaptype:\n        colormapfirst, colormaplength, colormapentry = 0, 256, 24\n    else:\n        colormapfirst, colormaplength, colormapentry = 0, 0, 0\n\n    if im.mode in (\"LA\", \"RGBA\"):\n        flags = 8\n    else:\n        flags = 0\n\n    orientation = im.encoderinfo.get(\"orientation\", im.info.get(\"orientation\", -1))\n    if orientation > 0:\n        flags = flags | 0x20\n\n    fp.write(\n        o8(id_len)\n        + o8(colormaptype)\n        + o8(imagetype)\n        + o16(colormapfirst)\n        + o16(colormaplength)\n        + o8(colormapentry)\n        + o16(0)\n        + o16(0)\n        + o16(im.size[0])\n        + o16(im.size[1])\n        + o8(bits)\n        + o8(flags)\n    )\n\n    if id_section:\n        fp.write(id_section)\n\n    if colormaptype:\n        fp.write(im.im.getpalette(\"RGB\", \"BGR\"))\n\n    if rle:\n        ImageFile._save(\n            im, fp, [(\"tga_rle\", (0, 0) + im.size, 0, (rawmode, orientation))]\n        )\n    else:\n        ImageFile._save(\n            im, fp, [(\"raw\", (0, 0) + im.size, 0, (rawmode, 0, orientation))]\n        )\n\n    # write targa version 2 footer\n    fp.write(b\"\\000\" * 8 + b\"TRUEVISION-XFILE.\" + b\"\\000\")\n\n\n#\n# --------------------------------------------------------------------\n# Registry\n\n\nImage.register_open(TgaImageFile.format, TgaImageFile)\nImage.register_save(TgaImageFile.format, _save)\n\nImage.register_extensions(TgaImageFile.format, [\".tga\", \".icb\", \".vda\", \".vst\"])\n\nImage.register_mime(TgaImageFile.format, \"image/x-tga\")\n",
            "new_file_content": "#\n# The Python Imaging Library.\n# $Id$\n#\n# TGA file handling\n#\n# History:\n# 95-09-01 fl   created (reads 24-bit files only)\n# 97-01-04 fl   support more TGA versions, including compressed images\n# 98-07-04 fl   fixed orientation and alpha layer bugs\n# 98-09-11 fl   fixed orientation for runlength decoder\n#\n# Copyright (c) Secret Labs AB 1997-98.\n# Copyright (c) Fredrik Lundh 1995-97.\n#\n# See the README file for information on usage and redistribution.\n#\n\n\nimport warnings\n\nfrom . import Image, ImageFile, ImagePalette\nfrom ._binary import i16le as i16\nfrom ._binary import o8\nfrom ._binary import o16le as o16\n\n#\n# --------------------------------------------------------------------\n# Read RGA file\n\n\nMODES = {\n    # map imagetype/depth to rawmode\n    (1, 8): \"P\",\n    (3, 1): \"1\",\n    (3, 8): \"L\",\n    (3, 16): \"LA\",\n    (2, 16): \"BGR;5\",\n    (2, 24): \"BGR\",\n    (2, 32): \"BGRA\",\n}\n\n\n##\n# Image plugin for Targa files.\n\n\nclass TgaImageFile(ImageFile.ImageFile):\n\n    format = \"TGA\"\n    format_description = \"Targa\"\n\n    def _open(self):\n\n        # process header\n        s = self.fp.read(18)\n\n        id_len = s[0]\n\n        colormaptype = s[1]\n        imagetype = s[2]\n\n        depth = s[16]\n\n        flags = s[17]\n\n        self._size = i16(s, 12), i16(s, 14)\n\n        # validate header fields\n        if (\n            colormaptype not in (0, 1)\n            or self.size[0] <= 0\n            or self.size[1] <= 0\n            or depth not in (1, 8, 16, 24, 32)\n        ):\n            raise SyntaxError(\"not a TGA file\")\n\n        # image mode\n        if imagetype in (3, 11):\n            self.mode = \"L\"\n            if depth == 1:\n                self.mode = \"1\"  # ???\n            elif depth == 16:\n                self.mode = \"LA\"\n        elif imagetype in (1, 9):\n            self.mode = \"P\"\n        elif imagetype in (2, 10):\n            self.mode = \"RGB\"\n            if depth == 32:\n                self.mode = \"RGBA\"\n        else:\n            raise SyntaxError(\"unknown TGA mode\")\n\n        # orientation\n        orientation = flags & 0x30\n        self._flip_horizontally = orientation in [0x10, 0x30]\n        if orientation in [0x20, 0x30]:\n            orientation = 1\n        elif orientation in [0, 0x10]:\n            orientation = -1\n        else:\n            raise SyntaxError(\"unknown TGA orientation\")\n\n        self.info[\"orientation\"] = orientation\n\n        if imagetype & 8:\n            self.info[\"compression\"] = \"tga_rle\"\n\n        if id_len:\n            self.info[\"id_section\"] = self.fp.read(id_len)\n\n        if colormaptype:\n            # read palette\n            start, size, mapdepth = i16(s, 3), i16(s, 5), s[7]\n            if mapdepth == 16:\n                self.palette = ImagePalette.raw(\n                    \"BGR;15\", b\"\\0\" * 2 * start + self.fp.read(2 * size)\n                )\n            elif mapdepth == 24:\n                self.palette = ImagePalette.raw(\n                    \"BGR\", b\"\\0\" * 3 * start + self.fp.read(3 * size)\n                )\n            elif mapdepth == 32:\n                self.palette = ImagePalette.raw(\n                    \"BGRA\", b\"\\0\" * 4 * start + self.fp.read(4 * size)\n                )\n\n        # setup tile descriptor\n        try:\n            rawmode = MODES[(imagetype & 7, depth)]\n            if imagetype & 8:\n                # compressed\n                self.tile = [\n                    (\n                        \"tga_rle\",\n                        (0, 0) + self.size,\n                        self.fp.tell(),\n                        (rawmode, orientation, depth),\n                    )\n                ]\n            else:\n                self.tile = [\n                    (\n                        \"raw\",\n                        (0, 0) + self.size,\n                        self.fp.tell(),\n                        (rawmode, 0, orientation),\n                    )\n                ]\n        except KeyError:\n            pass  # cannot decode\n\n    def load_end(self):\n        if self._flip_horizontally:\n            self.im = self.im.transpose(Image.Transpose.FLIP_LEFT_RIGHT)\n\n\n#\n# --------------------------------------------------------------------\n# Write TGA file\n\n\nSAVE = {\n    \"1\": (\"1\", 1, 0, 3),\n    \"L\": (\"L\", 8, 0, 3),\n    \"LA\": (\"LA\", 16, 0, 3),\n    \"P\": (\"P\", 8, 1, 1),\n    \"RGB\": (\"BGR\", 24, 0, 2),\n    \"RGBA\": (\"BGRA\", 32, 0, 2),\n}\n\n\ndef _save(im, fp, filename):\n\n    try:\n        rawmode, bits, colormaptype, imagetype = SAVE[im.mode]\n    except KeyError as e:\n        raise OSError(f\"cannot write mode {im.mode} as TGA\") from e\n\n    if \"rle\" in im.encoderinfo:\n        rle = im.encoderinfo[\"rle\"]\n    else:\n        compression = im.encoderinfo.get(\"compression\", im.info.get(\"compression\"))\n        rle = compression == \"tga_rle\"\n    if rle:\n        imagetype += 8\n\n    id_section = im.encoderinfo.get(\"id_section\", im.info.get(\"id_section\", \"\"))\n    id_len = len(id_section)\n    if id_len > 255:\n        id_len = 255\n        id_section = id_section[:255]\n        warnings.warn(\"id_section has been trimmed to 255 characters\")\n\n    if colormaptype:\n        palette = im.im.getpalette(\"RGB\", \"BGR\")\n        colormapfirst, colormaplength, colormapentry = 0, len(palette) // 3, 24\n    else:\n        colormapfirst, colormaplength, colormapentry = 0, 0, 0\n\n    if im.mode in (\"LA\", \"RGBA\"):\n        flags = 8\n    else:\n        flags = 0\n\n    orientation = im.encoderinfo.get(\"orientation\", im.info.get(\"orientation\", -1))\n    if orientation > 0:\n        flags = flags | 0x20\n\n    fp.write(\n        o8(id_len)\n        + o8(colormaptype)\n        + o8(imagetype)\n        + o16(colormapfirst)\n        + o16(colormaplength)\n        + o8(colormapentry)\n        + o16(0)\n        + o16(0)\n        + o16(im.size[0])\n        + o16(im.size[1])\n        + o8(bits)\n        + o8(flags)\n    )\n\n    if id_section:\n        fp.write(id_section)\n\n    if colormaptype:\n        fp.write(palette)\n\n    if rle:\n        ImageFile._save(\n            im, fp, [(\"tga_rle\", (0, 0) + im.size, 0, (rawmode, orientation))]\n        )\n    else:\n        ImageFile._save(\n            im, fp, [(\"raw\", (0, 0) + im.size, 0, (rawmode, 0, orientation))]\n        )\n\n    # write targa version 2 footer\n    fp.write(b\"\\000\" * 8 + b\"TRUEVISION-XFILE.\" + b\"\\000\")\n\n\n#\n# --------------------------------------------------------------------\n# Registry\n\n\nImage.register_open(TgaImageFile.format, TgaImageFile)\nImage.register_save(TgaImageFile.format, _save)\n\nImage.register_extensions(TgaImageFile.format, [\".tga\", \".icb\", \".vda\", \".vst\"])\n\nImage.register_mime(TgaImageFile.format, \"image/x-tga\")\n",
            "header": {
                "file": {
                    "path": "src/PIL/TgaImagePlugin.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "59b89e988",
                "new_commit_hash": "7f5075317",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/src/PIL/TgaImagePlugin.py"
            },
            "plus_file": {
                "path": "b/src/PIL/TgaImagePlugin.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 193,
                            "length": 7
                        },
                        "new_range": {
                            "start": 193,
                            "length": 8
                        },
                        "section": "def _save(im, fp, filename):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        warnings.warn(\"id_section has been trimmed to 255 characters\")",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    if colormaptype:",
                                "type": "context"
                            },
                            {
                                "content": "        colormapfirst, colormaplength, colormapentry = 0, 256, 24",
                                "type": "deleted"
                            },
                            {
                                "content": "        palette = im.im.getpalette(\"RGB\", \"BGR\")",
                                "type": "added"
                            },
                            {
                                "content": "        colormapfirst, colormaplength, colormapentry = 0, len(palette) // 3, 24",
                                "type": "added"
                            },
                            {
                                "content": "    else:",
                                "type": "context"
                            },
                            {
                                "content": "        colormapfirst, colormaplength, colormapentry = 0, 0, 0",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "src/PIL/TgaImagePlugin.py",
                            "type": "function",
                            "name": "_save",
                            "content": "def _save(im, fp, filename):\n\n    try:\n        rawmode, bits, colormaptype, imagetype = SAVE[im.mode]\n    except KeyError as e:\n        raise OSError(f\"cannot write mode {im.mode} as TGA\") from e\n\n    if \"rle\" in im.encoderinfo:\n        rle = im.encoderinfo[\"rle\"]\n    else:\n        compression = im.encoderinfo.get(\"compression\", im.info.get(\"compression\"))\n        rle = compression == \"tga_rle\"\n    if rle:\n        imagetype += 8\n\n    id_section = im.encoderinfo.get(\"id_section\", im.info.get(\"id_section\", \"\"))\n    id_len = len(id_section)\n    if id_len > 255:\n        id_len = 255\n        id_section = id_section[:255]\n        warnings.warn(\"id_section has been trimmed to 255 characters\")\n\n    if colormaptype:\n        colormapfirst, colormaplength, colormapentry = 0, 256, 24\n    else:\n        colormapfirst, colormaplength, colormapentry = 0, 0, 0\n\n    if im.mode in (\"LA\", \"RGBA\"):\n        flags = 8\n    else:\n        flags = 0\n\n    orientation = im.encoderinfo.get(\"orientation\", im.info.get(\"orientation\", -1))\n    if orientation > 0:\n        flags = flags | 0x20\n\n    fp.write(\n        o8(id_len)\n        + o8(colormaptype)\n        + o8(imagetype)\n        + o16(colormapfirst)\n        + o16(colormaplength)\n        + o8(colormapentry)\n        + o16(0)\n        + o16(0)\n        + o16(im.size[0])\n        + o16(im.size[1])\n        + o8(bits)\n        + o8(flags)\n    )\n\n    if id_section:\n        fp.write(id_section)\n\n    if colormaptype:\n        fp.write(im.im.getpalette(\"RGB\", \"BGR\"))\n\n    if rle:\n        ImageFile._save(\n            im, fp, [(\"tga_rle\", (0, 0) + im.size, 0, (rawmode, orientation))]\n        )\n    else:\n        ImageFile._save(\n            im, fp, [(\"raw\", (0, 0) + im.size, 0, (rawmode, 0, orientation))]\n        )\n\n    # write targa version 2 footer\n    fp.write(b\"\\000\" * 8 + b\"TRUEVISION-XFILE.\" + b\"\\000\")",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 173,
                            "end_lineno": 240,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 225,
                            "length": 7
                        },
                        "new_range": {
                            "start": 226,
                            "length": 7
                        },
                        "section": "def _save(im, fp, filename):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        fp.write(id_section)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    if colormaptype:",
                                "type": "context"
                            },
                            {
                                "content": "        fp.write(im.im.getpalette(\"RGB\", \"BGR\"))",
                                "type": "deleted"
                            },
                            {
                                "content": "        fp.write(palette)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    if rle:",
                                "type": "context"
                            },
                            {
                                "content": "        ImageFile._save(",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "src/PIL/TgaImagePlugin.py",
                            "type": "function",
                            "name": "_save",
                            "content": "def _save(im, fp, filename):\n\n    try:\n        rawmode, bits, colormaptype, imagetype = SAVE[im.mode]\n    except KeyError as e:\n        raise OSError(f\"cannot write mode {im.mode} as TGA\") from e\n\n    if \"rle\" in im.encoderinfo:\n        rle = im.encoderinfo[\"rle\"]\n    else:\n        compression = im.encoderinfo.get(\"compression\", im.info.get(\"compression\"))\n        rle = compression == \"tga_rle\"\n    if rle:\n        imagetype += 8\n\n    id_section = im.encoderinfo.get(\"id_section\", im.info.get(\"id_section\", \"\"))\n    id_len = len(id_section)\n    if id_len > 255:\n        id_len = 255\n        id_section = id_section[:255]\n        warnings.warn(\"id_section has been trimmed to 255 characters\")\n\n    if colormaptype:\n        colormapfirst, colormaplength, colormapentry = 0, 256, 24\n    else:\n        colormapfirst, colormaplength, colormapentry = 0, 0, 0\n\n    if im.mode in (\"LA\", \"RGBA\"):\n        flags = 8\n    else:\n        flags = 0\n\n    orientation = im.encoderinfo.get(\"orientation\", im.info.get(\"orientation\", -1))\n    if orientation > 0:\n        flags = flags | 0x20\n\n    fp.write(\n        o8(id_len)\n        + o8(colormaptype)\n        + o8(imagetype)\n        + o16(colormapfirst)\n        + o16(colormaplength)\n        + o8(colormapentry)\n        + o16(0)\n        + o16(0)\n        + o16(im.size[0])\n        + o16(im.size[1])\n        + o8(bits)\n        + o8(flags)\n    )\n\n    if id_section:\n        fp.write(id_section)\n\n    if colormaptype:\n        fp.write(im.im.getpalette(\"RGB\", \"BGR\"))\n\n    if rle:\n        ImageFile._save(\n            im, fp, [(\"tga_rle\", (0, 0) + im.size, 0, (rawmode, orientation))]\n        )\n    else:\n        ImageFile._save(\n            im, fp, [(\"raw\", (0, 0) + im.size, 0, (rawmode, 0, orientation))]\n        )\n\n    # write targa version 2 footer\n    fp.write(b\"\\000\" * 8 + b\"TRUEVISION-XFILE.\" + b\"\\000\")",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 173,
                            "end_lineno": 240,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "99e401123bab56bf9c64314b506750a4ea6a9e79^",
    "new_commit_hash": "99e401123bab56bf9c64314b506750a4ea6a9e79",
    "commit_message": "Corrected palette size when saving",
    "commit_date": "2022-08-13T19:46:07+10:00",
    "metadata": {}
}
{
    "repo_name": "pillow",
    "new_commit_hash": "99e401123bab56bf9c64314b506750a4ea6a9e79",
    "test_file_codes": [
        "import os\nfrom glob import glob\nfrom itertools import product\n\nimport pytest\n\nfrom PIL import Image\n\nfrom .helper import assert_image_equal, assert_image_equal_tofile, hopper\n\n_TGA_DIR = os.path.join(\"Tests\", \"images\", \"tga\")\n_TGA_DIR_COMMON = os.path.join(_TGA_DIR, \"common\")\n\n\n_MODES = (\"L\", \"LA\", \"P\", \"RGB\", \"RGBA\")\n_ORIGINS = (\"tl\", \"bl\")\n\n_ORIGIN_TO_ORIENTATION = {\"tl\": 1, \"bl\": -1}\n\n\ndef test_sanity(tmp_path):\n    for mode in _MODES:\n\n        def roundtrip(original_im):\n            out = str(tmp_path / \"temp.tga\")\n\n            original_im.save(out, rle=rle)\n            with Image.open(out) as saved_im:\n                if rle:\n                    assert (\n                        saved_im.info[\"compression\"] == original_im.info[\"compression\"]\n                    )\n                assert saved_im.info[\"orientation\"] == original_im.info[\"orientation\"]\n                if mode == \"P\":\n                    assert saved_im.getpalette() == original_im.getpalette()\n\n                assert_image_equal(saved_im, original_im)\n\n        png_paths = glob(os.path.join(_TGA_DIR_COMMON, f\"*x*_{mode.lower()}.png\"))\n\n        for png_path in png_paths:\n            with Image.open(png_path) as reference_im:\n                assert reference_im.mode == mode\n\n                path_no_ext = os.path.splitext(png_path)[0]\n                for origin, rle in product(_ORIGINS, (True, False)):\n                    tga_path = \"{}_{}_{}.tga\".format(\n                        path_no_ext, origin, \"rle\" if rle else \"raw\"\n                    )\n\n                    with Image.open(tga_path) as original_im:\n                        assert original_im.format == \"TGA\"\n                        assert original_im.get_format_mimetype() == \"image/x-tga\"\n                        if rle:\n                            assert original_im.info[\"compression\"] == \"tga_rle\"\n                        assert (\n                            original_im.info[\"orientation\"]\n                            == _ORIGIN_TO_ORIENTATION[origin]\n                        )\n                        if mode == \"P\":\n                            assert original_im.getpalette() == reference_im.getpalette()\n\n                        assert_image_equal(original_im, reference_im)\n\n                        roundtrip(original_im)\n\n\ndef test_palette_depth_16(tmp_path):\n    with Image.open(\"Tests/images/p_16.tga\") as im:\n        assert_image_equal_tofile(im.convert(\"RGB\"), \"Tests/images/p_16.png\")\n\n        out = str(tmp_path / \"temp.png\")\n        im.save(out)\n        with Image.open(out) as reloaded:\n            assert_image_equal_tofile(reloaded.convert(\"RGB\"), \"Tests/images/p_16.png\")\n\n\ndef test_id_field():\n    # tga file with id field\n    test_file = \"Tests/images/tga_id_field.tga\"\n\n    # Act\n    with Image.open(test_file) as im:\n\n        # Assert\n        assert im.size == (100, 100)\n\n\ndef test_id_field_rle():\n    # tga file with id field\n    test_file = \"Tests/images/rgb32rle.tga\"\n\n    # Act\n    with Image.open(test_file) as im:\n\n        # Assert\n        assert im.size == (199, 199)\n\n\ndef test_cross_scan_line():\n    with Image.open(\"Tests/images/cross_scan_line.tga\") as im:\n        assert_image_equal_tofile(im, \"Tests/images/cross_scan_line.png\")\n\n    with Image.open(\"Tests/images/cross_scan_line_truncated.tga\") as im:\n        with pytest.raises(OSError):\n            im.load()\n\n\ndef test_save(tmp_path):\n    test_file = \"Tests/images/tga_id_field.tga\"\n    with Image.open(test_file) as im:\n        out = str(tmp_path / \"temp.tga\")\n\n        # Save\n        im.save(out)\n        with Image.open(out) as test_im:\n            assert test_im.size == (100, 100)\n            assert test_im.info[\"id_section\"] == im.info[\"id_section\"]\n\n        # RGBA save\n        im.convert(\"RGBA\").save(out)\n    with Image.open(out) as test_im:\n        assert test_im.size == (100, 100)\n\n\ndef test_small_palette(tmp_path):\n    im = Image.new(\"P\", (1, 1))\n    colors = [0, 0, 0]\n    im.putpalette(colors)\n\n    out = str(tmp_path / \"temp.tga\")\n    im.save(out)\n\n    with Image.open(out) as reloaded:\n        assert reloaded.getpalette() == colors\n\n\ndef test_save_wrong_mode(tmp_path):\n    im = hopper(\"PA\")\n    out = str(tmp_path / \"temp.tga\")\n\n    with pytest.raises(OSError):\n        im.save(out)\n\n\ndef test_save_mapdepth():\n    # This image has been manually hexedited from 200x32_p_bl_raw.tga\n    # to include an origin\n    test_file = \"Tests/images/200x32_p_bl_raw_origin.tga\"\n    with Image.open(test_file) as im:\n        assert_image_equal_tofile(im, \"Tests/images/tga/common/200x32_p.png\")\n\n\ndef test_save_id_section(tmp_path):\n    test_file = \"Tests/images/rgb32rle.tga\"\n    with Image.open(test_file) as im:\n        out = str(tmp_path / \"temp.tga\")\n\n        # Check there is no id section\n        im.save(out)\n    with Image.open(out) as test_im:\n        assert \"id_section\" not in test_im.info\n\n    # Save with custom id section\n    im.save(out, id_section=b\"Test content\")\n    with Image.open(out) as test_im:\n        assert test_im.info[\"id_section\"] == b\"Test content\"\n\n    # Save with custom id section greater than 255 characters\n    id_section = b\"Test content\" * 25\n    pytest.warns(UserWarning, lambda: im.save(out, id_section=id_section))\n    with Image.open(out) as test_im:\n        assert test_im.info[\"id_section\"] == id_section[:255]\n\n    test_file = \"Tests/images/tga_id_field.tga\"\n    with Image.open(test_file) as im:\n\n        # Save with no id section\n        im.save(out, id_section=\"\")\n    with Image.open(out) as test_im:\n        assert \"id_section\" not in test_im.info\n\n\ndef test_save_orientation(tmp_path):\n    test_file = \"Tests/images/rgb32rle.tga\"\n    out = str(tmp_path / \"temp.tga\")\n    with Image.open(test_file) as im:\n        assert im.info[\"orientation\"] == -1\n\n        im.save(out, orientation=1)\n    with Image.open(out) as test_im:\n        assert test_im.info[\"orientation\"] == 1\n\n\ndef test_horizontal_orientations():\n    # These images have been manually hexedited to have the relevant orientations\n    with Image.open(\"Tests/images/rgb32rle_top_right.tga\") as im:\n        assert im.load()[90, 90][:3] == (0, 0, 0)\n\n    with Image.open(\"Tests/images/rgb32rle_bottom_right.tga\") as im:\n        assert im.load()[90, 90][:3] == (0, 255, 0)\n\n\ndef test_save_rle(tmp_path):\n    test_file = \"Tests/images/rgb32rle.tga\"\n    with Image.open(test_file) as im:\n        assert im.info[\"compression\"] == \"tga_rle\"\n\n        out = str(tmp_path / \"temp.tga\")\n\n        # Save\n        im.save(out)\n    with Image.open(out) as test_im:\n        assert test_im.size == (199, 199)\n        assert test_im.info[\"compression\"] == \"tga_rle\"\n\n    # Save without compression\n    im.save(out, compression=None)\n    with Image.open(out) as test_im:\n        assert \"compression\" not in test_im.info\n\n    # RGBA save\n    im.convert(\"RGBA\").save(out)\n    with Image.open(out) as test_im:\n        assert test_im.size == (199, 199)\n\n    test_file = \"Tests/images/tga_id_field.tga\"\n    with Image.open(test_file) as im:\n        assert \"compression\" not in im.info\n\n        # Save with compression\n        im.save(out, compression=\"tga_rle\")\n    with Image.open(out) as test_im:\n        assert test_im.info[\"compression\"] == \"tga_rle\"\n\n\ndef test_save_l_transparency(tmp_path):\n    # There are 559 transparent pixels in la.tga.\n    num_transparent = 559\n\n    in_file = \"Tests/images/la.tga\"\n    with Image.open(in_file) as im:\n        assert im.mode == \"LA\"\n        assert im.getchannel(\"A\").getcolors()[0][0] == num_transparent\n\n        out = str(tmp_path / \"temp.tga\")\n        im.save(out)\n\n    with Image.open(out) as test_im:\n        assert test_im.mode == \"LA\"\n        assert test_im.getchannel(\"A\").getcolors()[0][0] == num_transparent\n\n        assert_image_equal(im, test_im)\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 16ms\nInstalled 12 packages in 140ms\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 841ms\nPrepared 1 package in 33.70s\nInstalled 1 package in 1ms\n + pillow==9.3.0.dev0 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/pillow_99e401123bab56bf9c64314b506750a4ea6a9e79)\n",
    "new_commit_res_code": 0,
    "new_commit_res_stdout": "\u001b[1m============================= test session starts ==============================\u001b[0m\nplatform linux -- Python 3.9.21, pytest-8.3.4, pluggy-1.5.0\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/pillow_99e401123bab56bf9c64314b506750a4ea6a9e79\nconfigfile: setup.cfg\nplugins: cov-6.0.0\ncollected 14 items\n\nr2e_tests/test_1.py \u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m                                       [100%]\u001b[0m\n\n==================================== PASSES ====================================\n\u001b[36m\u001b[1m=========================== short test summary info ============================\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_sanity\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_palette_depth_16\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_id_field\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_id_field_rle\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_cross_scan_line\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_save\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_small_palette\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_save_wrong_mode\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_save_mapdepth\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_save_id_section\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_save_orientation\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_horizontal_orientations\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_save_rle\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_save_l_transparency\u001b[0m\n\u001b[32m============================== \u001b[32m\u001b[1m14 passed\u001b[0m\u001b[32m in 0.29s\u001b[0m\u001b[32m ==============================\u001b[0m\n",
    "new_commit_res_stderr": "",
    "old_commit_res_code": 1,
    "old_commit_res_stdout": "\u001b[1m============================= test session starts ==============================\u001b[0m\nplatform linux -- Python 3.9.21, pytest-8.3.4, pluggy-1.5.0\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/pillow_99e401123bab56bf9c64314b506750a4ea6a9e79\nconfigfile: setup.cfg\nplugins: cov-6.0.0\ncollected 14 items\n\nr2e_tests/test_1.py \u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[31mF\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[32m.\u001b[0m\u001b[31m                                       [100%]\u001b[0m\n\n=================================== FAILURES ===================================\n\u001b[31m\u001b[1m______________________________ test_small_palette ______________________________\u001b[0m\n\ntmp_path = PosixPath('/tmp/pytest-of-gcpuser/pytest-463/test_small_palette0')\n\n    def test_small_palette(tmp_path):\n        im = Image.new(\"P\", (1, 1))\n        colors = [0, 0, 0]\n        im.putpalette(colors)\n    \n        out = str(tmp_path / \"temp.tga\")\n        im.save(out)\n    \n        with Image.open(out) as reloaded:\n>           assert reloaded.getpalette() == colors\n\n\u001b[1m\u001b[31mr2e_tests/test_1.py\u001b[0m:135: \n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\u001b[1m\u001b[31msrc/PIL/Image.py\u001b[0m:1442: in getpalette\n    self.load()\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n\nself = <PIL.TgaImagePlugin.TgaImageFile image mode=P size=1x1 at 0x7F7D210C8700>\n\n    def load(self):\n        \"\"\"Load image data based on tile list\"\"\"\n    \n        if self.tile is None:\n            raise OSError(\"cannot load this image\")\n    \n        pixel = Image.Image.load(self)\n        if not self.tile:\n            return pixel\n    \n        self.map = None\n        use_mmap = self.filename and len(self.tile) == 1\n        # As of pypy 2.1.0, memory mapping was failing here.\n        use_mmap = use_mmap and not hasattr(sys, \"pypy_version_info\")\n    \n        readonly = 0\n    \n        # look for read/seek overrides\n        try:\n            read = self.load_read\n            # don't use mmap if there are custom read/seek functions\n            use_mmap = False\n        except AttributeError:\n            read = self.fp.read\n    \n        try:\n            seek = self.load_seek\n            use_mmap = False\n        except AttributeError:\n            seek = self.fp.seek\n    \n        if use_mmap:\n            # try memory mapping\n            decoder_name, extents, offset, args = self.tile[0]\n            if (\n                decoder_name == \"raw\"\n                and len(args) >= 3\n                and args[0] == self.mode\n                and args[0] in Image._MAPMODES\n            ):\n                try:\n                    # use mmap, if possible\n                    import mmap\n    \n                    with open(self.filename) as fp:\n                        self.map = mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ)\n>                   self.im = Image.core.map_buffer(\n                        self.map, self.size, decoder_name, offset, args\n                    )\n\u001b[1m\u001b[31mE                   ValueError: buffer is not large enough\u001b[0m\n\n\u001b[1m\u001b[31msrc/PIL/ImageFile.py\u001b[0m:195: ValueError\n==================================== PASSES ====================================\n\u001b[36m\u001b[1m=========================== short test summary info ============================\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_sanity\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_palette_depth_16\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_id_field\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_id_field_rle\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_cross_scan_line\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_save\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_save_wrong_mode\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_save_mapdepth\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_save_id_section\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_save_orientation\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_horizontal_orientations\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_save_rle\u001b[0m\n\u001b[32mPASSED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_save_l_transparency\u001b[0m\n\u001b[31mFAILED\u001b[0m r2e_tests/test_1.py::\u001b[1mtest_small_palette\u001b[0m - ValueError: buffer is not large enough\n\u001b[31m========================= \u001b[31m\u001b[1m1 failed\u001b[0m, \u001b[32m13 passed\u001b[0m\u001b[31m in 0.22s\u001b[0m\u001b[31m =========================\u001b[0m\n",
    "old_commit_res_stderr": ""
}
Tests/test_file_tga.py src/PIL/TgaImagePlugin.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** Saving TGA Images with Small Palettes Raises "Buffer is Not Large Enough" Error

**Description:**
When attempting to save a TGA image with a small palette, a `ValueError` is raised stating that the buffer is not large enough. This issue occurs because the palette size is incorrectly fixed, preventing the saving of images with palettes smaller than 256 colors.

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

im = Image.new("P", (1, 1))
colors = [0, 0, 0]  # Small palette with only one color
im.putpalette(colors)

im.save("temp.tga")
```

**Expected Behavior:**
The image should be saved successfully using the provided small palette without any errors.

**Actual Behavior:**
A `ValueError` is raised with the message "buffer is not large enough," preventing the image from being saved.

[/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/TgaImagePlugin.py
#
# The Python Imaging Library.
# $Id$
#
# TGA file handling
#
# History:
# 95-09-01 fl   created (reads 24-bit files only)
# 97-01-04 fl   support more TGA versions, including compressed images
# 98-07-04 fl   fixed orientation and alpha layer bugs
# 98-09-11 fl   fixed orientation for runlength decoder
#
# Copyright (c) Secret Labs AB 1997-98.
# Copyright (c) Fredrik Lundh 1995-97.
#
# See the README file for information on usage and redistribution.
#


import warnings

from . import Image, ImageFile, ImagePalette
from ._binary import i16le as i16
from ._binary import o8
from ._binary import o16le as o16

#
# --------------------------------------------------------------------
# Read RGA file


MODES = {
    # map imagetype/depth to rawmode
    (1, 8): "P",
    (3, 1): "1",
    (3, 8): "L",
    (3, 16): "LA",
    (2, 16): "BGR;5",
    (2, 24): "BGR",
    (2, 32): "BGRA",
}


##
# Image plugin for Targa files.


class TgaImageFile(ImageFile.ImageFile):

    format = "TGA"
    format_description = "Targa"

    def _open(self):

        # process header
        s = self.fp.read(18)

        id_len = s[0]

        colormaptype = s[1]
        imagetype = s[2]

        depth = s[16]

        flags = s[17]

        self._size = i16(s, 12), i16(s, 14)

        # validate header fields
        if (
            colormaptype not in (0, 1)
            or self.size[0] <= 0
            or self.size[1] <= 0
            or depth not in (1, 8, 16, 24, 32)
        ):
            raise SyntaxError("not a TGA file")

        # image mode
        if imagetype in (3, 11):
            self.mode = "L"
            if depth == 1:
                self.mode = "1"  # ???
            elif depth == 16:
                self.mode = "LA"
        elif imagetype in (1, 9):
            self.mode = "P"
        elif imagetype in (2, 10):
            self.mode = "RGB"
            if depth == 32:
                self.mode = "RGBA"
        else:
            raise SyntaxError("unknown TGA mode")

        # orientation
        orientation = flags & 0x30
        self._flip_horizontally = orientation in [0x10, 0x30]
        if orientation in [0x20, 0x30]:
            orientation = 1
        elif orientation in [0, 0x10]:
            orientation = -1
        else:
            raise SyntaxError("unknown TGA orientation")

        self.info["orientation"] = orientation

        if imagetype & 8:
            self.info["compression"] = "tga_rle"

        if id_len:
            self.info["id_section"] = self.fp.read(id_len)

        if colormaptype:
            # read palette
            start, size, mapdepth = i16(s, 3), i16(s, 5), s[7]
            if mapdepth == 16:
                self.palette = ImagePalette.raw(
                    "BGR;15", b"\0" * 2 * start + self.fp.read(2 * size)
                )
            elif mapdepth == 24:
                self.palette = ImagePalette.raw(
                    "BGR", b"\0" * 3 * start + self.fp.read(3 * size)
                )
            elif mapdepth == 32:
                self.palette = ImagePalette.raw(
                    "BGRA", b"\0" * 4 * start + self.fp.read(4 * size)
                )

        # setup tile descriptor
        try:
            rawmode = MODES[(imagetype & 7, depth)]
            if imagetype & 8:
                # compressed
                self.tile = [
                    (
                        "tga_rle",
                        (0, 0) + self.size,
                        self.fp.tell(),
                        (rawmode, orientation, depth),
                    )
                ]
            else:
                self.tile = [
                    (
                        "raw",
                        (0, 0) + self.size,
                        self.fp.tell(),
                        (rawmode, 0, orientation),
                    )
                ]
        except KeyError:
            pass  # cannot decode

    def load_end(self):
        if self._flip_horizontally:
            self.im = self.im.transpose(Image.Transpose.FLIP_LEFT_RIGHT)


#
# --------------------------------------------------------------------
# Write TGA file


SAVE = {
    "1": ("1", 1, 0, 3),
    "L": ("L", 8, 0, 3),
    "LA": ("LA", 16, 0, 3),
    "P": ("P", 8, 1, 1),
    "RGB": ("BGR", 24, 0, 2),
    "RGBA": ("BGRA", 32, 0, 2),
}


def _save(im, fp, filename):

    try:
        rawmode, bits, colormaptype, imagetype = SAVE[im.mode]
    except KeyError as e:
        raise OSError(f"cannot write mode {im.mode} as TGA") from e

    if "rle" in im.encoderinfo:
        rle = im.encoderinfo["rle"]
    else:
        compression = im.encoderinfo.get("compression", im.info.get("compression"))
        rle = compression == "tga_rle"
    if rle:
        imagetype += 8

    id_section = im.encoderinfo.get("id_section", im.info.get("id_section", ""))
    id_len = len(id_section)
    if id_len > 255:
        id_len = 255
        id_section = id_section[:255]
        warnings.warn("id_section has been trimmed to 255 characters")

    if colormaptype:
        colormapfirst, colormaplength, colormapentry = 0, 256, 24
    else:
        colormapfirst, colormaplength, colormapentry = 0, 0, 0

    if im.mode in ("LA", "RGBA"):
        flags = 8
    else:
        flags = 0

    orientation = im.encoderinfo.get("orientation", im.info.get("orientation", -1))
    if orientation > 0:
        flags = flags | 0x20

    fp.write(
        o8(id_len)
        + o8(colormaptype)
        + o8(imagetype)
        + o16(colormapfirst)
        + o16(colormaplength)
        + o8(colormapentry)
        + o16(0)
        + o16(0)
        + o16(im.size[0])
        + o16(im.size[1])
        + o8(bits)
        + o8(flags)
    )

    if id_section:
        fp.write(id_section)

    if colormaptype:
        fp.write(im.im.getpalette("RGB", "BGR"))

    if rle:
        ImageFile._save(
            im, fp, [("tga_rle", (0, 0) + im.size, 0, (rawmode, orientation))]
        )
    else:
        ImageFile._save(
            im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, 0, orientation))]
        )

    # write targa version 2 footer
    fp.write(b"\000" * 8 + b"TRUEVISION-XFILE." + b"\000")


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


Image.register_open(TgaImageFile.format, TgaImageFile)
Image.register_save(TgaImageFile.format, _save)

Image.register_extensions(TgaImageFile.format, [".tga", ".icb", ".vda", ".vst"])

Image.register_mime(TgaImageFile.format, "image/x-tga")

```
--- 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:** Saving TGA Images with Small Palettes Raises "Buffer is Not Large Enough" Error

**Description:**
When attempting to save a TGA image with a small palette, a `ValueError` is raised stating that the buffer is not large enough. This issue occurs because the palette size is incorrectly fixed, preventing the saving of images with palettes smaller than 256 colors.

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

im = Image.new("P", (1, 1))
colors = [0, 0, 0]  # Small palette with only one color
im.putpalette(colors)

im.save("temp.tga")
```

**Expected Behavior:**
The image should be saved successfully using the provided small palette without any errors.

**Actual Behavior:**
A `ValueError` is raised with the message "buffer is not large enough," preventing the image from being saved.

[/ISSUE]
{
    "\u001b[1mtest_sanity\u001b[0m": "PASSED",
    "\u001b[1mtest_palette_depth_16\u001b[0m": "PASSED",
    "\u001b[1mtest_id_field\u001b[0m": "PASSED",
    "\u001b[1mtest_id_field_rle\u001b[0m": "PASSED",
    "\u001b[1mtest_cross_scan_line\u001b[0m": "PASSED",
    "\u001b[1mtest_save\u001b[0m": "PASSED",
    "\u001b[1mtest_small_palette\u001b[0m": "PASSED",
    "\u001b[1mtest_save_wrong_mode\u001b[0m": "PASSED",
    "\u001b[1mtest_save_mapdepth\u001b[0m": "PASSED",
    "\u001b[1mtest_save_id_section\u001b[0m": "PASSED",
    "\u001b[1mtest_save_orientation\u001b[0m": "PASSED",
    "\u001b[1mtest_horizontal_orientations\u001b[0m": "PASSED",
    "\u001b[1mtest_save_rle\u001b[0m": "PASSED",
    "\u001b[1mtest_save_l_transparency\u001b[0m": "PASSED"
}
diff --git a/src/PIL/TgaImagePlugin.py b/src/PIL/TgaImagePlugin.py
index 59b89e988..7f5075317 100644
--- a/src/PIL/TgaImagePlugin.py
+++ b/src/PIL/TgaImagePlugin.py
@@ -193,7 +193,8 @@ def _save(im, fp, filename):
         warnings.warn("id_section has been trimmed to 255 characters")
 
     if colormaptype:
-        colormapfirst, colormaplength, colormapentry = 0, 256, 24
+        palette = im.im.getpalette("RGB", "BGR")
+        colormapfirst, colormaplength, colormapentry = 0, len(palette) // 3, 24
     else:
         colormapfirst, colormaplength, colormapentry = 0, 0, 0
 
@@ -225,7 +226,7 @@ def _save(im, fp, filename):
         fp.write(id_section)
 
     if colormaptype:
-        fp.write(im.im.getpalette("RGB", "BGR"))
+        fp.write(palette)
 
     if rle:
         ImageFile._save(
 

{"src/PIL/TgaImagePlugin.py": "#\n# The Python Imaging Library.\n# $Id$\n#\n# TGA file handling\n#\n# History:\n# 95-09-01 fl   created (reads 24-bit files only)\n# 97-01-04 fl   support more TGA versions, including compressed images\n# 98-07-04 fl   fixed orientation and alpha layer bugs\n# 98-09-11 fl   fixed orientation for runlength decoder\n#\n# Copyright (c) Secret Labs AB 1997-98.\n# Copyright (c) Fredrik Lundh 1995-97.\n#\n# See the README file for information on usage and redistribution.\n#\n\n\nimport warnings\n\nfrom . import Image, ImageFile, ImagePalette\nfrom ._binary import i16le as i16\nfrom ._binary import o8\nfrom ._binary import o16le as o16\n\n#\n# --------------------------------------------------------------------\n# Read RGA file\n\n\nMODES = {\n    # map imagetype/depth to rawmode\n    (1, 8): \"P\",\n    (3, 1): \"1\",\n    (3, 8): \"L\",\n    (3, 16): \"LA\",\n    (2, 16): \"BGR;5\",\n    (2, 24): \"BGR\",\n    (2, 32): \"BGRA\",\n}\n\n\n##\n# Image plugin for Targa files.\n\n\nclass TgaImageFile(ImageFile.ImageFile):\n\n    format = \"TGA\"\n    format_description = \"Targa\"\n\n    def _open(self):\n\n        # process header\n        s = self.fp.read(18)\n\n        id_len = s[0]\n\n        colormaptype = s[1]\n        imagetype = s[2]\n\n        depth = s[16]\n\n        flags = s[17]\n\n        self._size = i16(s, 12), i16(s, 14)\n\n        # validate header fields\n        if (\n            colormaptype not in (0, 1)\n            or self.size[0] <= 0\n            or self.size[1] <= 0\n            or depth not in (1, 8, 16, 24, 32)\n        ):\n            raise SyntaxError(\"not a TGA file\")\n\n        # image mode\n        if imagetype in (3, 11):\n            self.mode = \"L\"\n            if depth == 1:\n                self.mode = \"1\"  # ???\n            elif depth == 16:\n                self.mode = \"LA\"\n        elif imagetype in (1, 9):\n            self.mode = \"P\"\n        elif imagetype in (2, 10):\n            self.mode = \"RGB\"\n            if depth == 32:\n                self.mode = \"RGBA\"\n        else:\n            raise SyntaxError(\"unknown TGA mode\")\n\n        # orientation\n        orientation = flags & 0x30\n        self._flip_horizontally = orientation in [0x10, 0x30]\n        if orientation in [0x20, 0x30]:\n            orientation = 1\n        elif orientation in [0, 0x10]:\n            orientation = -1\n        else:\n            raise SyntaxError(\"unknown TGA orientation\")\n\n        self.info[\"orientation\"] = orientation\n\n        if imagetype & 8:\n            self.info[\"compression\"] = \"tga_rle\"\n\n        if id_len:\n            self.info[\"id_section\"] = self.fp.read(id_len)\n\n        if colormaptype:\n            # read palette\n            start, size, mapdepth = i16(s, 3), i16(s, 5), s[7]\n            if mapdepth == 16:\n                self.palette = ImagePalette.raw(\n                    \"BGR;15\", b\"\\0\" * 2 * start + self.fp.read(2 * size)\n                )\n            elif mapdepth == 24:\n                self.palette = ImagePalette.raw(\n                    \"BGR\", b\"\\0\" * 3 * start + self.fp.read(3 * size)\n                )\n            elif mapdepth == 32:\n                self.palette = ImagePalette.raw(\n                    \"BGRA\", b\"\\0\" * 4 * start + self.fp.read(4 * size)\n                )\n\n        # setup tile descriptor\n        try:\n            rawmode = MODES[(imagetype & 7, depth)]\n            if imagetype & 8:\n                # compressed\n                self.tile = [\n                    (\n                        \"tga_rle\",\n                        (0, 0) + self.size,\n                        self.fp.tell(),\n                        (rawmode, orientation, depth),\n                    )\n                ]\n            else:\n                self.tile = [\n                    (\n                        \"raw\",\n                        (0, 0) + self.size,\n                        self.fp.tell(),\n                        (rawmode, 0, orientation),\n                    )\n                ]\n        except KeyError:\n            pass  # cannot decode\n\n    def load_end(self):\n        if self._flip_horizontally:\n            self.im = self.im.transpose(Image.Transpose.FLIP_LEFT_RIGHT)\n\n\n#\n# --------------------------------------------------------------------\n# Write TGA file\n\n\nSAVE = {\n    \"1\": (\"1\", 1, 0, 3),\n    \"L\": (\"L\", 8, 0, 3),\n    \"LA\": (\"LA\", 16, 0, 3),\n    \"P\": (\"P\", 8, 1, 1),\n    \"RGB\": (\"BGR\", 24, 0, 2),\n    \"RGBA\": (\"BGRA\", 32, 0, 2),\n}\n\n\ndef _save(im, fp, filename):\n\n    try:\n        rawmode, bits, colormaptype, imagetype = SAVE[im.mode]\n    except KeyError as e:\n        raise OSError(f\"cannot write mode {im.mode} as TGA\") from e\n\n    if \"rle\" in im.encoderinfo:\n        rle = im.encoderinfo[\"rle\"]\n    else:\n        compression = im.encoderinfo.get(\"compression\", im.info.get(\"compression\"))\n        rle = compression == \"tga_rle\"\n    if rle:\n        imagetype += 8\n\n    id_section = im.encoderinfo.get(\"id_section\", im.info.get(\"id_section\", \"\"))\n    id_len = len(id_section)\n    if id_len > 255:\n        id_len = 255\n        id_section = id_section[:255]\n        warnings.warn(\"id_section has been trimmed to 255 characters\")\n\n    if colormaptype:\n        colormapfirst, colormaplength, colormapentry = 0, 256, 24\n    else:\n        colormapfirst, colormaplength, colormapentry = 0, 0, 0\n\n    if im.mode in (\"LA\", \"RGBA\"):\n        flags = 8\n    else:\n        flags = 0\n\n    orientation = im.encoderinfo.get(\"orientation\", im.info.get(\"orientation\", -1))\n    if orientation > 0:\n        flags = flags | 0x20\n\n    fp.write(\n        o8(id_len)\n        + o8(colormaptype)\n        + o8(imagetype)\n        + o16(colormapfirst)\n        + o16(colormaplength)\n        + o8(colormapentry)\n        + o16(0)\n        + o16(0)\n        + o16(im.size[0])\n        + o16(im.size[1])\n        + o8(bits)\n        + o8(flags)\n    )\n\n    if id_section:\n        fp.write(id_section)\n\n    if colormaptype:\n        fp.write(im.im.getpalette(\"RGB\", \"BGR\"))\n\n    if rle:\n        ImageFile._save(\n            im, fp, [(\"tga_rle\", (0, 0) + im.size, 0, (rawmode, orientation))]\n        )\n    else:\n        ImageFile._save(\n            im, fp, [(\"raw\", (0, 0) + im.size, 0, (rawmode, 0, orientation))]\n        )\n\n    # write targa version 2 footer\n    fp.write(b\"\\000\" * 8 + b\"TRUEVISION-XFILE.\" + b\"\\000\")\n\n\n#\n# --------------------------------------------------------------------\n# Registry\n\n\nImage.register_open(TgaImageFile.format, TgaImageFile)\nImage.register_save(TgaImageFile.format, _save)\n\nImage.register_extensions(TgaImageFile.format, [\".tga\", \".icb\", \".vda\", \".vst\"])\n\nImage.register_mime(TgaImageFile.format, \"image/x-tga\")\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:** Saving TGA Images with Small Palettes Raises "Buffer is Not Large Enough" Error

**Description:**
When attempting to save a TGA image with a small palette, a `ValueError` is raised stating that the buffer is not large enough. This issue occurs because the palette size is incorrectly fixed, preventing the saving of images with palettes smaller than 256 colors.

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

im = Image.new("P", (1, 1))
colors = [0, 0, 0]  # Small palette with only one color
im.putpalette(colors)

im.save("temp.tga")
```

**Expected Behavior:**
The image should be saved successfully using the provided small palette without any errors.

**Actual Behavior:**
A `ValueError` is raised with the message "buffer is not large enough," preventing the image from being saved.

[/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/TgaImagePlugin.py
#
# The Python Imaging Library.
# $Id$
#
# TGA file handling
#
# History:
# 95-09-01 fl   created (reads 24-bit files only)
# 97-01-04 fl   support more TGA versions, including compressed images
# 98-07-04 fl   fixed orientation and alpha layer bugs
# 98-09-11 fl   fixed orientation for runlength decoder
#
# Copyright (c) Secret Labs AB 1997-98.
# Copyright (c) Fredrik Lundh 1995-97.
#
# See the README file for information on usage and redistribution.
#


import warnings

from . import Image, ImageFile, ImagePalette
from ._binary import i16le as i16
from ._binary import o8
from ._binary import o16le as o16

#
# --------------------------------------------------------------------
# Read RGA file


MODES = {
    # map imagetype/depth to rawmode
    (1, 8): "P",
    (3, 1): "1",
    (3, 8): "L",
    (3, 16): "LA",
    (2, 16): "BGR;5",
    (2, 24): "BGR",
    (2, 32): "BGRA",
}


##
# Image plugin for Targa files.


class TgaImageFile(ImageFile.ImageFile):

    format = "TGA"
    format_description = "Targa"

    def _open(self):

        # process header
        s = self.fp.read(18)

        id_len = s[0]

        colormaptype = s[1]
        imagetype = s[2]

        depth = s[16]

        flags = s[17]

        self._size = i16(s, 12), i16(s, 14)

        # validate header fields
        if (
            colormaptype not in (0, 1)
            or self.size[0] <= 0
            or self.size[1] <= 0
            or depth not in (1, 8, 16, 24, 32)
        ):
            raise SyntaxError("not a TGA file")

        # image mode
        if imagetype in (3, 11):
            self.mode = "L"
            if depth == 1:
                self.mode = "1"  # ???
            elif depth == 16:
                self.mode = "LA"
        elif imagetype in (1, 9):
            self.mode = "P"
        elif imagetype in (2, 10):
            self.mode = "RGB"
            if depth == 32:
                self.mode = "RGBA"
        else:
            raise SyntaxError("unknown TGA mode")

        # orientation
        orientation = flags & 0x30
        self._flip_horizontally = orientation in [0x10, 0x30]
        if orientation in [0x20, 0x30]:
            orientation = 1
        elif orientation in [0, 0x10]:
            orientation = -1
        else:
            raise SyntaxError("unknown TGA orientation")

        self.info["orientation"] = orientation

        if imagetype & 8:
            self.info["compression"] = "tga_rle"

        if id_len:
            self.info["id_section"] = self.fp.read(id_len)

        if colormaptype:
            # read palette
            start, size, mapdepth = i16(s, 3), i16(s, 5), s[7]
            if mapdepth == 16:
                self.palette = ImagePalette.raw(
                    "BGR;15", b"\0" * 2 * start + self.fp.read(2 * size)
                )
            elif mapdepth == 24:
                self.palette = ImagePalette.raw(
                    "BGR", b"\0" * 3 * start + self.fp.read(3 * size)
                )
            elif mapdepth == 32:
                self.palette = ImagePalette.raw(
                    "BGRA", b"\0" * 4 * start + self.fp.read(4 * size)
                )

        # setup tile descriptor
        try:
            rawmode = MODES[(imagetype & 7, depth)]
            if imagetype & 8:
                # compressed
                self.tile = [
                    (
                        "tga_rle",
                        (0, 0) + self.size,
                        self.fp.tell(),
                        (rawmode, orientation, depth),
                    )
                ]
            else:
                self.tile = [
                    (
                        "raw",
                        (0, 0) + self.size,
                        self.fp.tell(),
                        (rawmode, 0, orientation),
                    )
                ]
        except KeyError:
            pass  # cannot decode

    def load_end(self):
        if self._flip_horizontally:
            self.im = self.im.transpose(Image.Transpose.FLIP_LEFT_RIGHT)


#
# --------------------------------------------------------------------
# Write TGA file


SAVE = {
    "1": ("1", 1, 0, 3),
    "L": ("L", 8, 0, 3),
    "LA": ("LA", 16, 0, 3),
    "P": ("P", 8, 1, 1),
    "RGB": ("BGR", 24, 0, 2),
    "RGBA": ("BGRA", 32, 0, 2),
}


def _save(im, fp, filename):

    try:
        rawmode, bits, colormaptype, imagetype = SAVE[im.mode]
    except KeyError as e:
        raise OSError(f"cannot write mode {im.mode} as TGA") from e

    if "rle" in im.encoderinfo:
        rle = im.encoderinfo["rle"]
    else:
        compression = im.encoderinfo.get("compression", im.info.get("compression"))
        rle = compression == "tga_rle"
    if rle:
        imagetype += 8

    id_section = im.encoderinfo.get("id_section", im.info.get("id_section", ""))
    id_len = len(id_section)
    if id_len > 255:
        id_len = 255
        id_section = id_section[:255]
        warnings.warn("id_section has been trimmed to 255 characters")

    if colormaptype:
        colormapfirst, colormaplength, colormapentry = 0, 256, 24
    else:
        colormapfirst, colormaplength, colormapentry = 0, 0, 0

    if im.mode in ("LA", "RGBA"):
        flags = 8
    else:
        flags = 0

    orientation = im.encoderinfo.get("orientation", im.info.get("orientation", -1))
    if orientation > 0:
        flags = flags | 0x20

    fp.write(
        o8(id_len)
        + o8(colormaptype)
        + o8(imagetype)
        + o16(colormapfirst)
        + o16(colormaplength)
        + o8(colormapentry)
        + o16(0)
        + o16(0)
        + o16(im.size[0])
        + o16(im.size[1])
        + o8(bits)
        + o8(flags)
    )

    if id_section:
        fp.write(id_section)

    if colormaptype:
        fp.write(im.im.getpalette("RGB", "BGR"))

    if rle:
        ImageFile._save(
            im, fp, [("tga_rle", (0, 0) + im.size, 0, (rawmode, orientation))]
        )
    else:
        ImageFile._save(
            im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, 0, orientation))]
        )

    # write targa version 2 footer
    fp.write(b"\000" * 8 + b"TRUEVISION-XFILE." + b"\000")


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


Image.register_open(TgaImageFile.format, TgaImageFile)
Image.register_save(TgaImageFile.format, _save)

Image.register_extensions(TgaImageFile.format, [".tga", ".icb", ".vda", ".vst"])

Image.register_mime(TgaImageFile.format, "image/x-tga")

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