-
Notifications
You must be signed in to change notification settings - Fork 0
/
decode.go
70 lines (59 loc) · 1.31 KB
/
decode.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
package gifenc
import (
"fmt"
"image"
"image/draw"
"image/gif"
)
// Decode a gif. This will split the GIF into multiple images.
func (config Config) Decode(gif *gif.GIF) ([]*image.RGBA, error) {
imgs, err := split(gif, config.Width, config.Height)
if err != nil {
return nil, fmt.Errorf("error while decoding file: %s", err)
}
return imgs, nil
}
// Split the GIF into images
func split(gif *gif.GIF, width int, height int) (imgs []*image.RGBA, err error) {
defer func() {
if recv := recover(); recv != nil {
err = fmt.Errorf("error while decoding file: %s", recv)
}
}()
x, y := getArea(gif)
if width == 0 {
width = x
}
if height == 0 {
height = y
}
var images []*image.RGBA
for _, img := range gif.Image {
dst := image.NewRGBA(image.Rect(0, 0, width, height))
draw.Draw(dst, dst.Bounds(), img, image.Point{}, draw.Over)
new := dst
images = append(images, new)
}
return images, nil
}
func getArea(gif *gif.GIF) (x, y int) {
var xLow int
var xHigh int
var yLow int
var yHigh int
for _, img := range gif.Image {
if img.Rect.Min.X < xLow {
xLow = img.Rect.Min.X
}
if img.Rect.Min.Y < yLow {
yLow = img.Rect.Min.Y
}
if img.Rect.Max.X > xHigh {
xHigh = img.Rect.Max.X
}
if img.Rect.Max.Y > yHigh {
yHigh = img.Rect.Max.Y
}
}
return xHigh - xLow, yHigh - yLow
}