diff --git a/src/PIL/GifImagePlugin.py b/src/PIL/GifImagePlugin.py
index b35420328..bbf1c603f 100644
--- a/src/PIL/GifImagePlugin.py
+++ b/src/PIL/GifImagePlugin.py
@@ -426,6 +426,7 @@ def _write_multiple_frames(im, fp, palette):
 
     im_frames = []
     frame_count = 0
+    background_im = None
     for imSequence in itertools.chain([im], im.encoderinfo.get("append_images", [])):
         for im_frame in ImageSequence.Iterator(imSequence):
             # a copy is required here since seek can still mutate the image
@@ -445,11 +446,22 @@ def _write_multiple_frames(im, fp, palette):
             if im_frames:
                 # delta frame
                 previous = im_frames[-1]
-                if _get_palette_bytes(im_frame) == _get_palette_bytes(previous["im"]):
-                    delta = ImageChops.subtract_modulo(im_frame, previous["im"])
+                if encoderinfo.get("disposal") == 2:
+                    if background_im is None:
+                        background = _get_background(
+                            im,
+                            im.encoderinfo.get("background", im.info.get("background")),
+                        )
+                        background_im = Image.new("P", im_frame.size, background)
+                        background_im.putpalette(im_frames[0]["im"].palette)
+                    base_im = background_im
+                else:
+                    base_im = previous["im"]
+                if _get_palette_bytes(im_frame) == _get_palette_bytes(base_im):
+                    delta = ImageChops.subtract_modulo(im_frame, base_im)
                 else:
                     delta = ImageChops.subtract_modulo(
-                        im_frame.convert("RGB"), previous["im"].convert("RGB")
+                        im_frame.convert("RGB"), base_im.convert("RGB")
                     )
                 bbox = delta.getbbox()
                 if not bbox:
@@ -683,10 +695,12 @@ def _get_color_table_size(palette_bytes):
     # calculate the palette size for the header
     import math
 
