-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdecoder.go
More file actions
131 lines (106 loc) · 1.93 KB
/
decoder.go
File metadata and controls
131 lines (106 loc) · 1.93 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package main
import (
"image"
_ "image/jpeg"
_ "image/png"
"io/ioutil"
"log"
"math/rand"
"os"
"strings"
)
type Decoder struct {
files []string
fileNum int
image image.Image
y int
}
func NewDecoder(path string) *Decoder {
files, err := getFilenames(path)
if err != nil {
return nil
}
start := 0
if len(files) > 1 {
start = rand.Intn(len(files))
}
d := &Decoder{
files: files,
fileNum: start,
image: nil,
y: 0,
}
if d.NextImage() {
return d
}
return nil
}
func getFilenames(path string) ([]string, error) {
files, err := ioutil.ReadDir(path)
if err != nil {
return []string{}, err
}
o := []string{}
for _, file := range files {
n := file.Name()
if strings.HasPrefix(n, ".") || strings.HasPrefix(n, "_") || file.IsDir() {
continue
}
o = append(o, path+"/"+n)
}
return o, nil
}
func (d *Decoder) NextImage() bool {
d.y = 0
// If we only have one image and it's already loaded, we're done.
if d.image != nil && len(d.files) < 2 {
return true
}
d.image = nil
for {
if len(d.files) == 0 {
return false
}
if d.fileNum >= len(d.files) {
d.fileNum = 0
}
file := d.files[d.fileNum]
img, err := readImage(file)
if err == nil {
d.image = img
d.y = img.Bounds().Min.Y
d.fileNum++
return true
}
log.Println("Error reading", file, err)
d.files = append(d.files[:d.fileNum], d.files[d.fileNum+1:]...)
}
}
func (d *Decoder) NextFrame() Frame {
if d.image == nil {
return nil
}
f := ImageRowToFrame(d.image, d.y)
// If we're on the last row, we'll have to load the next image.
d.y++
if d.y >= d.image.Bounds().Max.Y {
d.NextImage()
}
return f
}
func readImage(file string) (image.Image, error) {
reader, err := os.Open(file)
if err != nil {
return nil, err
}
defer func() {
_ = reader.Close()
}()
img, _, err := image.Decode(reader)
if err != nil {
return nil, err
}
return img, nil
}
func (d *Decoder) Close() {
}