Version 0 of Writing JPEG comments

Updated 2003-12-20 01:58:17

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
        set pos [tell $fh]
        if {$type == "\xC0" } { set sof $pos; break }
        if {$type == "\xFE"} { set com $pos; break }
        seek $fh [expr {$pos + $len - 2}] start
    }

    set clen [binary format S [expr {[string length $comment] + 2}]]
    if {[info exists com]} {
    puts 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 {
        return -code error "no image found"
    }
 }

--AF 19-12-03


See Also jpeg, Reading JPEG comments


Category Graphics