Skip to content

Commit 9781627

Browse files
optimize image rendering performance (#183)
1 parent 95b9184 commit 9781627

File tree

1 file changed

+19
-7
lines changed

1 file changed

+19
-7
lines changed

flags/pokemonflagset.go

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -331,13 +331,23 @@ func ImageFlag(w io.Writer, endpoint string, pokemonName string, size string) er
331331

332332
// Anonymous function to transform the image to a string
333333
ToString := func(width int, height int, img image.Image) string {
334-
// Resize the image to the specified width, preserving aspect ratio
335334
img = imaging.Resize(img, width, height, imaging.NearestNeighbor)
336335
b := img.Bounds()
337336

338337
imageWidth := b.Max.X
339338
h := b.Max.Y
339+
340+
rowCount := (h - 1) / 2
341+
if h%2 != 0 {
342+
rowCount++
343+
}
344+
estimatedSize := (imageWidth * rowCount * 55) + rowCount
345+
340346
str := strings.Builder{}
347+
str.Grow(estimatedSize)
348+
349+
// Cache for lipgloss styles to avoid recreating identical styles
350+
styleCache := make(map[string]lipgloss.Style)
341351

342352
for heightCounter := 0; heightCounter < h-1; heightCounter += 2 {
343353
for x := 0; x < imageWidth; x++ {
@@ -347,14 +357,16 @@ func ImageFlag(w io.Writer, endpoint string, pokemonName string, size string) er
347357
c2, _ := styling.MakeColor(img.At(x, heightCounter+1))
348358
color2 := lipgloss.Color(c2.Hex())
349359

350-
// Render the half-block character with the two colors
351-
str.WriteString(lipgloss.NewStyle().
352-
Foreground(color1).
353-
Background(color2).
354-
Render("▀"))
360+
styleKey := string(color1) + "_" + string(color2)
361+
style, exists := styleCache[styleKey]
362+
if !exists {
363+
style = lipgloss.NewStyle().Foreground(color1).Background(color2)
364+
styleCache[styleKey] = style
365+
}
366+
367+
str.WriteString(style.Render("▀"))
355368
}
356369

357-
// Add a newline after each row
358370
str.WriteString("\n")
359371
}
360372

0 commit comments

Comments
 (0)