-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathasciiart.go
77 lines (68 loc) · 1.51 KB
/
asciiart.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// Package asciiart can generate ASCII art from provided image.
package asciiart
import (
"image"
"image/draw"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"github.com/nfnt/resize"
)
type AsciiArt struct {
Title string
Art string
}
const (
sBLACK = '@'
sCHARCOAL = '#'
sDARKGRAY = '8'
sMEDIUMGRAY = '&'
sMEDIUM = 'o'
sGRAY = ':'
sSLATEGRAY = '*'
sLIGHTGRAY = '.'
sWHITE = ' '
)
// Reference: http://www.codeproject.com/Articles/20435/Using-C-To-Generate-ASCII-Art-From-An-Image
func generateAsciiArt(img image.Image) string {
resized := resize.Resize(80, 0, img, resize.Bilinear)
rect := resized.Bounds()
gray := image.NewGray(rect)
draw.Draw(gray, rect, resized, rect.Min, draw.Src)
size := rect.Size()
art := make([]byte, (size.X+1)*size.Y)
pos := 0
for y := 0; y < size.Y; y++ {
for x := 0; x < size.X; x++ {
r, _, _, _ := gray.At(x, y).RGBA()
r /= 256
if r >= 230 {
art[pos] = sWHITE
} else if r >= 200 {
art[pos] = sLIGHTGRAY
} else if r >= 180 {
art[pos] = sSLATEGRAY
} else if r >= 160 {
art[pos] = sGRAY
} else if r >= 130 {
art[pos] = sMEDIUM
} else if r >= 100 {
art[pos] = sMEDIUMGRAY
} else if r >= 70 {
art[pos] = sDARKGRAY
} else if r >= 50 {
art[pos] = sCHARCOAL
} else {
art[pos] = sBLACK
}
pos++
}
art[pos] = '\n'
pos++
}
return string(art)
}
// New creates an ASCII art from an image
func New(title string, img image.Image) *AsciiArt {
return &AsciiArt{title, generateAsciiArt(img)}
}