Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support saving JPEG comments #1

Merged
merged 3 commits into from Dec 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
28 changes: 18 additions & 10 deletions Tests/test_file_jpeg.py
Expand Up @@ -86,18 +86,26 @@ def test_app(self):
assert len(im.applist) == 2

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):
dummy_text = "this is a test comment"
def test_comment_write(self):
with Image.open(TEST_FILE) as im:
with BytesIO() as buf:
im.save(buf, format="JPEG")
with Image.open(buf) as im2:
assert im.app["COM"] == im2.app["COM"]
with BytesIO() as buf:
im.save(buf, format="JPEG", comment=dummy_text)
with Image.open(buf) as im2:
assert im2.app["COM"].decode() == dummy_text
assert im.info["comment"] == b"File written by Adobe Photoshop\xa8 4.0\x00"

# Test that existing comment is saved by default
out = BytesIO()
im.save(out, format="JPEG")
with Image.open(out) as reloaded:
assert im.info["comment"] == reloaded.info["comment"]

# 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):
# Test CMYK handling. Thanks to Tim and Charlie for test data,
Expand Down
6 changes: 2 additions & 4 deletions src/PIL/JpegImagePlugin.py
Expand Up @@ -714,9 +714,7 @@ def validate_qtables(qtables):

extra = info.get("extra", b"")

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