-
Notifications
You must be signed in to change notification settings - Fork 81
/
image.go
76 lines (70 loc) · 1.75 KB
/
image.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
package termloop
import (
"image"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"log"
"os"
)
// Image processing
func colorGridFromFile(filename string) *[][]Attr {
reader, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
defer reader.Close()
m, _, err := image.Decode(reader)
if err != nil {
log.Fatal(err)
}
bounds := m.Bounds()
// Pull pixel colour data out of image
w := bounds.Max.X - bounds.Min.X
h := bounds.Max.Y - bounds.Min.Y
colors := make([][]Attr, w)
for i := range colors {
colors[i] = make([]Attr, h)
}
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
for x := bounds.Min.X; x < bounds.Max.X; x++ {
r, g, b, a := m.At(x, y).RGBA()
if a < 1 {
continue
}
R := int(r >> 8)
G := int(g >> 8)
B := int(b >> 8)
colors[x-bounds.Min.X][y-bounds.Min.Y] = RgbTo256Color(R, G, B)
}
}
return &colors
}
// BackgroundCanvasFromFile takes a path to an image file,
// and creates a canvas of background-only Cells representing
// the image. This can be applied to an Entity with ApplyCanvas.
func BackgroundCanvasFromFile(filename string) *Canvas {
colors := colorGridFromFile(filename)
c := make(Canvas, len(*colors))
for i := range c {
c[i] = make([]Cell, len((*colors)[i]))
for j := range c[i] {
c[i][j] = Cell{Bg: (*colors)[i][j]}
}
}
return &c
}
// ForegroundCanvasFromFile takes a path to an image file,
// and creates a canvas of foreground-only Cells representing
// the image. This can be applied to an Entity with ApplyCanvas.
func ForegroundCanvasFromFile(filename string) *Canvas {
colors := colorGridFromFile(filename)
c := make(Canvas, len(*colors))
for i := range c {
c[i] = make([]Cell, len((*colors)[i]))
for j := range c[i] {
c[i][j] = Cell{Fg: (*colors)[i][j]}
}
}
return &c
}