Flipping a canvas

ulis, 2003-12-01. On c.l.t, Thomas Kistner asked how to flip a canvas. Thanks to the window format of the Img package, here is an answer:

https://web.archive.org/web/20070208100431/perso.orange.fr/maurice.ulis/tcl/reversed.gif


The script

  package require Img

  # create an image

  image create photo _image_ 
  for {set x 0} {$x < 128} {incr x} \
  {
    for {set y 0} {$y < 128} {incr y} \
    {
      set r [expr {$x * 2}]
      set g [expr {$y * 2}]
      set b [expr {$x + $y}]
      set pixel [format #%02x%02x%02x $r $g $b]
      _image_ put $pixel -to $x $y
    }
  }

  # create a canvas with a text and an image

  frame .f1 -bd 1 -relief ridge
  canvas .f1.c -width 200 -height 150
  .f1.c create text 20 2 -anchor nw -text "this is an image"
  .f1.c create image 10 20 -anchor nw -image _image_
  pack .f1 .f1.c

  # take a snapshot of the canvas

  update
  image create photo _canvas_ -format window -data .f1.c

  # reverse the image

  set width [image width _canvas_]
  set height [image height _canvas_]
  image create photo _reversed_
  for {set x 0} {$x < $width} {incr x} \
  {
    for {set y 0} {$y < $height} {incr y} \
    {
      set x1 [expr {$width - $x - 1}]
      set pixel [eval format #%02x%02x%02x [_canvas_ get $x $y]]
      _reversed_ put $pixel -to $x1 $y
    }
  }

  # show the reversed image

  frame .f2 -bd 1 -relief groove
  canvas .f2.c -width 200 -height 150
  .f2.c create image 2 2 -anchor nw -image _reversed_
  pack .f2 .f2.c

See also