5.6. Example - Large Objects - Picture Viewer, Part 2 - View Pictures

This example is the second part of a GIF picture viewer which stores the images as large objects in the database. Given an identifier on the command line, it attempts to retrieve and display the stored picture with that identifier.

See Section 5.5, “Example - Large Objects - Picture Viewer, Part 1 - Store Pictures” for the program used to insert the pictures in the database.

This example runs under wish, not tclsh. It also assumes database connection information is provided through the environment.

Example 5.13. Large Objects - View Pictures Stored in Database

#!/usr/bin/wish
# Example - picture storage as Large Object - viewer

package require Pgtcl

# Return the large object data identified by 'name'.
# Throw an error if it can't be read.
proc get_picture {conn name} {
    set q_name [pg_escape_string $name]

    set result [pg_exec $conn "SELECT poid FROM pics WHERE pname='$q_name'"]

    if {[pg_result $result -status] != "PGRES_TUPLES_OK"} {
        set message [pg_result $result -error]
        pg_result $result -clear
        error "Error: Query failed: $message"
    }

    if {[set n [pg_result $result -numTuples]] != 1} {
        pg_result $result -clear
        error "Error: Query returned $n results"
    }

    # Get the OID from the query result: tuple 0, column 0:
    set oid [lindex [pg_result $result -getTuple 0] 0]
    pg_result $result -clear

    # Read the large object from the database, and store it in $data:
    pg_execute $conn BEGIN
    if {[catch {
        set lofd [pg_lo_open $conn $oid r]
        set data {}
        while {[pg_lo_read $conn $lofd buf 8192] > 0} {
            append data $buf
        }
        pg_lo_close $conn $lofd
    } msg]} {
        pg_execute $conn ROLLBACK
        error "Error reading large object: $msg"
    }
    # No changes, might as well roll back
    pg_execute $conn ROLLBACK
    return $data
}


if {$argc != 1} {
    puts stderr "Usage: view_picture name"
    exit 1
}
set name [lindex $argv 0]

# Connect to the database.
set conn [pg_connect -conninfo ""]

# Get the picture data:
set failed [catch {get_picture $conn $name} data]

# Done with database connection:
pg_disconnect $conn

# Exit if unable to retrieve the data:
if {$failed} {
    puts "Failed to view picture '$name': $data"
    exit
}

# Make the viewer and show the picture:
wm title . "Picture: $name"
image create photo p -data $data -format GIF
label .top -image p
button .quit -text Close -command exit -default active
bind . <Return> exit
pack .top -side top
pack .quit

SourceForge.net Logo

This version of the manual was produced for the Pgtcl-ng Sourceforge project web service site, which requires the logo on each page.

To download a logo-free copy of the manual, see the Pgtcl-ng project downloads area.