Version 4 of Coloring a gray image

Updated 2004-06-05 09:22:55

ulis, 2003-08-22: A little proc to adapt a gray image with transparency to a colored background.

Before:

http://perso.wanadoo.fr/maurice.ulis/tcl/gray-image.gif

After:

http://perso.wanadoo.fr/maurice.ulis/tcl/colorize.gif


The proc

  proc colorize {image color} \
  {
    # get image sizes
    set width [image width $image]
    set height [image height $image]
    # get color's R G B
    foreach {rr gg bb} [winfo rgb . $color] break
    # compute new colors
    set colors {}
    for {set y 0} {$y < $height} {incr y} \
    {
      set row {}
      for {set x 0} {$x < $width} {incr x} \
      {
        # save transparency
        lappend trans $x $y [$image transparency get $x $y]
        # compute the new color
        foreach {r g b} [$image get $x $y] break
        set r [expr {round($r * $rr / 256)}]
        set g [expr {round($g * $gg / 256)}]
        set b [expr {round($b * $bb / 256)}]
        # append to the current row
        lappend row [format #%4.4x%4.4x%4.4x $r $g $b]
      }
      # append the row
      lappend colors $row
    }
    # set new image
    img put $colors
    # restore transparency
    foreach {x y t} $trans { $image transparency set $x $y $t }
  }

The demo

  # =========
  # demo
  # =========
  wm title . colorize
  # get a gray image
  image create photo img -file gray-image.gif
  # add colors
  colorize img azure
  # display
  set width [image width img]
  set height [image height img]
  canvas .c -width [incr width 4] -height [incr height 4] -bg beige
  .c create image 2 2 -anchor nw -image img
  pack .c

Category Example

Category Graphics

Category Image processing