package require Gdtclft
package require Img
package require base64
proc txt2png {police taille texte ang} {
    # Convert deg to rad :
    if { $ang != 0 && $ang != 90 && $ang != 180 && $ang != 270 } {
        set ang 0
    }
    set pi [expr {4.0*atan(1)}]
    set angle [expr $pi * $ang / 180]
    # text image BBox :
    set coords [gd text {} 0 $police $taille 0 0 0 $texte]
    set xmax [lindex $coords 2]
    set ymax [lindex $coords 3]
    set xmin [lindex $coords 6]
    set ymin [lindex $coords 7]
    # Image size :
    set Ltmp [expr ($xmax - $xmin) + 10]
    set Htmp [expr ($ymax - $ymin) + 10]
    # Rotate :
    switch -exact -- $ang {
        0 {
            set L $Ltmp
            set H $Htmp
            set X [expr abs($xmin - 5)]
            set Y [expr abs($ymin - 5)]
        }
        90 {
            set L $Htmp
            set H $Ltmp
            set X [expr abs($ymin - 5)]
            set Y [expr abs($xmax + 5)]
        }
        180 {
            set L $Ltmp
            set H $Htmp
            set X [expr abs($xmax - 5)]
            set Y [expr abs($ymax + 5)]
        }
        270 {
            set L $Htmp
            set H $Ltmp
            set X [expr abs($ymax + 5)]
            set Y [expr abs($xmin - 5)]
        }
    }
    # Build text iamge with gd :
    set gdh [gd create $L $H]
    set blanc [gd color new $gdh 255 255 255]
    set noir [gd color new $gdh 0 0 0]
    gd text $gdh -$noir $police $taille $angle $X $Y $texte
    # record png files :
    # gd builtin command number 1 :
    set fout [open gdtxt1.png w]
    fconfigure $fout -encoding binary -translation binary
    gd writePNG $gdh $fout
    close $fout
    puts stdout "Image 1 : done."
    update idletasks
    # gd builtin command number 2 :
    global data
    set fout [open gdtxt2.png w]
    gd writePNGvar $gdh data
    puts -nonewline $fout $data
    close $fout
    puts stdout "Image 2 : done."
    update idletasks
    # Img data record :
    image create photo test -file gdtxt1.png
    set fout [open gdtxt3.data w]
    puts -nonewline $fout [test data -format png]
    close $fout
    puts stdout "Image 3 : done."
    update idletasks
    # Img base64 decoded data record :
    set fout [open gdtxt4.png w]
    puts -nonewline $fout [::base64::decode [test data -format png]]
    close $fout
    puts stdout "Image 4 : done."
    update idletasks
}

# Set this var to an existing ttf file :
set font /usr/X11R6/lib/X11/fonts/truetype/Arial.ttf
# custom values :
set txtangle 90
set fontsize 33
set string "This is a test string
with 2 lines !"
# Test command :
txt2png $font $fontsize $string $txtangle