Corrected file length in header

This commit is contained in:
Andrew Murray 2021-11-20 14:17:42 +11:00
parent e1eefe4486
commit 838c8efa25
2 changed files with 16 additions and 5 deletions

View File

@ -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")

View File

@ -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"):