forked from imgproxy/imgproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
watermark_data.go
75 lines (59 loc) · 1.82 KB
/
watermark_data.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
package main
import (
"bytes"
"context"
"encoding/base64"
"fmt"
"io/ioutil"
"os"
)
func watermarkData() ([]byte, imageType, context.CancelFunc, error) {
if len(conf.WatermarkData) > 0 {
data, imgtype, err := base64WatermarkData()
return data, imgtype, func() {}, err
}
if len(conf.WatermarkPath) > 0 {
data, imgtype, err := fileWatermarkData()
return data, imgtype, func() {}, err
}
if len(conf.WatermarkURL) > 0 {
return remoteWatermarkData()
}
return nil, imageTypeUnknown, func() {}, nil
}
func base64WatermarkData() ([]byte, imageType, error) {
data, err := base64.StdEncoding.DecodeString(conf.WatermarkData)
if err != nil {
return nil, imageTypeUnknown, fmt.Errorf("Can't decode watermark data: %s", err)
}
imgtype, err := checkTypeAndDimensions(bytes.NewReader(data))
if err != nil {
return nil, imageTypeUnknown, fmt.Errorf("Can't decode watermark: %s", err)
}
return data, imgtype, nil
}
func fileWatermarkData() ([]byte, imageType, error) {
f, err := os.Open(conf.WatermarkPath)
if err != nil {
return nil, imageTypeUnknown, fmt.Errorf("Can't read watermark: %s", err)
}
imgtype, err := checkTypeAndDimensions(f)
if err != nil {
return nil, imageTypeUnknown, fmt.Errorf("Can't decode watermark: %s", err)
}
// Return to the beginning of the file
f.Seek(0, 0)
data, err := ioutil.ReadAll(f)
if err != nil {
return nil, imageTypeUnknown, fmt.Errorf("Can't read watermark: %s", err)
}
return data, imgtype, nil
}
func remoteWatermarkData() ([]byte, imageType, context.CancelFunc, error) {
ctx := context.WithValue(context.Background(), imageURLCtxKey, conf.WatermarkURL)
ctx, cancel, err := downloadImage(ctx)
if err != nil {
return nil, imageTypeUnknown, cancel, fmt.Errorf("Can't download watermark: %s", err)
}
return getImageData(ctx).Bytes(), getImageType(ctx), cancel, err
}