-    color_table_size = int(math.ceil(math.log(len(palette_bytes) // 3, 2))) - 1
-    if color_table_size < 0:
-        color_table_size = 0
-    return color_table_size
+    if not palette_bytes:
+        return 0
+    elif len(palette_bytes) < 9:
+        return 1
+    else:
+        return int(math.ceil(math.log(len(palette_bytes) // 3, 2))) - 1
 
 
 def _get_header_palette(palette_bytes):
@@ -717,6 +731,18 @@ def _get_palette_bytes(im):
     return im.palette.palette
 
 
+def _get_background(im, infoBackground):
+    background = 0
+    if infoBackground:
+        background = infoBackground
+        if isinstance(background, tuple):
+            # WebPImagePlugin stores an RGBA value in info["background"]
+            # So it must be converted to the same format as GifImagePlugin's
+            # info["background"] - a global color table index
+            background = im.palette.getcolor(background)
+    return background
+
+
 def _get_global_header(im, info):
     """Return a list of strings representing a GIF header"""
 
@@ -736,14 +762,7 @@ def _get_global_header(im, info):
         if im.info.get("version") == b"89a":
             version = b"89a"
 
-    background = 0
-    if "background" in info:
-        background = info["background"]
-        if isinstance(background, tuple):
-            # WebPImagePlugin stores an RGBA value in info["background"]
-            # So it must be converted to the same format as GifImagePlugin's
-            # info["background"] - a global color table index
-            background = im.palette.getcolor(background)
+    background = _get_background(im, info.get("background"))
 
     palette_bytes = _get_palette_bytes(im)
     color_table_size = _get_color_table_size(palette_bytes)

Animated, transparent GIFs not calculating diff correctly
function `_write_multiple_frames` in `GifImagePlugin.py` has an error on line 445 ([line 445 in present repo](https://github.com/python-pillow/Pillow/blob/daa8b5133923561d2c6d4d1f7b2c9d9aa233007e/src/PIL/GifImagePlugin.py#L445), line 443 in released version 5.4.1).
Specifically, when the disposal_method is set to '2', it should calculate the diff against the background color, but currently it is calculating the diff against the previous frame
`previous = im_frames[-1]`,
and this produces substantial artifacts in the rendering whenever there are still portions of the image in adjacent frames.
diff --git a/Tests/test_file_gif.py b/Tests/test_file_gif.py
index 69a1ee5be..45409cbc6 100644
--- a/Tests/test_file_gif.py
+++ b/Tests/test_file_gif.py
@@ -1,6 +1,6 @@
 from .helper import unittest, PillowTestCase, hopper, netpbm_available
 
-from PIL import Image, ImagePalette, GifImagePlugin
+from PIL import Image, ImagePalette, GifImagePlugin, ImageDraw
 
 from io import BytesIO
 
@@ -59,7 +59,7 @@ class TestFileGif(PillowTestCase):
             return len(test_file.getvalue())
 
         self.assertEqual(test_grayscale(0), 800)
-        self.assertEqual(test_grayscale(1), 38)
+        self.assertEqual(test_grayscale(1), 44)
         self.assertEqual(test_bilevel(0), 800)
         self.assertEqual(test_bilevel(1), 800)
 
@@ -318,6 +318,103 @@ class TestFileGif(PillowTestCase):
             img.seek(img.tell() + 1)
             self.assertEqual(img.disposal_method, i + 1)
 
+    def test_dispose2_palette(self):
+        out = self.tempfile("temp.gif")
+
+        # 4 backgrounds: White, Grey, Black, Red
+        circles = [(255, 255, 255), (153, 153, 153), (0, 0, 0), (255, 0, 0)]
+
+        im_list = []
+        for circle in circles:
+            img = Image.new("RGB", (100, 100), (255, 0, 0))
+
+            # Red circle in center of each frame
+            d = ImageDraw.Draw(img)
+            d.ellipse([(40, 40), (60, 60)], fill=circle)
+
+            im_list.append(img)
+
+        im_list[0].save(out, save_all=True, append_images=im_list[1:], disposal=2)
+
+        img = Image.open(out)
+
+        for i, circle in enumerate(circles):
+            img.seek(i)
+            rgb_img = img.convert("RGB")
+
+            # Check top left pixel matches background
+            self.assertEqual(rgb_img.getpixel((0, 0)), (255, 0, 0))
+
+            # Center remains red every frame
+            self.assertEqual(rgb_img.getpixel((50, 50)), circle)
+
+    def test_dispose2_diff(self):
+        out = self.tempfile("temp.gif")
+
+        # 4 frames: red/blue, red/red, blue/blue, red/blue
+        circles = [
+            ((255, 0, 0, 255), (0, 0, 255, 255)),
+            ((255, 0, 0, 255), (255, 0, 0, 255)),
+            ((0, 0, 255, 255), (0, 0, 255, 255)),
+            ((255, 0, 0, 255), (0, 0, 255, 255)),
+        ]
+
+        im_list = []
+        for i in range(len(circles)):
+            # Transparent BG
+            img = Image.new("RGBA", (100, 100), (255, 255, 255, 0))
+
+            # Two circles per frame
+            d = ImageDraw.Draw(img)
+            d.ellipse([(0, 30), (40, 70)], fill=circles[i][0])
+            d.ellipse([(60, 30), (100, 70)], fill=circles[i][1])
+
+            im_list.append(img)
+
+        im_list[0].save(
+            out, save_all=True, append_images=im_list[1:], disposal=2, transparency=0
+        )
+
+        img = Image.open(out)
+
+        for i, colours in enumerate(circles):
+            img.seek(i)
+            rgb_img = img.convert("RGBA")
+
+            # Check left circle is correct colour
+            self.assertEqual(rgb_img.getpixel((20, 50)), colours[0])
+
+            # Check right circle is correct colour
+            self.assertEqual(rgb_img.getpixel((80, 50)), colours[1])
+
+            # Check BG is correct colour
+            self.assertEqual(rgb_img.getpixel((1, 1)), (255, 255, 255, 0))
+
+    def test_dispose2_background(self):
+        out = self.tempfile("temp.gif")
+
+        im_list = []
+
+        im = Image.new("P", (100, 100))
+        d = ImageDraw.Draw(im)
+        d.rectangle([(50, 0), (100, 100)], fill="#f00")
+        d.rectangle([(0, 0), (50, 100)], fill="#0f0")
+        im_list.append(im)
+
+        im = Image.new("P", (100, 100))
+        d = ImageDraw.Draw(im)
+        d.rectangle([(0, 0), (100, 50)], fill="#f00")
+        d.rectangle([(0, 50), (100, 100)], fill="#0f0")
+        im_list.append(im)
+
+        im_list[0].save(
+            out, save_all=True, append_images=im_list[1:], disposal=[0, 2], background=1
+        )
+
+        im = Image.open(out)
+        im.seek(1)
+        self.assertEqual(im.getpixel((0, 0)), 0)
+
     def test_iss634(self):
         img = Image.open("Tests/images/iss634.gif")
         # seek to the second frame

pip install -e .[dev]
parse_log_pytest
requirements.txt
apt-get update apt-get install -y gcc libjpeg-dev zlib1g-dev libtiff5-dev libfreetype6-dev liblcms2-dev libwebp-dev tcl8.6-dev tk8.6-dev libharfbuzz-dev libfribidi-dev libxcb1-dev
3.9
requirements.txt
pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning
alabaster==0.7.16
babel==2.17.0
black==25.1.0
blessed==1.20.0
build==1.2.2.post1
certifi==2025.1.31
charset-normalizer==3.4.1
check-manifest==0.50
click==8.1.8
cov-core==1.15.0
coverage==7.8.0
coveralls==4.0.1
docopt==0.6.2
docutils==0.21.2
exceptiongroup==1.2.2
idna==3.10
imagesize==1.4.1
importlib_metadata==8.6.1
iniconfig==2.1.0
jarn.viewdoc==2.7
Jinja2==3.1.6
MarkupSafe==3.0.2
mypy-extensions==1.0.0
olefile==0.47
packaging==24.2
pathspec==0.12.1
-e git+https://github.com/python-pillow/Pillow.git@af0d90a0541fac1e9e3cddb042e2de230876bad8#egg=Pillow
platformdirs==4.3.7
pluggy==1.5.0
pycodestyle==2.13.0
pyflakes==3.3.1
Pygments==2.19.1
pyproject_hooks==1.2.0
pyroma==4.2
pytest==8.3.5
pytest-cov==6.0.0
pytz==2025.2
requests==2.32.3
six==1.17.0
snowballstemmer==2.2.0
Sphinx==7.4.7
sphinx-rtd-theme==3.0.2
sphinxcontrib-applehelp==2.0.0
sphinxcontrib-devhelp==2.0.0
sphinxcontrib-htmlhelp==2.1.0
sphinxcontrib-jquery==4.1
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==2.0.0
sphinxcontrib-serializinghtml==2.0.0
tomli==2.2.1
trove-classifiers==2025.3.19.19
typing_extensions==4.13.0
urllib3==2.3.0
wcwidth==0.2.13
zipp==3.21.0

name: Pillow
channels:
  - defaults
  - https://repo.anaconda.com/pkgs/main
  - https://repo.anaconda.com/pkgs/r
  - conda-forge
dependencies:
  - _libgcc_mutex=0.1=main
  - _openmp_mutex=5.1=1_gnu
  - ca-certificates=2025.2.25=h06a4308_0
  - ld_impl_linux-64=2.40=h12ee557_0
  - libffi=3.4.4=h6a678d5_1
  - libgcc-ng=11.2.0=h1234567_1
  - libgomp=11.2.0=h1234567_1
  - libstdcxx-ng=11.2.0=h1234567_1
  - ncurses=6.4=h6a678d5_0
  - openssl=3.0.16=h5eee18b_0
  - pip=25.0=py39h06a4308_0
  - python=3.9.21=he870216_1
  - readline=8.2=h5eee18b_0
  - setuptools=75.8.0=py39h06a4308_0
  - sqlite=3.45.3=h5eee18b_0
  - tk=8.6.14=h39e8969_0
  - tzdata=2025a=h04d1e81_0
  - wheel=0.45.1=py39h06a4308_0
  - xz=5.6.4=h5eee18b_1
  - zlib=1.2.13=h5eee18b_1
  - pip:
      - alabaster==0.7.16
      - babel==2.17.0
      - black==25.1.0
      - blessed==1.20.0
      - build==1.2.2.post1
      - certifi==2025.1.31
      - charset-normalizer==3.4.1
      - check-manifest==0.50
      - click==8.1.8
      - cov-core==1.15.0
      - coverage==7.8.0
      - coveralls==4.0.1
      - docopt==0.6.2
      - docutils==0.21.2
      - exceptiongroup==1.2.2
      - idna==3.10
      - imagesize==1.4.1
      - importlib-metadata==8.6.1
      - iniconfig==2.1.0
      - jarn-viewdoc==2.7
      - jinja2==3.1.6
      - markupsafe==3.0.2
      - mypy-extensions==1.0.0
      - olefile==0.47
      - packaging==24.2
      - pathspec==0.12.1
      - platformdirs==4.3.7
      - pluggy==1.5.0
      - pycodestyle==2.13.0
      - pyflakes==3.3.1
      - pygments==2.19.1
      - pyproject-hooks==1.2.0
      - pyroma==4.2
      - pytest==8.3.5
      - pytest-cov==6.0.0
      - pytz==2025.2
      - requests==2.32.3
      - six==1.17.0
      - snowballstemmer==2.2.0
      - sphinx==7.4.7
      - sphinx-rtd-theme==3.0.2
      - sphinxcontrib-applehelp==2.0.0
      - sphinxcontrib-devhelp==2.0.0
      - sphinxcontrib-htmlhelp==2.1.0
      - sphinxcontrib-jquery==4.1
      - sphinxcontrib-jsmath==1.0.1
      - sphinxcontrib-qthelp==2.0.0
      - sphinxcontrib-serializinghtml==2.0.0
      - tomli==2.2.1
      - trove-classifiers==2025.3.19.19
      - typing-extensions==4.13.0
      - urllib3==2.3.0
      - wcwidth==0.2.13
      - zipp==3.21.0
prefix: /opt/conda/envs/Pillow

Tests/test_file_gif.py::TestFileGif::test_dispose2_diff Tests/test_file_gif.py::TestFileGif::test_dispose2_palette Tests/test_file_gif.py::TestFileGif::test_optimize
Tests/test_file_gif.py::TestFileGif::test_append_images Tests/test_file_gif.py::TestFileGif::test_background Tests/test_file_gif.py::TestFileGif::test_bbox Tests/test_file_gif.py::TestFileGif::test_comment Tests/test_file_gif.py::TestFileGif::test_comment_over_255 Tests/test_file_gif.py::TestFileGif::test_dispose2_background Tests/test_file_gif.py::TestFileGif::test_dispose_background Tests/test_file_gif.py::TestFileGif::test_dispose_none Tests/test_file_gif.py::TestFileGif::test_dispose_previous Tests/test_file_gif.py::TestFileGif::test_duration Tests/test_file_gif.py::TestFileGif::test_eoferror Tests/test_file_gif.py::TestFileGif::test_extents Tests/test_file_gif.py::TestFileGif::test_getdata Tests/test_file_gif.py::TestFileGif::test_headers_saving_for_animated_gifs Tests/test_file_gif.py::TestFileGif::test_identical_frames Tests/test_file_gif.py::TestFileGif::test_invalid_file Tests/test_file_gif.py::TestFileGif::test_iss634 Tests/test_file_gif.py::TestFileGif::test_lzw_bits Tests/test_file_gif.py::TestFileGif::test_multiple_duration Tests/test_file_gif.py::TestFileGif::test_n_frames Tests/test_file_gif.py::TestFileGif::test_number_of_loops Tests/test_file_gif.py::TestFileGif::test_optimize_correctness Tests/test_file_gif.py::TestFileGif::test_optimize_full_l Tests/test_file_gif.py::TestFileGif::test_palette_434 Tests/test_file_gif.py::TestFileGif::test_palette_handling Tests/test_file_gif.py::TestFileGif::test_palette_save_ImagePalette Tests/test_file_gif.py::TestFileGif::test_palette_save_L Tests/test_file_gif.py::TestFileGif::test_palette_save_P Tests/test_file_gif.py::TestFileGif::test_rgb_transparency Tests/test_file_gif.py::TestFileGif::test_roundtrip Tests/test_file_gif.py::TestFileGif::test_roundtrip2 Tests/test_file_gif.py::TestFileGif::test_roundtrip_save_all Tests/test_file_gif.py::TestFileGif::test_sanity Tests/test_file_gif.py::TestFileGif::test_save_I Tests/test_file_gif.py::TestFileGif::test_save_dispose Tests/test_file_gif.py::TestFileGif::test_seek Tests/test_file_gif.py::TestFileGif::test_seek_info Tests/test_file_gif.py::TestFileGif::test_seek_rewind Tests/test_file_gif.py::TestFileGif::test_transparent_optimize Tests/test_file_gif.py::TestFileGif::test_unclosed_file Tests/test_file_gif.py::TestFileGif::test_version Tests/test_file_gif.py::TestFileGif::test_zero_comment_subblocks
src/PIL/GifImagePlugin.py
src/PIL/GifImagePlugin.py