forked from DAddYE/vips
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vips.go
355 lines (303 loc) · 7.71 KB
/
vips.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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
package vips
/*
#cgo pkg-config: vips
#include "vips.h"
*/
import "C"
import (
"errors"
"fmt"
"math"
"net/http"
"os"
"runtime"
"unsafe"
)
const DEBUG = false
const (
JPEG_MIME = "image/jpeg"
WEBP_MIME = "image/webp"
PNG_MIME = "image/png"
)
type ImageType int
const (
UNKNOWN ImageType = iota
JPEG
WEBP
PNG
)
const QUALITY = 80
type Interpolator int
const (
BICUBIC Interpolator = iota
BILINEAR
NOHALO
)
type Extend int
const (
EXTEND_BLACK Extend = C.VIPS_EXTEND_BLACK
EXTEND_WHITE Extend = C.VIPS_EXTEND_WHITE
)
var interpolations = map[Interpolator]string{
BICUBIC: "bicubic",
BILINEAR: "bilinear",
NOHALO: "nohalo",
}
func (i Interpolator) String() string { return interpolations[i] }
type Options struct {
Height int
Width int
Crop bool
Enlarge bool
Extend Extend
Embed bool
Interpolator Interpolator
Gravity Gravity
Quality int
}
func init() {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
err := C.vips_initialize()
if err != 0 {
C.vips_shutdown()
panic("unable to start vips!")
}
C.vips_concurrency_set(1)
C.vips_cache_set_max_mem(100 * 1024 * 1024)
C.vips_cache_set_max(500)
}
func Debug() {
C.im__print_all()
}
func Resize(buf []byte, o Options) ([]byte, error) {
debug("%#+v", o)
// detect (if possible) the file type
typ := UNKNOWN
switch {
case http.DetectContentType(buf) == JPEG_MIME:
typ = JPEG
case http.DetectContentType(buf) == WEBP_MIME:
typ = WEBP
case http.DetectContentType(buf) == PNG_MIME:
typ = PNG
default:
return nil, errors.New("unknown image format")
}
// create an image instance
var image, tmpImage *C.struct__VipsImage
// feed it
imageLength := C.size_t(len(buf))
imageBuf := unsafe.Pointer(&buf[0])
switch typ {
case JPEG:
C.vips_jpegload_buffer_seq(imageBuf, imageLength, &image)
case WEBP:
C.vips_webpload_buffer_seq(imageBuf, imageLength, &image)
case PNG:
C.vips_pngload_buffer_seq(imageBuf, imageLength, &image)
}
defer C.vips_thread_shutdown()
// defaults
if o.Quality == 0 {
o.Quality = QUALITY
}
// get WxH
inWidth := int(image.Xsize)
inHeight := int(image.Ysize)
// prepare for factor
factor := 0.0
// image calculations
switch {
// Fixed width and height
case o.Width > 0 && o.Height > 0:
xf := float64(inWidth) / float64(o.Width)
yf := float64(inHeight) / float64(o.Height)
if o.Crop {
factor = math.Min(xf, yf)
} else {
factor = math.Max(xf, yf)
}
// Fixed width, auto height
case o.Width > 0:
factor = float64(inWidth) / float64(o.Width)
o.Height = int(math.Floor(float64(inHeight) / factor))
// Fixed height, auto width
case o.Height > 0:
factor = float64(inWidth) / float64(o.Height)
o.Width = int(math.Floor(float64(inWidth) / factor))
// Identity transform
default:
factor = 1
o.Width = inWidth
o.Height = inHeight
}
debug("transform from %dx%d to %dx%d", inWidth, inHeight, o.Width, o.Height)
// shrink
shrink := int(math.Floor(factor))
if shrink < 1 {
shrink = 1
}
// residual
residual := float64(shrink) / factor
// Do not enlarge the output if the input width *or* height are already less than the required dimensions
if !o.Enlarge {
if inWidth < o.Width && inHeight < o.Height {
factor = 1
shrink = 1
residual = 0
o.Width = inWidth
o.Height = inHeight
}
}
debug("factor: %v, shrink: %v, residual: %v", factor, shrink, residual)
// Try to use libjpeg shrink-on-load
shrinkOnLoad := 1
if typ == JPEG && shrink >= 2 {
switch {
case shrink >= 8:
factor = factor / 8
shrinkOnLoad = 8
case shrink >= 4:
factor = factor / 4
shrinkOnLoad = 4
case shrink >= 2:
factor = factor / 2
shrinkOnLoad = 2
}
}
if shrinkOnLoad > 1 {
debug("shrink on load %d", shrinkOnLoad)
// Recalculate integral shrink and double residual
factor = math.Max(factor, 1.0)
shrink = int(math.Floor(factor))
residual = float64(shrink) / factor
// Reload input using shrink-on-load
err := C.vips_jpegload_buffer_shrink(unsafe.Pointer(&buf[0]), C.size_t(len(buf)), &tmpImage, C.int(shrinkOnLoad))
C.g_object_unref(C.gpointer(image))
image = tmpImage
if err != 0 {
return nil, resizeError()
}
}
if shrink > 1 {
debug("shrink %d", shrink)
// Use vips_shrink with the integral reduction
err := C.vips_shrink_0(image, &tmpImage, C.double(float64(shrink)), C.double(float64(shrink)))
C.g_object_unref(C.gpointer(image))
image = tmpImage
if err != 0 {
return nil, resizeError()
}
// Recalculate residual float based on dimensions of required vs shrunk images
shrunkWidth := int(image.Xsize)
shrunkHeight := int(image.Ysize)
residualx := float64(o.Width) / float64(shrunkWidth)
residualy := float64(o.Height) / float64(shrunkHeight)
if o.Crop {
residual = math.Max(residualx, residualy)
} else {
residual = math.Min(residualx, residualy)
}
}
// Use vips_affine with the remaining float part
debug("residual: %v", residual)
if residual != 0 {
debug("residual %.2f", residual)
// Create interpolator - "bilinear" (default), "bicubic" or "nohalo"
is := C.CString(o.Interpolator.String())
interpolator := C.vips_interpolate_new(is)
// Perform affine transformation
err := C.vips_affine_interpolator(image, &tmpImage, C.double(residual), 0, 0, C.double(residual), interpolator)
C.g_object_unref(C.gpointer(image))
image = tmpImage
C.free(unsafe.Pointer(is))
if err != 0 {
return nil, resizeError()
}
}
// Crop/embed
affinedWidth := int(image.Xsize)
affinedHeight := int(image.Ysize)
if affinedWidth != o.Width || affinedHeight != o.Height {
if o.Crop {
// Crop
debug("cropping")
left, top := sharpCalcCrop(affinedWidth, affinedHeight, o.Width, o.Height, o.Gravity)
o.Width = int(math.Min(float64(affinedWidth), float64(o.Width)))
o.Height = int(math.Min(float64(affinedHeight), float64(o.Height)))
err := C.vips_extract_area_0(image, &tmpImage, C.int(left), C.int(top), C.int(o.Width), C.int(o.Height))
C.g_object_unref(C.gpointer(image))
image = tmpImage
if err != 0 {
return nil, resizeError()
}
} else if o.Embed {
debug("embedding with extend %d", o.Extend)
left := (o.Width - affinedWidth) / 2
top := (o.Height - affinedHeight) / 2
err := C.vips_embed_extend(image, &tmpImage, C.int(left), C.int(top), C.int(o.Width), C.int(o.Height), C.int(o.Extend))
C.g_object_unref(C.gpointer(image))
image = tmpImage
if err != 0 {
return nil, resizeError()
}
}
} else {
debug("canvased same as affined")
}
// Always convert to sRGB colour space
C.vips_colourspace_0(image, &tmpImage, C.VIPS_INTERPRETATION_sRGB)
C.g_object_unref(C.gpointer(image))
image = tmpImage
// Finally save
length := C.size_t(0)
var ptr unsafe.Pointer
C.vips_jpegsave_custom(image, &ptr, &length, 1, C.int(o.Quality), 0)
C.g_object_unref(C.gpointer(image))
// get back the buffer
buf = C.GoBytes(ptr, C.int(length))
// cleanup
C.g_free(C.gpointer(ptr))
C.vips_error_clear()
return buf, nil
}
func resizeError() error {
s := C.GoString(C.vips_error_buffer())
C.vips_error_clear()
C.vips_thread_shutdown()
return errors.New(s)
}
type Gravity int
const (
CENTRE Gravity = iota
NORTH
EAST
SOUTH
WEST
)
func sharpCalcCrop(inWidth, inHeight, outWidth, outHeight int, gravity Gravity) (int, int) {
left, top := 0, 0
switch gravity {
case NORTH:
left = (inWidth - outWidth + 1) / 2
case EAST:
left = inWidth - outWidth
top = (inHeight - outHeight + 1) / 2
case SOUTH:
left = (inWidth - outWidth + 1) / 2
top = inHeight - outHeight
case WEST:
top = (inHeight - outHeight + 1) / 2
default:
left = (inWidth - outWidth + 1) / 2
top = (inHeight - outHeight + 1) / 2
}
return left, top
}
func debug(format string, args ...interface{}) {
if !DEBUG {
return
}
fmt.Fprintf(os.Stderr, format+"\n", args...)
}