This repository has been archived by the owner on Nov 23, 2018. It is now read-only.
/
image.go
197 lines (158 loc) · 4.27 KB
/
image.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
package server
import (
"crypto/sha1"
"encoding/hex"
"errors"
"fmt"
"strings"
"time"
"github.com/goware/go-metrics"
"github.com/goware/lg"
"github.com/pressly/imgry"
"github.com/pressly/imgry/imagick"
)
var (
EmptyImageKey = sha1Hash("")
ErrInvalidImageKey = errors.New("invalid image key")
)
// TODO: we should probably keep the Sizing as a url.Values and store it in the Hash value separately..
// then we can query for things... ie. find key, with whatever sizing props... etc..
type Image struct {
Key string `json:"key" redis:"key"`
SrcUrl string `json:"src_url" redis:"src"`
Width int `json:"width" redis:"w"`
Height int `json:"height" redis:"h"`
Format string `json:"format" redis:"f"`
SizingQuery string `json:"-" redis:"q"` // query from below, for saving
Sizing *imgry.Sizing `json:"-" redis:"-"`
Data []byte `json:"-" redis:"-"`
img imgry.Image
}
// Hrmm.. how will we generate a Uid if we just have a blob and no srcurl..?
// perhaps we allow the uid to be like "something.jpg" if they want..?
// unlikely to be collisions anyways...
// how to dedupe those..? guess we cant.. only if it was based on blob..
func NewImageFromKey(key string) *Image {
return &Image{Key: key}
}
func NewImageFromSrcUrl(srcUrl string) *Image {
return &Image{SrcUrl: srcUrl, Key: sha1Hash(srcUrl)}
}
func sha1Hash(in string) string {
hasher := sha1.New()
fmt.Fprintf(hasher, in)
return hex.EncodeToString(hasher.Sum(nil))
}
// Make sure to call Release() if methods LoadImage(), SizeIt()
// or MakeSize() are called.
func (im *Image) LoadImage() (err error) {
defer metrics.MeasureSince([]string{"fn.image.LoadImage"}, time.Now())
// TODO: throttle the number of images we load at a given time..
// this should be configurable...
defer func() {
if r := recover(); r != nil {
var ok bool
err, ok = r.(error)
if !ok {
err = fmt.Errorf("imgry: %v", r)
}
}
}()
var formatHint string
if im.SrcFileExtension() == "ico" {
formatHint = "ico"
}
ng := imagick.Engine{}
im.img, err = ng.LoadBlob(im.Data, formatHint)
if err != nil {
if err == imagick.ErrEngineFailure {
lg.Fatalf("**** ENGINE FAILURE on %s", im.SrcUrl)
}
return err
}
im.sync()
return nil
}
func (im *Image) SrcFilename() string {
fname := strings.Split(im.SrcUrl, "?")
fname = strings.Split(fname[0], "/")
return fname[len(fname)-1]
}
func (im *Image) SrcFileExtension() string {
parts := strings.Split(im.SrcFilename(), ".")
ext := strings.ToLower(parts[len(parts)-1])
return ext
}
func (im *Image) IsValidImage() bool {
return im.Width > 0 && im.Height > 0 && im.Format != ""
}
// Sizes the current image in place
func (im *Image) SizeIt(sizing *imgry.Sizing) error {
defer metrics.MeasureSince([]string{"fn.image.SizeIt"}, time.Now())
if err := im.ValidateKey(); err != nil {
return err
}
if im.img == nil {
if err := im.LoadImage(); err != nil {
return err
}
}
err := im.img.SizeIt(sizing)
if err != nil {
return fmt.Errorf("Error occurred when sizing an image: %s", err)
}
im.sync()
return nil
}
// Create a new blob object from an existing size
func (im *Image) MakeSize(sizing *imgry.Sizing) (*Image, error) {
defer metrics.MeasureSince([]string{"fn.image.MakeSize"}, time.Now())
if err := im.ValidateKey(); err != nil {
return nil, err
}
im2 := &Image{
Key: im.Key,
Data: im.Data,
SrcUrl: im.SrcUrl,
Sizing: sizing,
SizingQuery: sizing.ToQuery().Encode(),
}
// Clone the originating image
var err error
if err = im2.LoadImage(); err != nil {
return nil, err
}
// Resize the new image object
if err = im2.SizeIt(sizing); err != nil {
return nil, err
}
return im2, nil
}
func (im *Image) ValidateKey() error {
if im.Key == "" || im.Key == EmptyImageKey {
return ErrInvalidImageKey
}
return nil
}
func (im *Image) MimeType() string {
mt := MimeTypes[im.Format]
if mt == "" {
mt = "application/octet-stream"
}
return mt
}
func (im *Image) Release() {
if im == nil {
return
}
defer metrics.IncrCounter([]string{"fn.image.Release"}, 1)
if im.img != nil {
im.img.Release()
}
}
func (im *Image) sync() {
im.Width = im.img.Width()
im.Height = im.img.Height()
im.Format = im.img.Format()
im.Data = im.img.Data()
}