forked from pirsipy/cdn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
magick.lua
574 lines (552 loc) · 16 KB
/
magick.lua
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
local VERSION = "1.0.0"
local ffi = require("ffi")
ffi.cdef([[ typedef void MagickWand;
typedef void PixelWand;
typedef int MagickBooleanType;
typedef int ExceptionType;
typedef int ssize_t;
typedef int CompositeOperator;
typedef int GravityType;
void MagickWandGenesis();
MagickWand* NewMagickWand();
MagickWand* DestroyMagickWand(MagickWand*);
MagickBooleanType MagickReadImage(MagickWand*, const char*);
MagickBooleanType MagickReadImageBlob(MagickWand*, const void*, const size_t);
const char* MagickGetException(const MagickWand*, ExceptionType*);
int MagickGetImageWidth(MagickWand*);
int MagickGetImageHeight(MagickWand*);
MagickBooleanType MagickAddImage(MagickWand*, const MagickWand*);
MagickBooleanType MagickAdaptiveResizeImage(MagickWand*, const size_t, const size_t);
MagickBooleanType MagickWriteImage(MagickWand*, const char*);
unsigned char* MagickGetImageBlob(MagickWand*, size_t*);
void* MagickRelinquishMemory(void*);
MagickBooleanType MagickCropImage(MagickWand*,
const size_t, const size_t, const ssize_t, const ssize_t);
MagickBooleanType MagickBlurImage(MagickWand*, const double, const double);
MagickBooleanType MagickSetImageFormat(MagickWand* wand, const char* format);
const char* MagickGetImageFormat(MagickWand* wand);
size_t MagickGetImageCompressionQuality(MagickWand * wand);
MagickBooleanType MagickSetImageCompressionQuality(MagickWand *wand,
const size_t quality);
MagickBooleanType MagickSharpenImage(MagickWand *wand,
const double radius,const double sigma);
MagickBooleanType MagickScaleImage(MagickWand *wand,
const size_t columns,const size_t rows);
MagickBooleanType MagickSetOption(MagickWand *,const char *,const char *);
char* MagickGetOption(MagickWand *,const char *);
MagickBooleanType MagickCompositeImage(MagickWand *wand,
const MagickWand *source_wand,const CompositeOperator compose,
const ssize_t x,const ssize_t y);
GravityType MagickGetImageGravity(MagickWand *wand);
MagickBooleanType MagickSetImageGravity(MagickWand *wand,
const GravityType gravity);
MagickBooleanType MagickStripImage(MagickWand *wand);
MagickBooleanType MagickGetImagePixelColor(MagickWand *wand,
const ssize_t x,const ssize_t y,PixelWand *color);
PixelWand *NewPixelWand(void);
PixelWand *DestroyPixelWand(PixelWand *);
double PixelGetAlpha(const PixelWand *);
double PixelGetRed(const PixelWand *);
double PixelGetGreen(const PixelWand *);
double PixelGetBlue(const PixelWand *);
]])
local get_flags
get_flags = function()
local proc = io.popen("MagickWand-config --cflags --libs", "r")
local flags = proc:read("*a")
get_flags = function()
return flags
end
proc:close()
return flags
end
local get_filters
get_filters = function()
local fname = "magick/resample.h"
local prefixes = {
"/usr/include/ImageMagick",
"/usr/local/include/ImageMagick",
function()
return get_flags():match("-I([^%s]+)")
end
}
for _index_0 = 1, #prefixes do
local _continue_0 = false
repeat
local p = prefixes[_index_0]
if "function" == type(p) then
p = p()
if not (p) then
_continue_0 = true
break
end
end
local full = tostring(p) .. "/" .. tostring(fname)
do
local f = io.open(full)
if f then
local content
do
local _with_0 = f:read("*a")
f:close()
content = _with_0
end
local filter_types = content:match("(typedef enum.-FilterTypes;)")
if filter_types then
ffi.cdef(filter_types)
return true
end
end
end
_continue_0 = true
until true
if not _continue_0 then
break
end
end
return false
end
local try_to_load
try_to_load = function(...)
local out
local _list_0 = {
...
}
for _index_0 = 1, #_list_0 do
local _continue_0 = false
repeat
local name = _list_0[_index_0]
if "function" == type(name) then
name = name()
if not (name) then
_continue_0 = true
break
end
end
if pcall(function()
out = ffi.load(name)
end) then
return out
end
_continue_0 = true
until true
if not _continue_0 then
break
end
end
return error("Failed to load ImageMagick (" .. tostring(...) .. ")")
end
local lib = try_to_load("MagickWand", function()
local lname = get_flags():match("-l(MagickWand[^%s]*)")
local suffix
if ffi.os == "OSX" then
suffix = ".dylib"
elseif ffi.os == "Windows" then
suffix = ".dll"
else
suffix = ".so"
end
return lname and "lib" .. lname .. suffix
end)
local can_resize
if get_filters() then
ffi.cdef([[ MagickBooleanType MagickResizeImage(MagickWand*,
const size_t, const size_t,
const FilterTypes, const double);
]])
can_resize = true
end
local composite_op = {
["UndefinedCompositeOp"] = 0,
["NoCompositeOp"] = 1,
["ModulusAddCompositeOp"] = 2,
["AtopCompositeOp"] = 3,
["BlendCompositeOp"] = 4,
["BumpmapCompositeOp"] = 5,
["ChangeMaskCompositeOp"] = 6,
["ClearCompositeOp"] = 7,
["ColorBurnCompositeOp"] = 8,
["ColorDodgeCompositeOp"] = 9,
["ColorizeCompositeOp"] = 10,
["CopyBlackCompositeOp"] = 11,
["CopyBlueCompositeOp"] = 12,
["CopyCompositeOp"] = 13,
["CopyCyanCompositeOp"] = 14,
["CopyGreenCompositeOp"] = 15,
["CopyMagentaCompositeOp"] = 16,
["CopyOpacityCompositeOp"] = 17,
["CopyRedCompositeOp"] = 18,
["CopyYellowCompositeOp"] = 19,
["DarkenCompositeOp"] = 20,
["DstAtopCompositeOp"] = 21,
["DstCompositeOp"] = 22,
["DstInCompositeOp"] = 23,
["DstOutCompositeOp"] = 24,
["DstOverCompositeOp"] = 25,
["DifferenceCompositeOp"] = 26,
["DisplaceCompositeOp"] = 27,
["DissolveCompositeOp"] = 28,
["ExclusionCompositeOp"] = 29,
["HardLightCompositeOp"] = 30,
["HueCompositeOp"] = 31,
["InCompositeOp"] = 32,
["LightenCompositeOp"] = 33,
["LinearLightCompositeOp"] = 34,
["LuminizeCompositeOp"] = 35,
["MinusDstCompositeOp"] = 36,
["ModulateCompositeOp"] = 37,
["MultiplyCompositeOp"] = 38,
["OutCompositeOp"] = 39,
["OverCompositeOp"] = 40,
["OverlayCompositeOp"] = 41,
["PlusCompositeOp"] = 42,
["ReplaceCompositeOp"] = 43,
["SaturateCompositeOp"] = 44,
["ScreenCompositeOp"] = 45,
["SoftLightCompositeOp"] = 46,
["SrcAtopCompositeOp"] = 47,
["SrcCompositeOp"] = 48,
["SrcInCompositeOp"] = 49,
["SrcOutCompositeOp"] = 50,
["SrcOverCompositeOp"] = 51,
["ModulusSubtractCompositeOp"] = 52,
["ThresholdCompositeOp"] = 53,
["XorCompositeOp"] = 54,
["DivideDstCompositeOp"] = 55,
["DistortCompositeOp"] = 56,
["BlurCompositeOp"] = 57,
["PegtopLightCompositeOp"] = 58,
["VividLightCompositeOp"] = 59,
["PinLightCompositeOp"] = 60,
["LinearDodgeCompositeOp"] = 61,
["LinearBurnCompositeOp"] = 62,
["MathematicsCompositeOp"] = 63,
["DivideSrcCompositeOp"] = 64,
["MinusSrcCompositeOp"] = 65,
["DarkenIntensityCompositeOp"] = 66,
["LightenIntensityCompositeOp"] = 67
}
local gravity_str = {
"ForgetGravity",
"NorthWestGravity",
"NorthGravity",
"NorthEastGravity",
"WestGravity",
"CenterGravity",
"EastGravity",
"SouthWestGravity",
"SouthGravity",
"SouthEastGravity",
"StaticGravity"
}
local gravity_type = { }
for i, t in ipairs(gravity_str) do
gravity_type[t] = i
end
lib.MagickWandGenesis()
local filter
filter = function(name)
return lib[name .. "Filter"]
end
local get_exception
get_exception = function(wand)
local etype = ffi.new("ExceptionType[1]", 0)
local msg = ffi.string(lib.MagickGetException(wand, etype))
return etype[0], msg
end
local handle_result
handle_result = function(img_or_wand, status)
local wand = img_or_wand.wand or img_or_wand
if status == 0 then
local code, msg = get_exception(wand)
return nil, msg, code
else
return true
end
end
local Image
do
local _base_0 = {
get_width = function(self)
return lib.MagickGetImageWidth(self.wand)
end,
get_height = function(self)
return lib.MagickGetImageHeight(self.wand)
end,
get_format = function(self)
return ffi.string(lib.MagickGetImageFormat(self.wand)):lower()
end,
set_format = function(self, format)
return handle_result(self, lib.MagickSetImageFormat(self.wand, format))
end,
get_quality = function(self)
return lib.MagickGetImageCompressionQuality(self.wand)
end,
set_quality = function(self, quality)
return handle_result(self, lib.MagickSetImageCompressionQuality(self.wand, quality))
end,
get_option = function(self, magick, key)
local format = magick .. ":" .. key
return ffi.string(lib.MagickGetOption(self.wand, format))
end,
set_option = function(self, magick, key, value)
local format = magick .. ":" .. key
return handle_result(self, lib.MagickSetOption(self.wand, format, value))
end,
get_gravity = function(self)
return gravity_str[lib.MagickGetImageGravity(self.wand)]
end,
set_gravity = function(self, typestr)
local type = gravity_type[typestr]
if not (type) then
error("invalid gravity type")
end
return lib.MagickSetImageGravity(self.wand, type)
end,
strip = function(self)
return lib.MagickStripImage(self.wand)
end,
_keep_aspect = function(self, w, h)
if not w and h then
return self:get_width() / self:get_height() * h, h
elseif w and not h then
return w, self:get_height() / self:get_width() * w
else
return w, h
end
end,
clone = function(self)
local wand = lib.NewMagickWand()
lib.MagickAddImage(wand, self.wand)
return Image(wand, self.path)
end,
resize = function(self, w, h, f, blur)
if f == nil then
f = "Lanczos2"
end
if blur == nil then
blur = 1.0
end
if not (can_resize) then
error("Failed to load filter list, can't resize")
end
w, h = self:_keep_aspect(w, h)
return handle_result(self, lib.MagickResizeImage(self.wand, w, h, filter(f), blur))
end,
adaptive_resize = function(self, w, h)
w, h = self:_keep_aspect(w, h)
return handle_result(self, lib.MagickAdaptiveResizeImage(self.wand, w, h))
end,
scale = function(self, w, h)
w, h = self:_keep_aspect(w, h)
return handle_result(self, lib.MagickScaleImage(self.wand, w, h))
end,
crop = function(self, w, h, x, y)
if x == nil then
x = 0
end
if y == nil then
y = 0
end
return handle_result(self, lib.MagickCropImage(self.wand, w, h, x, y))
end,
blur = function(self, sigma, radius)
if radius == nil then
radius = 0
end
return handle_result(self, lib.MagickBlurImage(self.wand, radius, sigma))
end,
sharpen = function(self, sigma, radius)
if radius == nil then
radius = 0
end
return handle_result(self, lib.MagickSharpenImage(self.wand, radius, sigma))
end,
composite = function(self, blob, x, y, opstr)
if opstr == nil then
opstr = "OverCompositeOp"
end
if type(blob) == "table" and blob.__class == Image then
blob = blob.wand
end
local op = composite_op[opstr]
if not (op) then
error("invalid operator type")
end
return handle_result(self, lib.MagickCompositeImage(self.wand, blob, op, x, y))
end,
resize_and_crop = function(self, w, h)
local src_w, src_h = self:get_width(), self:get_height()
local ar_src = src_w / src_h
local ar_dest = w / h
if ar_dest > ar_src then
local new_height = w / ar_src
self:resize(w, new_height)
return self:crop(w, h, 0, (new_height - h) / 2)
else
local new_width = h * ar_src
self:resize(new_width, h)
return self:crop(w, h, (new_width - w) / 2, 0)
end
end,
scale_and_crop = function(self, w, h)
local src_w, src_h = self:get_width(), self:get_height()
local ar_src = src_w / src_h
local ar_dest = w / h
if ar_dest > ar_src then
local new_height = w / ar_src
self:resize(w, new_height)
return self:scale(w, h)
else
local new_width = h * ar_src
self:resize(new_width, h)
return self:scale(w, h)
end
end,
get_blob = function(self)
local len = ffi.new("size_t[1]", 0)
local blob = lib.MagickGetImageBlob(self.wand, len)
do
local _with_0 = ffi.string(blob, len[0])
lib.MagickRelinquishMemory(blob)
return _with_0
end
end,
write = function(self, fname)
return handle_result(self, lib.MagickWriteImage(self.wand, fname))
end,
destroy = function(self)
if self.wand then
lib.DestroyMagickWand(self.wand)
end
self.wand = nil
if self.pixel_wand then
lib.DestroyPixelWand(self.pixel_wand)
self.pixel_wand = nil
end
end,
get_pixel = function(self, x, y)
self.pixel_wand = self.pixel_wand or lib.NewPixelWand()
assert(lib.MagickGetImagePixelColor(self.wand, x, y, self.pixel_wand), "failed to get pixel")
return lib.PixelGetRed(self.pixel_wand), lib.PixelGetGreen(self.pixel_wand), lib.PixelGetBlue(self.pixel_wand), lib.PixelGetAlpha(self.pixel_wand)
end,
__tostring = function(self)
return "Image<" .. tostring(self.path) .. ", " .. tostring(self.wand) .. ">"
end
}
_base_0.__index = _base_0
local _class_0 = setmetatable({
__init = function(self, wand, path)
self.wand, self.path = wand, path
end,
__base = _base_0,
__name = "Image"
}, {
__index = _base_0,
__call = function(cls, ...)
local _self_0 = setmetatable({}, _base_0)
cls.__init(_self_0, ...)
return _self_0
end
})
_base_0.__class = _class_0
Image = _class_0
end
local load_image
load_image = function(path)
local wand = lib.NewMagickWand()
if 0 == lib.MagickReadImage(wand, path) then
local code, msg = get_exception(wand)
lib.DestroyMagickWand(wand)
return nil, msg, code
end
return Image(wand, path)
end
local load_image_from_blob
load_image_from_blob = function(blob)
local wand = lib.NewMagickWand()
if 0 == lib.MagickReadImageBlob(wand, blob, #blob) then
local code, msg = get_exception(wand)
lib.DestroyMagickWand(wand)
return nil, msg, code
end
return Image(wand, "<from_blob>")
end
local tonumber = tonumber
local parse_size_str
parse_size_str = function(str, src_w, src_h)
local w, h, rest = str:match("^(%d*%%?)x(%d*%%?)(.*)$")
if not w then
return nil, "failed to parse string (" .. tostring(str) .. ")"
end
do
local p = w:match("(%d+)%%")
if p then
w = tonumber(p) / 100 * src_w
else
w = tonumber(w)
end
end
do
local p = h:match("(%d+)%%")
if p then
h = tonumber(p) / 100 * src_h
else
h = tonumber(h)
end
end
local center_crop = rest:match("#") and true
local crop_x, crop_y = rest:match("%+(%d+)%+(%d+)")
if crop_x then
crop_x = tonumber(crop_x)
crop_y = tonumber(crop_y)
else
if w and h and not center_crop then
if not (rest:match("!")) then
if src_w / src_h > w / h then
h = nil
else
w = nil
end
end
end
end
return {
w = w,
h = h,
crop_x = crop_x,
crop_y = crop_y,
center_crop = center_crop
}
end
local thumb
thumb = function(img, size_str, output)
if type(img) == "string" then
img = assert(load_image(img))
end
local src_w, src_h = img:get_width(), img:get_height()
local opts = parse_size_str(size_str, src_w, src_h)
if opts.center_crop then
img:resize_and_crop(opts.w, opts.h)
elseif opts.crop_x then
img:crop(opts.w, opts.h, opts.crop_x, opts.crop_y)
else
img:resize(opts.w, opts.h)
end
local ret
if output then
ret = img:write(output)
else
ret = img:get_blob()
end
img:destroy()
return ret
end
return {
load_image = load_image,
load_image_from_blob = load_image_from_blob,
thumb = thumb,
Image = Image,
parse_size_str = parse_size_str,
VERSION = VERSION
}