-
Notifications
You must be signed in to change notification settings - Fork 7
/
option.go
78 lines (64 loc) · 1.87 KB
/
option.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
package imgconv
import (
"image"
"io"
"path/filepath"
)
const defaultOpacity = 128
var defaultFormat = &FormatOption{Format: JPEG}
// Options represents options that can be used to configure a image operation.
type Options struct {
Watermark *WatermarkOption
Resize *ResizeOption
Format *FormatOption
Gray bool
}
// NewOptions creates a new option with default setting.
func NewOptions() *Options {
return &Options{Format: defaultFormat}
}
// SetWatermark sets the value for the Watermark field.
func (opts *Options) SetWatermark(mark image.Image, opacity uint) *Options {
opts.Watermark = &WatermarkOption{Mark: mark}
if opacity == 0 {
opts.Watermark.Opacity = defaultOpacity
} else {
opts.Watermark.Opacity = uint8(opacity)
}
return opts
}
// SetResize sets the value for the Resize field.
func (opts *Options) SetResize(width, height int, percent float64) *Options {
opts.Resize = &ResizeOption{Width: width, Height: height, Percent: percent}
return opts
}
// SetFormat sets the value for the Format field.
func (opts *Options) SetFormat(f Format, options ...EncodeOption) *Options {
opts.Format = &FormatOption{f, options}
return opts
}
// SetGray sets the value for the Gray field.
func (opts *Options) SetGray(gray bool) *Options {
opts.Gray = gray
return opts
}
// Convert image according options opts.
func (opts *Options) Convert(w io.Writer, base image.Image) error {
if opts.Gray {
base = ToGray(base)
}
if opts.Resize != nil {
base = opts.Resize.do(base)
}
if opts.Watermark != nil {
base = opts.Watermark.do(base)
}
if opts.Format == nil {
opts.Format = defaultFormat
}
return opts.Format.Encode(w, base)
}
// ConvertExt convert filename's ext according image format.
func (opts *Options) ConvertExt(filename string) string {
return filename[0:len(filename)-len(filepath.Ext(filename))] + "." + formatExts[opts.Format.Format][0]
}