Welcome, guest | Sign In | My Account | Store | Cart

This recipe shows how to inline a GIF image directly into your Tcl code.

Tcl, 13 lines
package require base64 ; # in tcllib, part of ActiveTcl

proc inlineGIF {img {name ""}} {
    set f [open $img]
    fconfigure $f -translation binary
    set data [base64::encode [read $f]]
    close $f
    if {[llength [info level 0]] == 2} {
	# base name on root name of the image file
	set name [file root [file tail $img]]
    return "image create photo [list $name] -data {\n$data\n}"

Being able to directly inline images into your Tcl code prevents the need to ship lots of extra image files, like icons, along with your package. This simplifies distribution, especially of one-script applications.

This code applies to GIF images, as the core will read those when base64 encoded as -data. The Img extension extends this capability to other image types and the formats that it handles. Tk does allow for direct use of the binary data passed to -data, but that makes for a very unreadable script which would be difficult to edit.

The string returned is the exact Tcl code to be placed in your script. Note that base64 encoding is whitespace insensitive, so it can be formatted to fit whatever indentation level you desire. It is recommended that sane names be used for the images, as they become commands in the interpreter as well as usable images. You may namespace the image names.

1 comment

Richard Suchenwirth 19 years, 8 months ago  # | flag

Don't give an image name - take one! "sane names be used for images": yes, very much so! "they become commands in the interpreter": and even silently overwrite preexisting commands! Imagine you have an icon for a set of objects, and want to call that image "set": you may, yes, but your program can't do any assignments from that point on, and will probably end up in error messages. The same danger is in the default mechanism of deriving the image name from the filename: assume the file is called "close.gif", you lose Tcl's close command. Therefore it is highly recommended not to give an image name at all, but let the image command create a safe one (like "image123") for you. See http://wiki.tcl.tk/643.html - Richard Suchenwirth

Created by Jeff Hobbs on Mon, 18 Mar 2002 (MIT)
Tcl recipes (162)
Jeff Hobbs's recipes (16)

Required Modules

  • (none specified)

Other Information and Tasks