Merge pull request #1 from radarhere/write-jpeg-com

Support saving JPEG comments
This commit is contained in:
Sam Mason 2022-12-03 12:28:05 +00:00 committed by GitHub
commit e71f7c1083
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 20 additions and 14 deletions

View File

@ -86,18 +86,26 @@ class TestFileJpeg:
assert len(im.applist) == 2 assert len(im.applist) == 2
assert im.info["comment"] == b"File written by Adobe Photoshop\xa8 4.0\x00" assert im.info["comment"] == b"File written by Adobe Photoshop\xa8 4.0\x00"
assert im.app["COM"] == im.info["comment"]
def test_com_write(self): def test_comment_write(self):
dummy_text = "this is a test comment"
with Image.open(TEST_FILE) as im: with Image.open(TEST_FILE) as im:
with BytesIO() as buf: assert im.info["comment"] == b"File written by Adobe Photoshop\xa8 4.0\x00"
im.save(buf, format="JPEG")
with Image.open(buf) as im2: # Test that existing comment is saved by default
assert im.app["COM"] == im2.app["COM"] out = BytesIO()
with BytesIO() as buf: im.save(out, format="JPEG")
im.save(buf, format="JPEG", comment=dummy_text) with Image.open(out) as reloaded:
with Image.open(buf) as im2: assert im.info["comment"] == reloaded.info["comment"]
assert im2.app["COM"].decode() == dummy_text
# Test that a comment argument overrides the default comment
for comment in ("Test comment text", b"Text comment text"):
out = BytesIO()
im.save(out, format="JPEG", comment=comment)
with Image.open(out) as reloaded:
if not isinstance(comment, bytes):
comment = comment.encode()
assert reloaded.info["comment"] == comment
def test_cmyk(self): def test_cmyk(self):
# Test CMYK handling. Thanks to Tim and Charlie for test data, # Test CMYK handling. Thanks to Tim and Charlie for test data,

View File

@ -714,9 +714,7 @@ def _save(im, fp, filename):
extra = info.get("extra", b"") extra = info.get("extra", b"")
comment = info.get("comment") comment = info.get("comment", im.info.get("comment"))
if comment is None and isinstance(im, JpegImageFile):
comment = im.app.get("COM")
if comment: if comment:
if isinstance(comment, str): if isinstance(comment, str):
comment = comment.encode() comment = comment.encode()
@ -734,7 +732,7 @@ def _save(im, fp, filename):
icc_profile = icc_profile[MAX_DATA_BYTES_IN_MARKER:] icc_profile = icc_profile[MAX_DATA_BYTES_IN_MARKER:]
i = 1 i = 1
for marker in markers: for marker in markers:
size = struct.pack(">H", 2 + ICC_OVERHEAD_LEN + len(marker)) size = o16(2 + ICC_OVERHEAD_LEN + len(marker))
extra += ( extra += (
b"\xFF\xE2" b"\xFF\xE2"
+ size + size