Updated 2012-08-01 14:10:17 by AMG

This procedure inserts a comment into a PNG file. This functionality is also present in the tcllib png module.
 proc write_png_comment {file keyword text} {
    set fh [open $file r+]
    fconfigure $fh -encoding binary -translation binary -eofchar {}
    if {[read $fh 8] != "\x89PNG\r\n\x1a\n"} { close $fh; return }

    while {[set r [read $fh 8]] != ""} {
        binary scan $r Ia4 len type
        if {$type ==  "IDAT"} {
            seek $fh -8 current
            set pos [tell $fh]
            set data [read $fh]
            seek $fh $pos start
            set size [binary format I [string length "${keyword}\x00${text}"]]
            puts -nonewline $fh "${size}tEXt${keyword}\x00${text}\x00\x00\x00\x00$data"
            close $fh
        seek $fh [expr {$len + 4}] current
    close $fh
    return -code error "no data section found"


Does not calculate the crc for the comment chunk. Todo: add crc obviously (maybe using tcllib crc package).