Debian Codegraph @

mosaic/mosaic.go

raw
1 // Package mosaic provides a unicode image renderer.
2 package mosaic
3
4 import (
5 "image"
6 "image/color"
7 "image/color/palette"
8 "image/draw"
9 "math"
10 "strings"
11
12 "github.com/charmbracelet/x/ansi"
13 xdraw "golang.org/x/image/draw"
14 )
15
16 // Blocks definition.
17 var (
18 halfBlocks = []block{
19 {Char: '▀', Coverage: [4]bool{true, true, false, false}, CoverageMap: "██\n "}, // Upper half block.
20 {Char: '▄', Coverage: [4]bool{false, false, true, true}, CoverageMap: " \n██"}, // Lower half block.
21 {Char: ' ', Coverage: [4]bool{false, false, false, false}, CoverageMap: " \n "}, // Space.
22 {Char: '█', Coverage: [4]bool{true, true, true, true}, CoverageMap: "██\n██"}, // Full block.
23 }
24 quarterBlocks = []block{
25 {Char: '▘', Coverage: [4]bool{true, false, false, false}, CoverageMap: "█ \n "}, // Quadrant upper left.
26 {Char: '▝', Coverage: [4]bool{false, true, false, false}, CoverageMap: " █\n "}, // Quadrant upper right.
27 {Char: '▖', Coverage: [4]bool{false, false, true, false}, CoverageMap: " \n█ "}, // Quadrant lower left.
28 {Char: '▗', Coverage: [4]bool{false, false, false, true}, CoverageMap: " \n █"}, // Quadrant lower right.
29 {Char: '▌', Coverage: [4]bool{true, false, true, false}, CoverageMap: "█ \n█ "}, // Left half block.
30 {Char: '▐', Coverage: [4]bool{false, true, false, true}, CoverageMap: " █\n █"}, // Right half block.
31 {Char: '▀', Coverage: [4]bool{true, true, false, false}, CoverageMap: "██\n "}, // Upper half block (already added).
32 {Char: '▄', Coverage: [4]bool{false, false, true, true}, CoverageMap: " \n██"}, // Lower half block (already added).
33 }
34 complexBlocks = []block{
35 {Char: '▙', Coverage: [4]bool{true, false, true, true}, CoverageMap: "█ \n██"}, // Quadrant upper left and lower half.
36 {Char: '▟', Coverage: [4]bool{false, true, true, true}, CoverageMap: " █\n██"}, // Quadrant upper right and lower half.
37 {Char: '▛', Coverage: [4]bool{true, true, true, false}, CoverageMap: "██\n█ "}, // Quadrant upper half and lower left.
38 {Char: '▜', Coverage: [4]bool{true, true, false, true}, CoverageMap: "██\n █"}, // Quadrant upper half and lower right.
39 {Char: '▚', Coverage: [4]bool{true, false, false, true}, CoverageMap: "█ \n █"}, // Quadrant upper left and lower right.
40 {Char: '▞', Coverage: [4]bool{false, true, true, false}, CoverageMap: " █\n█ "}, // Quadrant upper right and lower left.
41 }
42 )
43
44 // Block represents different Unicode block characters.
45 type block struct {
46 Char rune
47 Coverage [4]bool // Which parts of the block are filled (true = filled).
48 CoverageMap string // Visual representation of coverage for debugging.
49 }
50
51 // Symbol represents the symbol type to use when rendering the image.
52 type Symbol uint8
53
54 // Symbol types.
55 const (
56 All Symbol = iota
57 Half
58 Quarter
59 )
60
61 // In many contexts, a default threshold level is often set to 0.5 (or 50%),
62 // which means that values above this threshold are considered positive,
63 // while those below are considered negative.
64 // The value 128 represents the 0.5 of 0..255.
65 const middleThresholdLevel = 128
66
67 // Render mosaic with default values.
68 func Render(img image.Image, width int, height int) string {
69 m := New().Width(width).Height(height)
70 return m.Render(img)
71 }
72
73 // Mosaic represents a Unicode image renderer.
74 //
75 // Example:
76 //
77 // ```go
78 // art := mosaic.New().Width(100). // Limit to 100 cells
79 // Scale(mosaic.Fit). // Fit to width
80 // Render()
81 // ```
82 type Mosaic struct {
83 outputWidth int // Output width.
84 outputHeight int // Output height (0 for auto).
85 thresholdLevel uint8 // Threshold for considering a pixel as set (0-255).
86 dither bool // Enable Dithering (false as default).
87 useFgBgOnly bool // Use only foreground/background colors (no block symbols).
88 invertColors bool // Invert colors.
89 scale int // Scale level
90 symbols Symbol // Which symbols to use: "half", "quarter", "all".
91 }
92
93 // New creates and returns a [Renderer].
94 func New() Mosaic {
95 return Mosaic{
96 outputWidth: 0, // Override width.
97 outputHeight: 0, // Override height.
98 thresholdLevel: middleThresholdLevel, // Middle threshold.
99 dither: false, // Enable dithering.
100 useFgBgOnly: false, // Use block symbols.
101 invertColors: false, // Don't invert.
102 scale: 1, // Don't scale.
103 symbols: Half, // Use half blocks.
104 }
105 }
106
107 // PixelBlock represents a 2x2 pixel block from the image.
108 type pixelBlock struct {
109 Pixels [2][2]color.Color // 2x2 pixel grid.
110 AvgFg color.Color // Average foreground color.
111 AvgBg color.Color // Average background color.
112 BestSymbol rune // Best matching character.
113 BestFgColor color.Color // Best foreground color.
114 BestBgColor color.Color // Best background color.
115 }
116
117 // Represents 255.
118 const u8MaxValue = 0xff
119
120 type shiftable interface {
121 ~uint | ~uint16 | ~uint32 | ~uint64
122 }
123
124 func shift[T shiftable](x T) T {
125 if x > u8MaxValue {
126 x >>= 8
127 }
128 return x
129 }
130
131 // Scale sets the [ScaleMode] on [Mosaic].
132 func (m Mosaic) Scale(scale int) Mosaic {
133 m.scale = scale
134 return m
135 }
136
137 // IgnoreBlockSymbols set UseFgBgOnly on [Mosaic].
138 func (m Mosaic) IgnoreBlockSymbols(fgOnly bool) Mosaic {
139 m.useFgBgOnly = fgOnly
140 return m
141 }
142
143 // Dither sets the dither level on [Mosaic].
144 func (m Mosaic) Dither(dither bool) Mosaic {
145 m.dither = dither
146 return m
147 }
148
149 // Threshold sets the threshold level on [Mosaic].
150 // It expects a value between 0-255, anything else will be ignored.
151 func (m Mosaic) Threshold(threshold int) Mosaic {
152 if threshold >= 0 && threshold <= u8MaxValue {
153 m.thresholdLevel = uint8(threshold)
154 }
155
156 return m
157 }
158
159 // InvertColors whether to invert the colors of the mosaic image.
160 func (m Mosaic) InvertColors(invertColors bool) Mosaic {
161 m.invertColors = invertColors
162 return m
163 }
164
165 // Width sets the maximum width the image can have. Defaults to the image width.
166 func (m Mosaic) Width(width int) Mosaic {
167 m.outputWidth = width
168 return m
169 }
170
171 // Height sets the maximum height the image can have. Defaults to the image height.
172 func (m Mosaic) Height(height int) Mosaic {
173 m.outputHeight = height
174 return m
175 }
176
177 // Symbol sets the mosaic symbol type.
178 func (m Mosaic) Symbol(symbol Symbol) Mosaic {
179 m.symbols = symbol
180 return m
181 }
182
183 // Render renders the image to a string.
184 func (m *Mosaic) Render(img image.Image) string {
185 // Calculate dimensions.
186 bounds := img.Bounds()
187 srcWidth := bounds.Max.X - bounds.Min.X
188 srcHeight := bounds.Max.Y - bounds.Min.Y
189
190 // Determine output dimensions.
191 outWidth := srcWidth
192 if m.outputWidth > 0 {
193 outWidth = m.outputWidth
194 }
195
196 outHeight := srcHeight
197 if m.outputHeight > 0 {
198 outHeight = m.outputHeight
199 }
200
201 if outHeight <= 0 {
202 // Calculate height based on aspect ratio and character cell proportions.
203 // Terminal characters are roughly twice as tall as wide, so we divide by 2.
204 const divider = 2
205 outHeight = int(float64(outWidth) * float64(srcHeight) / float64(srcWidth) / divider)
206 if outHeight < 1 {
207 outHeight = 1
208 }
209 }
210
211 // Scale image according to the scale.
212 scaledImg := m.applyScaling(img, outWidth*m.scale, outHeight*m.scale)
213
214 // Apply dithering if enabled.
215 if m.dither {
216 scaledImg = m.applyDithering(scaledImg)
217 }
218
219 // Invert colors if needed.
220 if m.invertColors {
221 scaledImg = m.invertImage(scaledImg)
222 }
223
224 // Generate terminal outpum.
225 var output strings.Builder
226
227 // Process the image by 2x2 blocks (representing one character cell).
228 imageBounds := scaledImg.Bounds()
229
230 // Set initial blocks based on symbols value (initial/default is half)
231 blocks := halfBlocks
232
233 // Quarter blocks.
234 if m.symbols == Quarter || m.symbols == All {
235 blocks = append(blocks, quarterBlocks...)
236 }
237
238 // All block elements (including complex combinations).
239 if m.symbols == All {
240 blocks = append(blocks, complexBlocks...)
241 }
242
243 for y := 0; y < imageBounds.Max.Y; y += 2 {
244 for x := 0; x < imageBounds.Max.X; x += 2 {
245 // Create and analyze the 2x2 pixel block.
246 block := m.createPixelBlock(scaledImg, x, y)
247
248 // Determine best symbol and colors.
249 m.findBestRepresentation(block, blocks)
250
251 // Append to output.
252 output.WriteString(
253 ansi.Style{}.ForegroundColor(block.BestFgColor).BackgroundColor(block.BestBgColor).Styled(string(block.BestSymbol)),
254 )
255 }
256 output.WriteString("\n")
257 }
258
259 return output.String()
260 }
261
262 // createPixelBlock extracts a 2x2 block of pixels from the image.
263 func (m *Mosaic) createPixelBlock(img image.Image, x, y int) *pixelBlock {
264 block := &pixelBlock{}
265
266 // Extract the 2x2 pixel grid.
267 for dy := 0; dy < 2; dy++ {
268 for dx := 0; dx < 2; dx++ {
269 block.Pixels[dy][dx] = m.getPixelSafe(img, x+dx, y+dy)
270 }
271 }
272
273 return block
274 }
275
276 // findBestRepresentation finds the best block character and colors for a 2x2 pixel block.
277 func (m *Mosaic) findBestRepresentation(block *pixelBlock, availableBlocks []block) {
278 // Simple case: use only foreground/background colors.
279 if m.useFgBgOnly {
280 // Just use the upper half block with top pixels as background and bottom as foreground.
281 block.BestSymbol = '▀'
282 block.BestBgColor = m.averageColors(block.Pixels[0][0], block.Pixels[0][1])
283 block.BestFgColor = m.averageColors(block.Pixels[1][0], block.Pixels[1][1])
284 return
285 }
286
287 // Determine which pixels are "set" based on threshold.
288 pixelMask := [2][2]bool{}
289 for y := 0; y < 2; y++ {
290 for x := 0; x < 2; x++ {
291 // Calculate luminance.
292 luma := rgbaToLuminance(block.Pixels[y][x])
293 pixelMask[y][x] = luma >= m.thresholdLevel
294 }
295 }
296
297 // Find the best matching block character.
298 bestChar := ' '
299 bestScore := math.MaxFloat64
300
301 for _, blockChar := range availableBlocks {
302 score := 0.0
303 for i := 0; i < 4; i++ {
304 y, x := i/2, i%2 //nolint:mnd
305 if blockChar.Coverage[i] != pixelMask[y][x] {
306 score += 1.0
307 }
308 }
309
310 if score < bestScore {
311 bestScore = score
312 bestChar = blockChar.Char
313 }
314 }
315
316 // Determine foreground and background colors based on the best character.
317 var fgPixels, bgPixels []color.Color
318
319 // Get the coverage pattern for the selected character.
320 var coverage [4]bool
321 for _, b := range availableBlocks {
322 if b.Char == bestChar {
323 coverage = b.Coverage
324 break
325 }
326 }
327
328 // Assign pixels to foreground or background based on the character's coverage.
329 for i := 0; i < 4; i++ {
330 y, x := i/2, i%2 //nolint:mnd
331 if coverage[i] {
332 fgPixels = append(fgPixels, block.Pixels[y][x])
333 } else {
334 bgPixels = append(bgPixels, block.Pixels[y][x])
335 }
336 }
337
338 // Calculate average colors.
339 if len(fgPixels) > 0 {
340 block.BestFgColor = m.averageColors(fgPixels...)
341 } else {
342 // Default to black if no foreground pixels.
343 block.BestFgColor = color.Black
344 }
345
346 if len(bgPixels) > 0 {
347 block.BestBgColor = m.averageColors(bgPixels...)
348 } else {
349 // Default to black if no background pixels.
350 block.BestBgColor = color.Black
351 }
352
353 block.BestSymbol = bestChar
354 }
355
356 // averageColors calculates the average color from a slice of colors.
357 func (m *Mosaic) averageColors(colors ...color.Color) color.Color {
358 if len(colors) == 0 {
359 return color.Black
360 }
361
362 var sumR, sumG, sumB, sumA uint32
363
364 for _, c := range colors {
365 r, g, b, a := c.RGBA()
366 r, g, b, a = shift(r), shift(g), shift(b), shift(a)
367 sumR += r
368 sumG += g
369 sumB += b
370 sumA += a
371 }
372
373 count := uint32(len(colors)) //nolint:gosec
374 return color.RGBA{
375 R: uint8(sumR / count), //nolint:gosec
376 G: uint8(sumG / count), //nolint:gosec
377 B: uint8(sumB / count), //nolint:gosec
378 A: uint8(sumA / count), //nolint:gosec
379 }
380 }
381
382 // getPixelSafe returns the color at (x,y) or black if out of bounds.
383 func (m *Mosaic) getPixelSafe(img image.Image, x, y int) color.RGBA {
384 bounds := img.Bounds()
385 if x < bounds.Min.X || x >= bounds.Max.X || y < bounds.Min.Y || y >= bounds.Max.Y {
386 return color.RGBA{0, 0, 0, 255}
387 }
388
389 r8, g8, b8, a8 := img.At(x, y).RGBA()
390 return color.RGBA{
391 R: uint8(r8 >> 8), //nolint:gosec,mnd
392 G: uint8(g8 >> 8), //nolint:gosec,mnd
393 B: uint8(b8 >> 8), //nolint:gosec,mnd
394 A: uint8(a8 >> 8), //nolint:gosec,mnd
395 }
396 }
397
398 // applyScaling resizes an image to the specified dimensions.
399 func (m *Mosaic) applyScaling(img image.Image, width, height int) image.Image {
400 rect := image.Rect(0, 0, width, height)
401 dst := image.NewRGBA(rect)
402 xdraw.ApproxBiLinear.Scale(dst, rect, img, img.Bounds(), draw.Over, nil)
403 return dst
404 }
405
406 // applyDithering applies Floyd-Steinberg dithering.
407 func (m *Mosaic) applyDithering(img image.Image) image.Image {
408 b := img.Bounds()
409 pm := image.NewPaletted(b, palette.Plan9)
410 draw.FloydSteinberg.Draw(pm, b, img, image.Point{})
411 return pm
412 }
413
414 // invertImage inverts the colors of an image.
415 func (m *Mosaic) invertImage(img image.Image) image.Image {
416 bounds := img.Bounds()
417 width := bounds.Max.X - bounds.Min.X
418 height := bounds.Max.Y - bounds.Min.Y
419
420 result := image.NewRGBA(bounds)
421 for y := 0; y < height; y++ {
422 for x := 0; x < width; x++ {
423 r8, g8, b8, a8 := img.At(x+bounds.Min.X, y+bounds.Min.Y).RGBA()
424 result.Set(x, y, color.RGBA{
425 R: uint8(255 - (r8 >> 8)), //nolint:gosec,mnd
426 G: uint8(255 - (g8 >> 8)), //nolint:gosec,mnd
427 B: uint8(255 - (b8 >> 8)), //nolint:gosec,mnd
428 A: uint8(a8 >> 8), //nolint:gosec,mnd
429 })
430 }
431 }
432
433 return result
434 }
435
436 // rgbaToLuminance converts RGBA color to luminance (brightness).
437 func rgbaToLuminance(c color.Color) uint8 {
438 r, g, b, _ := c.RGBA()
439 r, g, b = shift(r), shift(g), shift(b)
440 // Weighted RGB to account for human perception
441 // source: https://www.w3.org/TR/AERT/#color-contrast
442 // context: https://stackoverflow.com/questions/596216/formula-to-determine-perceived-brightness-of-rgb-color
443 return uint8(float64(r)*0.299 + float64(g)*0.587 + float64(b)*0.114)
444 }