-
-
Notifications
You must be signed in to change notification settings - Fork 7.7k
/
Copy pathimages.go
211 lines (177 loc) · 5.15 KB
/
images.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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
// Copyright 2019 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package images provides template functions for manipulating images.
package images
import (
"errors"
"fmt"
"image"
"path"
"sync"
"github.com/bep/overlayfs"
"github.com/gohugoio/hugo/common/hashing"
"github.com/gohugoio/hugo/common/hugio"
"github.com/gohugoio/hugo/resources/images"
"github.com/gohugoio/hugo/resources/resource_factories/create"
"github.com/mitchellh/mapstructure"
"rsc.io/qr"
// Importing image codecs for image.DecodeConfig
_ "image/gif"
_ "image/jpeg"
_ "image/png"
// Import webp codec
_ "golang.org/x/image/webp"
"github.com/gohugoio/hugo/deps"
"github.com/spf13/afero"
"github.com/spf13/cast"
)
// New returns a new instance of the images-namespaced template functions.
func New(d *deps.Deps) *Namespace {
var readFileFs afero.Fs
// The docshelper script does not have or need all the dependencies set up.
if d.PathSpec != nil {
readFileFs = overlayfs.New(overlayfs.Options{
Fss: []afero.Fs{
d.PathSpec.BaseFs.Work,
d.PathSpec.BaseFs.Content.Fs,
},
})
}
return &Namespace{
readFileFs: readFileFs,
Filters: &images.Filters{},
cache: map[string]image.Config{},
deps: d,
createClient: create.New(d.ResourceSpec),
}
}
// Namespace provides template functions for the "images" namespace.
type Namespace struct {
*images.Filters
readFileFs afero.Fs
cacheMu sync.RWMutex
cache map[string]image.Config
deps *deps.Deps
createClient *create.Client
}
// Config returns the image.Config for the specified path relative to the
// working directory.
func (ns *Namespace) Config(path any) (image.Config, error) {
filename, err := cast.ToStringE(path)
if err != nil {
return image.Config{}, err
}
if filename == "" {
return image.Config{}, errors.New("config needs a filename")
}
// Check cache for image config.
ns.cacheMu.RLock()
config, ok := ns.cache[filename]
ns.cacheMu.RUnlock()
if ok {
return config, nil
}
f, err := ns.readFileFs.Open(filename)
if err != nil {
return image.Config{}, err
}
defer f.Close()
config, _, err = image.DecodeConfig(f)
if err != nil {
return config, err
}
ns.cacheMu.Lock()
ns.cache[filename] = config
ns.cacheMu.Unlock()
return config, nil
}
// Filter applies the given filters to the image given as the last element in args.
func (ns *Namespace) Filter(args ...any) (images.ImageResource, error) {
if len(args) < 2 {
return nil, errors.New("must provide an image and one or more filters")
}
img := args[len(args)-1].(images.ImageResource)
filtersv := args[:len(args)-1]
return img.Filter(filtersv...)
}
var qrErrorCorrectionLevels = map[string]qr.Level{
"low": qr.L,
"medium": qr.M,
"quartile": qr.Q,
"high": qr.H,
}
// QR encodes the given text into a QR code using the specified options,
// returning an image resource.
func (ns *Namespace) QR(args ...any) (images.ImageResource, error) {
const (
qrDefaultErrorCorrectionLevel = "medium"
qrDefaultScale = 4
)
opts := struct {
Level string // error correction level; one of low, medium, quartile, or high
Scale int // number of image pixels per QR code module
TargetDir string // target directory relative to publishDir
}{
Level: qrDefaultErrorCorrectionLevel,
Scale: qrDefaultScale,
}
if len(args) == 0 || len(args) > 2 {
return nil, errors.New("requires 1 or 2 arguments")
}
text, err := cast.ToStringE(args[0])
if err != nil {
return nil, err
}
if text == "" {
return nil, errors.New("cannot encode an empty string")
}
if len(args) == 2 {
err := mapstructure.WeakDecode(args[1], &opts)
if err != nil {
return nil, err
}
}
level, ok := qrErrorCorrectionLevels[opts.Level]
if !ok {
return nil, errors.New("error correction level must be one of low, medium, quartile, or high")
}
if opts.Scale < 2 {
return nil, errors.New("scale must be an integer greater than or equal to 2")
}
targetPath := path.Join(opts.TargetDir, fmt.Sprintf("qr_%s.png", hashing.HashStringHex(text, opts)))
r, err := ns.createClient.FromOpts(
create.Options{
TargetPath: targetPath,
TargetPathHasHash: true,
CreateContent: func() (func() (hugio.ReadSeekCloser, error), error) {
code, err := qr.Encode(text, level)
if err != nil {
return nil, err
}
code.Scale = opts.Scale
png := code.PNG()
return func() (hugio.ReadSeekCloser, error) {
return hugio.NewReadSeekerNoOpCloserFromBytes(png), nil
}, nil
},
},
)
if err != nil {
return nil, err
}
ir, ok := r.(images.ImageResource)
if !ok {
panic("bug: resource is not an image resource")
}
return ir, nil
}