Updated 2018-03-25 09:40:35 by dbohdan

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

Before:

After:


The proc edit

proc colorize {image color} {
    # get image sizes
    set width  [image width  $image]
    set height [image height $image]
    # get color's R G B
    lassign [winfo rgb . $color] rr gg bb
    # 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
            lassign [$image get $x $y] r g b
            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 edit

# =========
# 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