-
Notifications
You must be signed in to change notification settings - Fork 5
/
pngquant.go
61 lines (50 loc) · 1.02 KB
/
pngquant.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
package pngquant
import (
"bytes"
"fmt"
"image"
"image/png"
"os/exec"
"strconv"
"strings"
)
func Compress(input image.Image, speed string) (output image.Image, err error) {
if err = speedCheck(speed); err != nil {
return
}
var w bytes.Buffer
err = png.Encode(&w, input)
if err != nil {
return
}
b := w.Bytes()
compressed, err := CompressBytes(b, speed)
if err != nil {
return
}
output, err = png.Decode(bytes.NewReader(compressed))
return
}
func CompressBytes(input []byte, speed string) (output []byte, err error) {
cmd := exec.Command("pngquant", "-", "--speed", speed)
cmd.Stdin = strings.NewReader(string(input))
var o bytes.Buffer
cmd.Stdout = &o
err = cmd.Run()
if err != nil {
return
}
output = o.Bytes()
return
}
func speedCheck(speed string) (err error) {
// conversion, as an aside, also forces the speed argument to be a number.
speedInt, err := strconv.Atoi(speed)
if err != nil {
return
}
if speedInt > 10 {
return fmt.Errorf("speed cannot exceed value of 10")
}
return
}