From db011643f9db4b46a78d8d6eddf69e61127878a4 Mon Sep 17 00:00:00 2001 From: Aleteoryx Date: Fri, 19 Sep 2025 23:16:24 -0400 Subject: [PATCH] sixel2xbm --- sixel.tcl | 76 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100755 sixel.tcl diff --git a/sixel.tcl b/sixel.tcl new file mode 100755 index 0000000000000000000000000000000000000000..e8715aefddce70c5f0552b4cdb0824b1e75b4b49 --- /dev/null +++ b/sixel.tcl @@ -0,0 +1,76 @@ +#!/bin/env tclsh + +proc char2n {char} { + binary scan $char c n + expr {($n&0x7F)-0x3F} +} + +proc chars2bytes {sixels} { + foreach sixel $sixels { lappend nums [char2n $sixel] } + for {set i 0} {$i < 6} {incr i} { + set s "" + foreach n $nums { + append s [expr {($n>>$i)&1}] + } + append s [string repeat "0" [expr {7 - (([string length $s] + 7) % 8)}]] + binary scan [binary format b* $s] c* bytes + foreach byte $bytes { + lappend ret [format "%02x" [expr {$byte&0xff}]] + } + } + return $ret +} + +proc splitsixels {str} { + set ret {} + set row {} + + foreach c [split $str {}] { + switch -regexp -- $c { + - { + lappend ret $row + set row {} + } + [?-~] { + lappend row $c + } + default { # ignored } + } + } + if {$row != {}} { lappend ret $row } + + return $ret +} + +proc sixels2xbm {sixels} { + set rows [splitsixels $sixels] + set ba {} + if {[llength $rows] == 0} { return {} } + if {[llength $rows] > 3} { set rows [lrange $rows 0 2] } + + set height [expr {min(16, [llength $rows]*6)}] + set width 0 + foreach row $rows { + set width [expr {max($width, [llength $row])}] + } + if {$width == 0} { return {} } + + foreach row $rows { + append row [string repeat " ?" [expr {$width - [llength $row]}]] + lappend bytes {*}[chars2bytes $row] + } + + set nbytes [expr {int(ceil($width / 8.0)) * $height}] + set bytes [lrange $bytes 0 $nbytes-1] + + set ret "#define img_width $width\n#define img_height $height\n" + append ret "static unsigned char img_bits\[\] = {\n\t" + foreach byte $bytes { + append ret "0x" $byte ", " + } + set ret [string range $ret 0 end-2] + append ret "\n\t};\n" + return $ret +} + +puts [sixels2xbm "o{}^}{{{}^}{o???-F^^zvvvvvz^^F???"]