3

I want to write a python program that adds a comment to a jpeg file. I've read that a comment in a jpeg file is signaled by the marker 0xfffe. Thus, can I just open the file and append this marker with whatever comment I want following it? My code looks something like this:

file = open("someimage.jpg", "a+b")
file.write("\xff\xfeCOMMENT")
file.close()

Does it matter if my comment is after the end of file marker (0xffd9)? Thanks!

osdev0
  • 280
  • 4
  • 7

2 Answers2

2

The accepted answer uses EXIF fields. If a standard JPEG comment is needed, you'll need to insert the payload length:

Two bytes giving the-length-of-the-comment-in-bytes-plus-2 as a big-endian (unsigned short) integer must be inserted between the FF FE bytes and the comment.

For example, the sequence of bytes corresponding to a comment Hello is FF FE00 0748 65 6C 6C 6F because the length of the payload (unsigned short + comment) is 7 bytes. If an optional C-style null-terminator is wanted, it's FF FE00 0848 65 6C 6C 6F 00.

The comment segment should strictly be before the end-of-file marker (FF D9) though some image viewers may understand extra data after the marker.

For details, see How do text comments in JPG files work?.

Gnubie
  • 2,587
  • 4
  • 25
  • 38
2

This will work (it will append text beyond the part needed to store the image).

A more sophisticated approach would read the JPG file format and add a comment in EXIF fields. See this StackOverflow discussion: Exif manipulation library for python

See pyexiv for python bindings to exiv2, a tool for reading and writing image metadata.

Community
  • 1
  • 1
Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485