-
Notifications
You must be signed in to change notification settings - Fork 0
/
compress.go
80 lines (67 loc) · 1.8 KB
/
compress.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
package gifsicle
import (
"fmt"
"image/gif"
"io"
)
type Options struct {
// This parameter ranges from 0-200 (higher value -> more compression).
//
// This is the main compression parameter used in websites like ezgif!
Lossy uint
// Additional compression optimization.
OptimizeLevel OptimizeLevel
// Optional parameter to specify the number of colors (2-256) for the GIF
//
// Specifying less colors compresses the GIF more.
// If this is 0, gifsicle will default to using the image's color map.
NumColors uint
}
// Shortcut function to compress GIFs quickly and easily with gifsicle.
func Compress(w io.Writer, g *gif.GIF, o *Options) error {
gifsicleCli, err := NewGifsicle()
if err != nil {
return fmt.Errorf("NewGifsicle failed: %v", err)
}
if o != nil {
gifsicleCli.Lossy(o.Lossy)
gifsicleCli.OptimizeLevel(o.OptimizeLevel)
if o.NumColors >= 2 {
gifsicleCli.NumColors(o.NumColors)
}
}
return gifsicleCli.InputGif(g).Output(w).Run()
}
/*
Shortcut function to compress GIFs quickly and easily with gifsicle
using an io.Reader like a file or buffer.
Example:
testFilePath := path.Join("testfiles", "portrait_3mb.gif")
testFile, err := os.Open(testFilePath)
if err != nil {
return err
}
var buf bytes.Buffer
err = gifsicle.CompressFromReader(&buf, testFile, &gifsicle.Options{
Lossy: 200,
OptimizeLevel: gifsicle.OPTIMIZE_LEVEL_THREE,
NumColors: 256,
})
if err != nil {
return err
}
*/
func CompressFromReader(w io.Writer, r io.Reader, o *Options) error {
gifsicleCli, err := NewGifsicle()
if err != nil {
return fmt.Errorf("NewGifsicle failed: %v", err)
}
if o != nil {
gifsicleCli.Lossy(o.Lossy)
gifsicleCli.OptimizeLevel(o.OptimizeLevel)
if o.NumColors >= 2 {
gifsicleCli.NumColors(o.NumColors)
}
}
return gifsicleCli.Input(r).Output(w).Run()
}