/
blur.go
88 lines (74 loc) · 1.95 KB
/
blur.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
package blur
import (
"encoding/json"
"errors"
"fmt"
"image"
"strconv"
"github.com/caddyserver/caddy/v2"
"github.com/disintegration/imaging"
imagefilter "github.com/ueffel/caddy-imagefilter"
)
// BlurFactory creates Blur instances.
type BlurFactory struct{}
// Blur produces a blurred version of the image.
type Blur struct {
Sigma string `json:"sigma,omitempty"`
}
// Name returns the name of the filter, which is also the directive used in the image filter block.
func (ff BlurFactory) Name() string { return "blur" }
// New initialises and returns a configured Blur instance.
// Syntax:
//
// blur [<sigma>]
//
// Parameters:
//
// sigma must be a positive floating point number and indicates how much the image will be blurred.
// Default is 1.
func (ff BlurFactory) New(args ...string) (imagefilter.Filter, error) {
if len(args) > 1 {
return nil, imagefilter.ErrTooManyArgs
}
var sigma string
if len(args) == 1 {
sigma = args[0]
}
return Blur{Sigma: sigma}, nil
}
// Unmarshal decodes JSON data and returns a Blur instance.
func (ff BlurFactory) Unmarshal(data []byte) (imagefilter.Filter, error) {
filter := Blur{}
err := json.Unmarshal(data, &filter)
if err != nil {
return nil, err
}
return filter, nil
}
// Apply applies the image filter to an image and returns the new image.
func (f Blur) Apply(repl *caddy.Replacer, img image.Image) (image.Image, error) {
var err error
var sigma float64
sigmaRepl := repl.ReplaceAll(f.Sigma, "")
if sigmaRepl == "" {
sigma = 1
} else {
sigma, err = strconv.ParseFloat(sigmaRepl, 64)
if err != nil {
return img, fmt.Errorf("invalid sigma: %w", err)
}
}
if sigma <= 0 {
return img, errors.New("invalid sigma: cannot be less or equal 0")
}
return imaging.Blur(img, sigma), nil
}
// init registers the image filter.
func init() {
imagefilter.Register(BlurFactory{})
}
// Interface guards.
var (
_ imagefilter.FilterFactory = (*BlurFactory)(nil)
_ imagefilter.Filter = (*Blur)(nil)
)