Writing JPEG comments

For a possibly more current version of this code see the tcllib jpeg module

 proc write_jpg_comment {file comment} {
    set fh [open $file r+]
    fconfigure $fh -encoding binary -translation binary -eofchar {}
    if {[read $fh 2] != "\xFF\xD8"} { close $fh; return -code error "not a jpeg file" }

    while {[read $fh 1] == "\xFF"} {
        binary scan [read $fh 3] aS type len
        if {$type == "\xC0"} { set sof [tell $fh]; break }
        if {$type == "\xFE"} { set com [tell $fh]; break }
        seek $fh [expr {$len - 2}] current

    set clen [binary format S [expr {[string length $comment] + 2}]]
    if {[info exists com]} {
        seek $fh 0 start
        set data1 [read $fh [expr {$com - 2}]]
        binary scan [read $fh 2] S len
        seek $fh [expr {$len - 2}] current
        set data2 [read $fh]
        close $fh
        set fh [open $file w]
        puts -nonewline $fh $data1$clen$comment$data2
    } elseif {[info exists sof]} {
        seek $fh [expr {$sof - 4}] start
        set data [read $fh]
        seek $fh [expr {$sof - 4}] start
        puts -nonewline $fh "\xFF\xFE$clen$comment$data"
    } else {
        close $fh
        return -code error "no image found"
    close $fh

--AF 19-12-03 I think jfif supports more than one comment block but it's not really used since the comments are just unformatted text. This proc replaces the first comment found, otherwise writes a new comment block just before the image data.

See also jpeg, Reading JPEG comments