Version 4 of Reading PNG Comments

Updated 2003-12-18 02:37:45

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 {[string length $r] != $len} { close $fh; return }
        if {$type == "tEXt"} {
            lappend text [split $r \x00]
        } elseif {$type == "iTXt"} {
            set f [string first \x00 $r]
            set keyword [string range $r 0 [expr {$f - 1}]]
            set r [string range $r [expr {$f + 1}] end]
            binary scan $r cc comp method
            set r [split [string range $r 2 end] \x00]
            if {$comp == 0} {
                eval lappend text [list $keyword] [lrange $r 0 2]
            }
        }
        seek $fh 4 current
    }
    close $fh
    return $text
 }

Currently only supports uncompressed comments. 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 (internationl) comment is 4 elements: the human readable keyword, the langauge identifier, the translated keyword, and the unicode text data.

--AF


Category Graphics