@@ -14,19 +14,46 @@ import (
14
14
"github.com/nfnt/resize"
15
15
)
16
16
17
+ type colorCache struct {
18
+ rgbaToTermenv map [color.RGBA ]termenv.RGBColor
19
+ }
20
+
21
+ func newColorCache () * colorCache {
22
+ return & colorCache {
23
+ rgbaToTermenv : make (map [color.RGBA ]termenv.RGBColor ),
24
+ }
25
+ }
26
+
27
+ func (c * colorCache ) getTermenvColor (col color.Color , fallbackColor string ) termenv.RGBColor {
28
+ rgba := color .RGBAModel .Convert (col ).(color.RGBA )
29
+ if rgba .A == 0 {
30
+ return termenv .RGBColor (fallbackColor )
31
+ }
32
+
33
+ if termenvColor , exists := c .rgbaToTermenv [rgba ]; exists {
34
+ return termenvColor
35
+ }
36
+
37
+ termenvColor := termenv .RGBColor (fmt .Sprintf ("#%02x%02x%02x" , rgba .R , rgba .G , rgba .B ))
38
+ c .rgbaToTermenv [rgba ] = termenvColor
39
+ return termenvColor
40
+ }
41
+
17
42
// ConvertImageToANSI converts an image to ANSI escape codes with proper aspect ratio
18
43
func ConvertImageToANSI (img image.Image , defaultBGColor color.Color ) string {
19
44
width := img .Bounds ().Dx ()
20
45
height := img .Bounds ().Dy ()
21
46
output := ""
47
+ cache := newColorCache ()
48
+ defaultBGHex := colorToHex (defaultBGColor )
22
49
23
50
for y := 0 ; y < height ; y += 2 {
24
51
for x := 0 ; x < width ; x ++ {
25
- upperColor := colorToTermenv (img .At (x , y ), colorToHex ( defaultBGColor ) )
26
- lowerColor := colorToTermenv (defaultBGColor , "" )
52
+ upperColor := cache . getTermenvColor (img .At (x , y ), defaultBGHex )
53
+ lowerColor := cache . getTermenvColor (defaultBGColor , "" )
27
54
28
55
if y + 1 < height {
29
- lowerColor = colorToTermenv (img .At (x , y + 1 ), colorToHex ( defaultBGColor ) )
56
+ lowerColor = cache . getTermenvColor (img .At (x , y + 1 ), defaultBGHex )
30
57
}
31
58
32
59
// Using the "▄" character which fills the lower half
@@ -39,15 +66,6 @@ func ConvertImageToANSI(img image.Image, defaultBGColor color.Color) string {
39
66
return output
40
67
}
41
68
42
- // colorToTermenv converts a color.Color to a termenv.RGBColor
43
- func colorToTermenv (c color.Color , fallbackColor string ) termenv.RGBColor {
44
- r , g , b , a := c .RGBA ()
45
- if a == 0 {
46
- return termenv .RGBColor (fallbackColor )
47
- }
48
- return termenv .RGBColor (fmt .Sprintf ("#%02x%02x%02x" , uint8 (r >> 8 ), uint8 (g >> 8 ), uint8 (b >> 8 )))
49
- }
50
-
51
69
// Return image preview ansi string
52
70
func ImagePreview (path string , maxWidth , maxHeight int , defaultBGColor string ) (string , error ) {
53
71
// Load image file
0 commit comments