Version 8 of Image scaling

Updated 2003-02-27 16:06:16

Richard Suchenwirth 2003-02-25 - Photo images can be resized by adding the -zoom or -subsample switches when copying an image. Here is a wrapper that takes only a factor and selects the appropriate switch. The image is scaled in place (so when it is displayed in a widget, updating goes automatically), the temporary image t is freed when no more needed. The following enhanced version is 3 LOC more, but also does flipping around x and/or y axis:

 proc scaleImage {im xfactor {yfactor 0}} {
    set mode -subsample
    if {abs($xfactor) < 1} {
       set xfactor [expr round(1./$xfactor)]
    } elseif {$xfactor>=0 && $yfactor>=0} {
        set mode -zoom
    }
    if {$yfactor == 0} {set yfactor $xfactor}
    set t [image create photo]
    $t copy $im
    $im blank
    $im copy $t -shrink $mode $xfactor $yfactor
    image delete $t
 }

http://mini.net/files/ifilezoom.jpg

Usage examples: adding the following lines gives iFile: a little file system browser scaling capacities on the image shown on the "File" page:

 .m add casc -label Image -menu [menu .m.image -tearoff 0]
 .m.image add comm -label "Zoom x 3" -command {scaleImage $g(i) 3}
 .m.image add comm -label "Zoom x 2" -command {scaleImage $g(i) 2}
 .m.image add comm -label "Zoom x 0.5" -command {scaleImage $g(i) 0.5}
 .m.image add comm -label "Zoom x 0.33" -command {scaleImage $g(i) 0.33}
 .m.image add separator
 .m.image add comm -label "Flip LR" -command {scaleImage $g(i) -1 1}
 .m.image add comm -label "Flip TB" -command {scaleImage $g(i) 1 -1}
 .m.image add comm -label "Flip both" -command {scaleImage $g(i) -1 -1}

For robustness, one might disable this menu when no image is displayed. Experience shows that enlarging bigger photo images may let the little machine run out of memory - time to throw away some fat MP3 files...


Image scaling also helps in the GIF transparency problem on iPAQ - this workaround works:

  • put an instance of the image in a widget (e.g. a text)
  • zoom up
  • subsample down again

Now transparent pixels are in the widget background color (white), no more random and black, for all instances, and certainly look better than before.

 foreach i $g(images) {
   $g(text) image create end -image $g($i)
   scaleImage $g($i) 3
   scaleImage $g($i) .33
 }

See also Photo image rotation


Arts and crafts of Tcl-Tk programming