-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathdwebp.go
124 lines (99 loc) · 2.3 KB
/
dwebp.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
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
package webpbin
import (
"bytes"
"errors"
"image"
"image/png"
"io"
"github.com/nickalie/go-binwrapper"
)
// DWebP wraps dwebp tool used for decompression of WebP files into PNG.
// https://developers.google.com/speed/webp/docs/dwebp
type DWebP struct {
*binwrapper.BinWrapper
inputFile string
input io.Reader
outputFile string
output io.Writer
}
// NewDWebP creates new WebP instance
func NewDWebP(optionFuncs ...OptionFunc) *DWebP {
bin := &DWebP{
BinWrapper: createBinWrapper(optionFuncs...),
}
bin.ExecPath("dwebp")
return bin
}
// InputFile sets webp file to convert.
// Input or InputImage called before will be ignored.
func (c *DWebP) InputFile(file string) *DWebP {
c.input = nil
c.inputFile = file
return c
}
// Input sets reader to convert.
// InputFile or InputImage called before will be ignored.
func (c *DWebP) Input(reader io.Reader) *DWebP {
c.inputFile = ""
c.input = reader
return c
}
// OutputFile specify the name of the output image file.
// Output called before will be ignored.
func (c *DWebP) OutputFile(file string) *DWebP {
c.output = nil
c.outputFile = file
return c
}
// Output specify writer to write image file content.
// OutputFile called before will be ignored.
func (c *DWebP) Output(writer io.Writer) *DWebP {
c.outputFile = ""
c.output = writer
return c
}
// Version returns dwebp version.
func (c *DWebP) Version() (string, error) {
return version(c.BinWrapper)
}
// Run starts dwebp with specified parameters.
func (c *DWebP) Run() (image.Image, error) {
defer c.BinWrapper.Reset()
output, err := c.getOutput()
if err != nil {
return nil, err
}
c.Arg("-o", output)
err = c.setInput()
if err != nil {
return nil, err
}
if c.output != nil {
c.SetStdOut(c.output)
}
err = c.BinWrapper.Run()
if err != nil {
return nil, errors.New(err.Error() + ". " + string(c.StdErr()))
}
if c.output == nil && c.outputFile == "" {
return png.Decode(bytes.NewReader(c.BinWrapper.StdOut()))
}
return nil, nil
}
func (c *DWebP) setInput() error {
if c.input != nil {
c.Arg("--").Arg("-")
c.StdIn(c.input)
} else if c.inputFile != "" {
c.Arg(c.inputFile)
} else {
return errors.New("Undefined input")
}
return nil
}
func (c *DWebP) getOutput() (string, error) {
if c.outputFile != "" {
return c.outputFile, nil
}
return "-", nil
}