forked from perkeep/perkeep
/
image.go
264 lines (237 loc) · 6.71 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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
/*
Copyright 2011 Google Inc.
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 server
import (
"bytes"
"errors"
"fmt"
"image"
"image/jpeg"
"image/png"
"io"
"log"
"net/http"
"strings"
"time"
"camlistore.org/pkg/blobref"
"camlistore.org/pkg/blobserver"
"camlistore.org/pkg/images"
"camlistore.org/pkg/magic"
"camlistore.org/pkg/schema"
)
const imageDebug = false
type ImageHandler struct {
Fetcher blobref.StreamingFetcher
Cache blobserver.Storage // optional
MaxWidth, MaxHeight int
Square bool
sc ScaledImage // optional cache for scaled images
}
func (ih *ImageHandler) storageSeekFetcher() blobref.SeekFetcher {
return blobref.SeekerFromStreamingFetcher(ih.Fetcher) // TODO: pass ih.Cache?
}
type subImager interface {
SubImage(image.Rectangle) image.Image
}
func squareImage(i image.Image) image.Image {
si, ok := i.(subImager)
if !ok {
log.Fatalf("image %T isn't a subImager", i)
}
b := i.Bounds()
if b.Dx() > b.Dy() {
thin := (b.Dx() - b.Dy()) / 2
newB := b
newB.Min.X += thin
newB.Max.X -= thin
return si.SubImage(newB)
}
thin := (b.Dy() - b.Dx()) / 2
newB := b
newB.Min.Y += thin
newB.Max.Y -= thin
return si.SubImage(newB)
}
func (ih *ImageHandler) cache(tr io.Reader, name string) (*blobref.BlobRef, error) {
br, err := schema.WriteFileFromReader(ih.Cache, name, tr)
if err != nil {
return br, errors.New("failed to cache " + name + ": " + err.Error())
}
if imageDebug {
log.Printf("Image Cache: saved as %v\n", br)
}
return br, nil
}
// CacheScaled saves in the image handler's cache the scaled image read
// from tr, and puts its blobref in the scaledImage under the key name.
func (ih *ImageHandler) cacheScaled(tr io.Reader, name string) error {
br, err := ih.cache(tr, name)
if err != nil {
return err
}
ih.sc.Put(name, br)
return nil
}
// cached returns a FileReader for the given file schema blobref.
// The FileReader should be closed when done reading.
func (ih *ImageHandler) cached(fileRef *blobref.BlobRef) (*schema.FileReader, error) {
fetchSeeker := blobref.SeekerFromStreamingFetcher(ih.Cache)
fr, err := schema.NewFileReader(fetchSeeker, fileRef)
if err != nil {
return nil, err
}
if imageDebug {
log.Printf("Image Cache: hit: %v\n", fileRef)
}
return fr, nil
}
// Key format: "scaled:" + bref + ":" + width "x" + height
// where bref is the blobref of the unscaled image.
func cacheKey(bref string, width int, height int) string {
return fmt.Sprintf("scaled:%v:%dx%d", bref, width, height)
}
// ScaledCached reads the scaled version of the image in file,
// if it is in cache. On success, the image format is returned.
func (ih *ImageHandler) scaledCached(buf *bytes.Buffer, file *blobref.BlobRef) (format string, err error) {
name := cacheKey(file.String(), ih.MaxWidth, ih.MaxHeight)
br, err := ih.sc.Get(name)
if err != nil {
return format, fmt.Errorf("%v: %v", name, err)
}
fr, err := ih.cached(br)
if err != nil {
return format, fmt.Errorf("No cache hit for %v: %v", br, err)
}
defer fr.Close()
_, err = io.Copy(buf, fr)
if err != nil {
return format, fmt.Errorf("error reading cached thumbnail %v: %v", name, err)
}
mime := magic.MimeType(buf.Bytes())
if mime == "" {
return format, fmt.Errorf("error with cached thumbnail %v: unknown mime type", name)
}
pieces := strings.Split(mime, "/")
if len(pieces) < 2 {
return format, fmt.Errorf("error with cached thumbnail %v: bogus mime type", name)
}
if pieces[0] != "image" {
return format, fmt.Errorf("error with cached thumbnail %v: not an image", name)
}
return pieces[1], nil
}
func (ih *ImageHandler) scaleImage(buf *bytes.Buffer, file *blobref.BlobRef) (format string, err error) {
fr, err := schema.NewFileReader(ih.storageSeekFetcher(), file)
if err != nil {
return format, err
}
defer fr.Close()
_, err = io.Copy(buf, fr)
if err != nil {
return format, fmt.Errorf("image resize: error reading image %s: %v", file, err)
}
i, imConfig, err := images.Decode(bytes.NewReader(buf.Bytes()),
&images.DecodeOpts{MaxWidth: ih.MaxWidth, MaxHeight: ih.MaxHeight})
if err != nil {
return format, err
}
b := i.Bounds()
useBytesUnchanged := !imConfig.Modified
isSquare := b.Dx() == b.Dy()
if ih.Square && !isSquare {
useBytesUnchanged = false
i = squareImage(i)
b = i.Bounds()
}
if !useBytesUnchanged {
// Encode as a new image
buf.Reset()
switch format {
case "jpeg":
err = jpeg.Encode(buf, i, nil)
default:
err = png.Encode(buf, i)
}
if err != nil {
return format, err
}
}
return format, nil
}
func (ih *ImageHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request, file *blobref.BlobRef) {
if req.Method != "GET" && req.Method != "HEAD" {
http.Error(rw, "Invalid method", 400)
return
}
mw, mh := ih.MaxWidth, ih.MaxHeight
if mw == 0 || mh == 0 || mw > 2000 || mh > 2000 {
http.Error(rw, "bogus dimensions", 400)
return
}
if req.Header.Get("If-Modified-Since") != "" {
// Immutable, so any copy's a good copy.
rw.WriteHeader(http.StatusNotModified)
return
}
var buf bytes.Buffer
var err error
format := ""
cacheHit := false
if ih.sc != nil {
format, err = ih.scaledCached(&buf, file)
if err != nil {
log.Printf("image resize: %v", err)
} else {
cacheHit = true
}
}
if !cacheHit {
format, err = ih.scaleImage(&buf, file)
if err != nil {
http.Error(rw, err.Error(), 500)
return
}
if ih.sc != nil {
name := cacheKey(file.String(), mw, mh)
bufcopy := buf.Bytes()
err = ih.cacheScaled(bytes.NewBuffer(bufcopy), name)
if err != nil {
log.Printf("image resize: %v", err)
}
}
}
h := rw.Header()
h.Set("Expires", time.Now().Add(oneYear).Format(http.TimeFormat))
h.Set("Last-Modified", time.Now().Format(http.TimeFormat))
h.Set("Content-Type", imageContentTypeOfFormat(format))
size := buf.Len()
h.Set("Content-Length", fmt.Sprintf("%d", size))
if req.Method == "GET" {
n, err := io.Copy(rw, &buf)
if err != nil {
log.Printf("error serving thumbnail of file schema %s: %v", file, err)
return
}
if n != int64(size) {
log.Printf("error serving thumbnail of file schema %s: sent %d, expected size of %d",
file, n, size)
return
}
}
}
func imageContentTypeOfFormat(format string) string {
if format == "jpeg" {
return "image/jpeg"
}
return "image/png"
}