Improve test in _get_optimize()

Palette can be optimized if number of colors can be reduced by half or more.
This commit is contained in:
Ray Gardner 2022-06-18 18:07:58 -06:00
parent 765d66c069
commit 128ed189e5
2 changed files with 21 additions and 1 deletions

View File

@ -180,6 +180,21 @@ def test_optimize_full_l():
assert im.mode == "L"
def test_optimize_if_palette_can_be_reduced_by_half():
with Image.open("Tests/images/test.colors.gif") as im:
# Reduce because original is too big for _get_optimize()
im = im.resize((591, 443))
imrgb = im.convert("RGB")
out = BytesIO()
imrgb.save(out, "GIF", optimize=False)
with Image.open(out) as reloaded:
assert len(reloaded.palette.palette) // 3 == 256
out = BytesIO()
imrgb.save(out, "GIF", optimize=True)
with Image.open(out) as reloaded:
assert len(reloaded.palette.palette) // 3 == 8
def test_roundtrip(tmp_path):
out = str(tmp_path / "temp.gif")
im = hopper()

View File

@ -824,9 +824,14 @@ def _get_optimize(im, info):
if count:
used_palette_colors.append(i)
num_palette_colors = len(im.palette.palette) // 4 if im.palette.mode == 'RGBA' else len(im.palette.palette) // 3
# Round up to power of 2 but at least 4
num_palette_colors = max(4, 1 << (num_palette_colors - 1).bit_length())
if optimise or (
len(used_palette_colors) <= 128
and max(used_palette_colors) > len(used_palette_colors)
and max(used_palette_colors) >= len(used_palette_colors)
or len(used_palette_colors) <= num_palette_colors // 2
):
return used_palette_colors