~aleteoryx/ntalk

ref: e9b9fea44bc5237d8610448bb035efe2350ffb2a ntalk/sixel.tcl -rwxr-xr-x 1.6 KiB
e9b9fea4Aleteoryx nano!!! a month ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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???"]