-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconvert.go
52 lines (43 loc) · 1.05 KB
/
convert.go
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
package image2ascii
import (
"image"
"image/color"
"strings"
"github.com/zkck/image2ascii/ansicodes"
)
type Converter struct {
AsciiMap string
Color bool
Bold bool
}
func DefaultConverter() Converter {
return Converter{
AsciiMap: " .:-=+*#%@",
Color: true,
Bold: false,
}
}
func getColorDepth(c color.Color) int {
depth, _, _, _ := color.GrayModel.Convert(c).RGBA()
return int(depth)
}
func (c Converter) Convert(img image.Image, width, height uint) string {
img = resize(img, scaleBounds(img.Bounds(), width, height))
var builder strings.Builder
bounds := img.Bounds()
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
for x := bounds.Min.X; x < bounds.Max.X; x++ {
asciiChar := c.AsciiMap[len(c.AsciiMap)*getColorDepth(img.At(x, y))/(0xffff+1)]
if c.Color {
builder.WriteString(ansicodes.SetForegroundColor(img.At(x, y)))
}
if c.Bold {
builder.WriteString(ansicodes.Bold)
}
builder.WriteByte(asciiChar)
builder.WriteString(ansicodes.Reset)
}
builder.WriteByte('\n')
}
return builder.String()
}