-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenc.go
125 lines (112 loc) · 2.41 KB
/
enc.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
125
package main
import (
"fmt"
"image"
"image/draw"
"image/gif"
"image/jpeg"
"image/png"
"io"
"golang.org/x/image/tiff"
"github.com/cdillond/imgconv/pkg/utils"
"github.com/cdillond/imgconv/pkg/webpenc"
)
type EncodeCfg struct {
FileType utils.FileType
GifNumColors int
GifQuantizer draw.Quantizer
GifDrawer draw.Drawer
JpegQuality int
TiffCompType tiff.CompressionType
TiffPredictor bool
WebPLossy bool
WebPQuality uint
}
type EncodeOpt func(*EncodeCfg)
func NewEncodeCfg(fileType utils.FileType, opts ...EncodeOpt) EncodeCfg {
cfg := EncodeCfg{
FileType: fileType,
GifNumColors: 256,
GifQuantizer: nil,
GifDrawer: nil,
JpegQuality: 100,
TiffCompType: 0,
TiffPredictor: false,
WebPLossy: false,
WebPQuality: 100,
}
for _, opt := range opts {
opt(&cfg)
}
return cfg
}
// I think these constraints are enforced by the image package anyway, but might as well be safe...
func WithJpegQuality(n int) func(*EncodeCfg) {
return func(e *EncodeCfg) {
if n < 0 {
e.JpegQuality = 0
} else if n > 100 {
e.JpegQuality = 100
} else {
e.JpegQuality = n
}
}
}
func WithGifNumColors(n int) func(*EncodeCfg) {
return func(e *EncodeCfg) {
if n < 0 {
e.GifNumColors = 1
} else if n > 256 {
e.GifNumColors = 256
} else {
e.GifNumColors = n
}
}
}
func WithWebPLossy(l bool) func(*EncodeCfg) {
return func(e *EncodeCfg) {
e.WebPLossy = l
}
}
func WithWebPQual(u uint) func(*EncodeCfg) {
return func(e *EncodeCfg) {
if u > 100 {
e.WebPQuality = 100
} else {
e.WebPQuality = u
}
}
}
/*
TO DO
func WithGifQuantizer(q draw.Quantizer) func(*EncodeCfg) {
return func(e *EncodeCfg) {
e.GifQuantizer = q
}
}
*/
func Encode(img image.Image, w io.Writer, cfg EncodeCfg) error {
switch cfg.FileType {
case utils.GIF:
return gif.Encode(w, img, &gif.Options{
NumColors: cfg.GifNumColors,
Quantizer: cfg.GifQuantizer,
Drawer: cfg.GifDrawer})
case utils.JPEG:
return jpeg.Encode(w, img, &jpeg.Options{Quality: cfg.JpegQuality})
case utils.PNG:
return png.Encode(w, img)
case utils.TIFF:
return tiff.Encode(w, img, &tiff.Options{
Compression: cfg.TiffCompType,
Predictor: cfg.TiffPredictor})
case utils.WEBP:
return webpenc.EncodeWebP(w, img, webpenc.WebPOptions{IsLossy: cfg.WebPLossy, Quality: cfg.WebPQuality})
default:
return fmt.Errorf("unsupported file type")
}
}
/*
TODO
implement webp encoding in Go
*/