From eada3cbd7fb9963ee90673fb7b5270124a0d5f4b Mon Sep 17 00:00:00 2001
From: Andrew Murray <3112309+radarhere@users.noreply.github.com>
Date: Tue, 23 Jun 2026 09:46:33 +1000
Subject: [PATCH] Prevent saving 1 mode images as TGA with run-length encoding
 (#9709)

---
 Tests/test_file_tga.py    | 12 +++++++++++-
 src/PIL/TgaImagePlugin.py |  4 ++++
 2 files changed, 15 insertions(+), 1 deletion(-)

Index: pillow-11.3.0/Tests/test_file_tga.py
===================================================================
--- pillow-11.3.0.orig/Tests/test_file_tga.py
+++ pillow-11.3.0/Tests/test_file_tga.py
@@ -161,10 +161,20 @@ def test_save_wrong_mode(tmp_path: Path)
     im = hopper("PA")
     out = tmp_path / "temp.tga"
 
-    with pytest.raises(OSError):
+    with pytest.raises(OSError, match="cannot write mode PA as TGA"):
         im.save(out)
 
 
+def test_save_1_mode_rle(tmp_path: Path) -> None:
+    im = Image.new("1", (1, 1))
+    out = tmp_path / "temp.tga"
+
+    with pytest.raises(
+        OSError, match="cannot write mode 1 as TGA with run-length encoding"
+    ):
+        im.save(out, compression="tga_rle")
+
+
 def test_save_mapdepth() -> None:
     # This image has been manually hexedited from 200x32_p_bl_raw.tga
     # to include an origin
Index: pillow-11.3.0/src/PIL/TgaImagePlugin.py
===================================================================
--- pillow-11.3.0.orig/src/PIL/TgaImagePlugin.py
+++ pillow-11.3.0/src/PIL/TgaImagePlugin.py
@@ -189,6 +189,10 @@ def _save(im: Image.Image, fp: IO[bytes]
         compression = im.encoderinfo.get("compression", im.info.get("compression"))
         rle = compression == "tga_rle"
     if rle:
+        if im.mode == "1":
+            msg = f"cannot write mode {im.mode} as TGA with run-length encoding"
+            raise OSError(msg)
+
         imagetype += 8
 
     id_section = im.encoderinfo.get("id_section", im.info.get("id_section", ""))
