Updated 2012-01-06 13:12:51 by RLE

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

    while {[set r [read $fh 8]] != ""} {
        binary scan $r Ia4 len type
        set r [read $fh $len]
        if {[eof $fh]} { close $fh; return }
        if {$type == "tEXt"} {
            lappend text [split $r \x00]
        } elseif {$type == "iTXt"} {
            set keyword [lindex [split $r \x00] 0]
            set r [string range $r [expr {[string length $keyword] + 1}] end]
            binary scan $r cc comp method
            if {$comp == 0} {
                lappend text [linsert [split [string range $r 2 end] \x00] 0 $keyword]
            }
        }
        seek $fh 4 current
    }
    close $fh
    return $text
 }

Currently only supports uncompressed comments. Does not attempt to verify checksum. Todo: add inflate support.

Returns a list where each element is a comment.

Each comment is itself a list.

a plain text comment consists of 2 elements: the human readable keyword, and the text data.

a unicode (international) comment is 4 elements: the human readable keyword, the langauge identifier, the translated keyword, and the unicode text data.

--AF 18-12-03