-
Notifications
You must be signed in to change notification settings - Fork 35
/
gif.go
82 lines (74 loc) · 1.84 KB
/
gif.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
78
79
80
81
82
package magick
// #include <stdlib.h>
// extern void * gif_encode(void *im, int single, int *size);
// #cgo LDFLAGS: -lgif
import "C"
import (
"bytes"
"errors"
"fmt"
"os/exec"
"unsafe"
)
var (
gifsicleCmd string
errNoGifsicle = errors.New("error decoding GIF image: Corrupt data. Install gifsicle to try to fix it.")
errCouldNotEncodeGif = errors.New("error encoding GIF")
maxGifTries = 1
)
func looksLikeGif(data []byte) bool {
return bytes.HasPrefix(data, []byte{'G', 'I', 'F'})
}
func runGifsicle(data []byte, args []string) ([]byte, error) {
cmd := exec.Command(gifsicleCmd, args...)
cmd.Stdin = bytes.NewReader(data)
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
return nil, fmt.Errorf("error running gifsicle: %s", err)
}
return out.Bytes(), nil
}
func fixAndDecodeGif(data []byte, try int) (*Image, error) {
if gifsicleCmd == "" {
return nil, errNoGifsicle
}
args := []string{"--careful", "--unoptimize", "--colors=256"}
data, err := runGifsicle(data, args)
if err != nil {
return nil, err
}
return decodeData(data, try+1)
}
// GifEncode encodes the Image as GIF using giflib
// rather than ImageMagick or GraphicksMagick. While this
// will result in a lower quality GIF, encoding is 9-10x
// faster and produces files ~20% smaller.
func (im *Image) GifEncode() ([]byte, error) {
if !im.coalesced {
coalesced, err := im.Coalesce()
if err != nil {
return nil, err
}
coalesced.parent = im.parent
defer coalesced.Dispose()
im = coalesced
}
var size C.int
var single C.int
if im.parent != nil {
single = 1
}
res := C.gif_encode(unsafe.Pointer(im.image), single, &size)
if res != nil {
p := unsafe.Pointer(res)
b := C.GoBytes(p, size)
C.free(p)
return b, nil
}
return nil, errCouldNotEncodeGif
}
func init() {
gifsicleCmd, _ = exec.LookPath("gifsicle")
}