Skip to content

Commit a48762d

Browse files
committed
perf: optimize color conversion with caching
1 parent 3a50367 commit a48762d

File tree

1 file changed

+30
-12
lines changed

1 file changed

+30
-12
lines changed

src/pkg/file_preview/image_preview.go

+30-12
Original file line numberDiff line numberDiff line change
@@ -14,19 +14,46 @@ import (
1414
"github.com/nfnt/resize"
1515
)
1616

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+
1742
// ConvertImageToANSI converts an image to ANSI escape codes with proper aspect ratio
1843
func ConvertImageToANSI(img image.Image, defaultBGColor color.Color) string {
1944
width := img.Bounds().Dx()
2045
height := img.Bounds().Dy()
2146
output := ""
47+
cache := newColorCache()
48+
defaultBGHex := colorToHex(defaultBGColor)
2249

2350
for y := 0; y < height; y += 2 {
2451
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, "")
2754

2855
if y + 1 < height {
29-
lowerColor = colorToTermenv(img.At(x, y + 1), colorToHex(defaultBGColor))
56+
lowerColor = cache.getTermenvColor(img.At(x, y+1), defaultBGHex)
3057
}
3158

3259
// Using the "▄" character which fills the lower half
@@ -39,15 +66,6 @@ func ConvertImageToANSI(img image.Image, defaultBGColor color.Color) string {
3966
return output
4067
}
4168

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-
5169
// Return image preview ansi string
5270
func ImagePreview(path string, maxWidth, maxHeight int, defaultBGColor string) (string, error) {
5371
// Load image file

0 commit comments

Comments
 (0)