diff --git a/Tests/test_file_icns.py b/Tests/test_file_icns.py index 47de38d06..3afbbeaac 100644 --- a/Tests/test_file_icns.py +++ b/Tests/test_file_icns.py @@ -1,8 +1,9 @@ import io +import os import pytest -from PIL import IcnsImagePlugin, Image, features +from PIL import IcnsImagePlugin, Image, _binary, features from .helper import assert_image_equal, assert_image_similar_tofile @@ -38,6 +39,11 @@ def test_save(tmp_path): assert reread.size == (1024, 1024) assert reread.format == "ICNS" + file_length = os.path.getsize(temp_file) + with open(temp_file, "rb") as fp: + fp.seek(4) + assert _binary.i32be(fp.read(4)) == file_length + def test_save_append_images(tmp_path): temp_file = str(tmp_path / "temp.icns") diff --git a/src/PIL/IcnsImagePlugin.py b/src/PIL/IcnsImagePlugin.py index d30eaf90f..6412d1cfb 100644 --- a/src/PIL/IcnsImagePlugin.py +++ b/src/PIL/IcnsImagePlugin.py @@ -337,23 +337,28 @@ def _save(im, fp, filename): entries = [] for type, size in sizes.items(): stream = size_streams[size] - entries.append({"type": type, "size": len(stream), "stream": stream}) + entries.append( + {"type": type, "size": HEADERSIZE + len(stream), "stream": stream} + ) # Header fp.write(MAGIC) - fp.write(struct.pack(">i", sum(entry["size"] for entry in entries))) + file_length = HEADERSIZE # Header + file_length += HEADERSIZE + 8 * len(entries) # TOC + file_length += sum(entry["size"] for entry in entries) + fp.write(struct.pack(">i", file_length)) # TOC fp.write(b"TOC ") fp.write(struct.pack(">i", HEADERSIZE + len(entries) * HEADERSIZE)) for entry in entries: fp.write(entry["type"]) - fp.write(struct.pack(">i", HEADERSIZE + entry["size"])) + fp.write(struct.pack(">i", entry["size"])) # Data for entry in entries: fp.write(entry["type"]) - fp.write(struct.pack(">i", HEADERSIZE + entry["size"])) + fp.write(struct.pack(">i", entry["size"])) fp.write(entry["stream"]) if hasattr(fp, "flush"):