-
Notifications
You must be signed in to change notification settings - Fork 166
/
Copy pathmapnik_image.cpp
4248 lines (3921 loc) · 139 KB
/
mapnik_image.cpp
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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// mapnik
#include <mapnik/color.hpp> // for color
#include <mapnik/image.hpp> // for image types
#include <mapnik/image_any.hpp> // for image_any
#include <mapnik/image_reader.hpp> // for get_image_reader, etc
#include <mapnik/image_util.hpp> // for save_to_string, guess_type, etc
#include <mapnik/image_copy.hpp>
#include <mapnik/image_compositing.hpp>
#include <mapnik/image_filter_types.hpp>
#include <mapnik/image_filter.hpp> // filter_visitor
#include <mapnik/image_scaling.hpp>
#include <mapnik/marker.hpp>
#include <mapnik/marker_cache.hpp>
#include <mapnik/svg/svg_parser.hpp>
#include <mapnik/svg/svg_storage.hpp>
#include <mapnik/svg/svg_converter.hpp>
#include <mapnik/svg/svg_path_adapter.hpp>
#include <mapnik/svg/svg_path_attributes.hpp>
#include <mapnik/svg/svg_path_adapter.hpp>
#include <mapnik/svg/svg_renderer_agg.hpp>
#include <mapnik/svg/svg_path_attributes.hpp>
#include "mapnik_image.hpp"
#include "mapnik_image_view.hpp"
#include "mapnik_palette.hpp"
#include "mapnik_color.hpp"
#include "utils.hpp"
#include "agg_rasterizer_scanline_aa.h"
#include "agg_basics.h"
#include "agg_rendering_buffer.h"
#include "agg_renderer_base.h"
#include "agg_pixfmt_rgba.h"
#include "agg_scanline_u.h"
// boost
#include <boost/optional/optional.hpp>
// std
#include <exception>
#include <ostream> // for operator<<, basic_ostream
#include <sstream> // for basic_ostringstream, etc
#include <cstdlib>
Nan::Persistent<v8::FunctionTemplate> Image::constructor;
/**
* **`mapnik.Image`**
*
* Create a new image object (surface) that can be used for rendering data to.
* @class Image
* @param {number} width - width in pixels
* @param {number} height - height in pixels
* @param {Object} [options]
* @param {Object<mapnik.imageType>} [options.type=mapnik.imageType.rgb8] - a {@link mapnik.imageType} object
* @param {boolean} [options.initialize=true]
* @param {boolean} [options.premultiplied=false]
* @param {boolean} [options.painted=false]
* @property {number} offset - offset number
* @property {number} scaling - scaling number
* @throws {TypeError} if any argument is the wrong type, like if width
* or height is not numeric.
* @example
* var im = new mapnik.Image(256, 256, {
* premultiplied: true,
* type: mapnik.imageType.gray8
* });
*/
void Image::Initialize(v8::Local<v8::Object> target) {
Nan::HandleScope scope;
v8::Local<v8::FunctionTemplate> lcons = Nan::New<v8::FunctionTemplate>(Image::New);
lcons->InstanceTemplate()->SetInternalFieldCount(1);
lcons->SetClassName(Nan::New("Image").ToLocalChecked());
Nan::SetPrototypeMethod(lcons, "getType", getType);
Nan::SetPrototypeMethod(lcons, "getPixel", getPixel);
Nan::SetPrototypeMethod(lcons, "setPixel", setPixel);
Nan::SetPrototypeMethod(lcons, "encodeSync", encodeSync);
Nan::SetPrototypeMethod(lcons, "encode", encode);
Nan::SetPrototypeMethod(lcons, "view", view);
Nan::SetPrototypeMethod(lcons, "saveSync", saveSync);
Nan::SetPrototypeMethod(lcons, "save", save);
Nan::SetPrototypeMethod(lcons, "setGrayScaleToAlpha", setGrayScaleToAlpha);
Nan::SetPrototypeMethod(lcons, "width", width);
Nan::SetPrototypeMethod(lcons, "height", height);
Nan::SetPrototypeMethod(lcons, "painted", painted);
Nan::SetPrototypeMethod(lcons, "composite", composite);
Nan::SetPrototypeMethod(lcons, "filter", filter);
Nan::SetPrototypeMethod(lcons, "filterSync", filterSync);
Nan::SetPrototypeMethod(lcons, "fillSync", fillSync);
Nan::SetPrototypeMethod(lcons, "fill", fill);
Nan::SetPrototypeMethod(lcons, "premultiplySync", premultiplySync);
Nan::SetPrototypeMethod(lcons, "premultiply", premultiply);
Nan::SetPrototypeMethod(lcons, "premultiplied", premultiplied);
Nan::SetPrototypeMethod(lcons, "demultiplySync", demultiplySync);
Nan::SetPrototypeMethod(lcons, "demultiply", demultiply);
Nan::SetPrototypeMethod(lcons, "clear", clear);
Nan::SetPrototypeMethod(lcons, "clearSync", clearSync);
Nan::SetPrototypeMethod(lcons, "compare", compare);
Nan::SetPrototypeMethod(lcons, "isSolid", isSolid);
Nan::SetPrototypeMethod(lcons, "isSolidSync", isSolidSync);
Nan::SetPrototypeMethod(lcons, "copy", copy);
Nan::SetPrototypeMethod(lcons, "copySync", copySync);
Nan::SetPrototypeMethod(lcons, "resize", resize);
Nan::SetPrototypeMethod(lcons, "resizeSync", resizeSync);
Nan::SetPrototypeMethod(lcons, "data", data);
// properties
ATTR(lcons, "scaling", get_scaling, set_scaling);
ATTR(lcons, "offset", get_offset, set_offset);
// This *must* go after the ATTR setting
Nan::SetMethod(lcons->GetFunction().As<v8::Object>(),
"open",
Image::open);
Nan::SetMethod(lcons->GetFunction().As<v8::Object>(),
"fromBytes",
Image::fromBytes);
Nan::SetMethod(lcons->GetFunction().As<v8::Object>(),
"openSync",
Image::openSync);
Nan::SetMethod(lcons->GetFunction().As<v8::Object>(),
"fromBytesSync",
Image::fromBytesSync);
Nan::SetMethod(lcons->GetFunction().As<v8::Object>(),
"fromBufferSync",
Image::fromBufferSync);
Nan::SetMethod(lcons->GetFunction().As<v8::Object>(),
"fromSVG",
Image::fromSVG);
Nan::SetMethod(lcons->GetFunction().As<v8::Object>(),
"fromSVGSync",
Image::fromSVGSync);
Nan::SetMethod(lcons->GetFunction().As<v8::Object>(),
"fromSVGBytes",
Image::fromSVGBytes);
Nan::SetMethod(lcons->GetFunction().As<v8::Object>(),
"fromSVGBytesSync",
Image::fromSVGBytesSync);
target->Set(Nan::New("Image").ToLocalChecked(),lcons->GetFunction());
constructor.Reset(lcons);
}
Image::Image(unsigned int width, unsigned int height, mapnik::image_dtype type, bool initialized, bool premultiplied, bool painted) :
Nan::ObjectWrap(),
this_(std::make_shared<mapnik::image_any>(width,height,type,initialized,premultiplied,painted))
{
}
Image::Image(image_ptr _this) :
Nan::ObjectWrap(),
this_(_this)
{
}
Image::~Image()
{
}
NAN_METHOD(Image::New)
{
if (!info.IsConstructCall())
{
Nan::ThrowError("Cannot call constructor as function, you need to use 'new' keyword");
return;
}
if (info[0]->IsExternal())
{
v8::Local<v8::External> ext = info[0].As<v8::External>();
void* ptr = ext->Value();
Image* im = static_cast<Image*>(ptr);
im->Wrap(info.This());
info.GetReturnValue().Set(info.This());
return;
}
if (info.Length() >= 2)
{
mapnik::image_dtype type = mapnik::image_dtype_rgba8;
bool initialize = true;
bool premultiplied = false;
bool painted = false;
if (!info[0]->IsNumber() || !info[1]->IsNumber())
{
Nan::ThrowTypeError("Image 'width' and 'height' must be a integers");
return;
}
if (info.Length() >= 3)
{
if (info[2]->IsObject())
{
v8::Local<v8::Object> options = v8::Local<v8::Object>::Cast(info[2]);
if (options->Has(Nan::New("type").ToLocalChecked()))
{
v8::Local<v8::Value> init_val = options->Get(Nan::New("type").ToLocalChecked());
if (!init_val.IsEmpty() && init_val->IsNumber())
{
int int_val = init_val->IntegerValue();
if (int_val >= mapnik::image_dtype::IMAGE_DTYPE_MAX || int_val < 0)
{
Nan::ThrowTypeError("Image 'type' must be a valid image type");
return;
}
type = static_cast<mapnik::image_dtype>(init_val->IntegerValue());
}
else
{
Nan::ThrowTypeError("'type' option must be a valid 'mapnik.imageType'");
return;
}
}
if (options->Has(Nan::New("initialize").ToLocalChecked()))
{
v8::Local<v8::Value> init_val = options->Get(Nan::New("initialize").ToLocalChecked());
if (!init_val.IsEmpty() && init_val->IsBoolean())
{
initialize = init_val->BooleanValue();
}
else
{
Nan::ThrowTypeError("initialize option must be a boolean");
return;
}
}
if (options->Has(Nan::New("premultiplied").ToLocalChecked()))
{
v8::Local<v8::Value> pre_val = options->Get(Nan::New("premultiplied").ToLocalChecked());
if (!pre_val.IsEmpty() && pre_val->IsBoolean())
{
premultiplied = pre_val->BooleanValue();
}
else
{
Nan::ThrowTypeError("premultiplied option must be a boolean");
return;
}
}
if (options->Has(Nan::New("painted").ToLocalChecked()))
{
v8::Local<v8::Value> painted_val = options->Get(Nan::New("painted").ToLocalChecked());
if (!painted_val.IsEmpty() && painted_val->IsBoolean())
{
painted = painted_val->BooleanValue();
}
else
{
Nan::ThrowTypeError("painted option must be a boolean");
return;
}
}
}
else
{
Nan::ThrowTypeError("Options parameter must be an object");
return;
}
}
try {
Image* im = new Image(info[0]->IntegerValue(),
info[1]->IntegerValue(),
type,
initialize,
premultiplied,
painted);
im->Wrap(info.This());
info.GetReturnValue().Set(info.This());
} catch (std::exception const& ex) {
Nan::ThrowError(ex.what());
}
return;
}
else
{
Nan::ThrowError("please provide at least Image width and height");
return;
}
return;
}
/**
* Determine the image type
*
* @name getType
* @instance
* @returns {number} Number of the image type
* @memberof Image
* @example
* var img = new mapnik.Image(256, 256, {
* type: mapnik.imageType.gray8
* });
* var type = img.getType();
* var typeCheck = mapnik.imageType.gray8;
* console.log(type, typeCheck); // 1, 1
*/
NAN_METHOD(Image::getType)
{
Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder());
unsigned type = im->this_->get_dtype();
info.GetReturnValue().Set(Nan::New<v8::Number>(type));
}
struct visitor_get_pixel
{
visitor_get_pixel(int x, int y)
: x_(x), y_(y) {}
v8::Local<v8::Value> operator() (mapnik::image_null const&)
{
// This should never be reached because the width and height of 0 for a null
// image will prevent the visitor from being called.
/* LCOV_EXCL_START */
Nan::EscapableHandleScope scope;
return scope.Escape(Nan::Undefined());
/* LCOV_EXCL_STOP */
}
v8::Local<v8::Value> operator() (mapnik::image_gray8 const& data)
{
Nan::EscapableHandleScope scope;
std::uint32_t val = mapnik::get_pixel<std::uint32_t>(data, x_, y_);
return scope.Escape(Nan::New<v8::Uint32>(val));
}
v8::Local<v8::Value> operator() (mapnik::image_gray8s const& data)
{
Nan::EscapableHandleScope scope;
std::int32_t val = mapnik::get_pixel<std::int32_t>(data, x_, y_);
return scope.Escape(Nan::New<v8::Int32>(val));
}
v8::Local<v8::Value> operator() (mapnik::image_gray16 const& data)
{
Nan::EscapableHandleScope scope;
std::uint32_t val = mapnik::get_pixel<std::uint32_t>(data, x_, y_);
return scope.Escape(Nan::New<v8::Uint32>(val));
}
v8::Local<v8::Value> operator() (mapnik::image_gray16s const& data)
{
Nan::EscapableHandleScope scope;
std::int32_t val = mapnik::get_pixel<std::int32_t>(data, x_, y_);
return scope.Escape(Nan::New<v8::Int32>(val));
}
v8::Local<v8::Value> operator() (mapnik::image_gray32 const& data)
{
Nan::EscapableHandleScope scope;
std::uint32_t val = mapnik::get_pixel<std::uint32_t>(data, x_, y_);
return scope.Escape(Nan::New<v8::Uint32>(val));
}
v8::Local<v8::Value> operator() (mapnik::image_gray32s const& data)
{
Nan::EscapableHandleScope scope;
std::int32_t val = mapnik::get_pixel<std::int32_t>(data, x_, y_);
return scope.Escape(Nan::New<v8::Int32>(val));
}
v8::Local<v8::Value> operator() (mapnik::image_gray32f const& data)
{
Nan::EscapableHandleScope scope;
double val = mapnik::get_pixel<double>(data, x_, y_);
return scope.Escape(Nan::New<v8::Number>(val));
}
v8::Local<v8::Value> operator() (mapnik::image_gray64 const& data)
{
Nan::EscapableHandleScope scope;
std::uint64_t val = mapnik::get_pixel<std::uint64_t>(data, x_, y_);
return scope.Escape(Nan::New<v8::Number>(val));
}
v8::Local<v8::Value> operator() (mapnik::image_gray64s const& data)
{
Nan::EscapableHandleScope scope;
std::int64_t val = mapnik::get_pixel<std::int64_t>(data, x_, y_);
return scope.Escape(Nan::New<v8::Number>(val));
}
v8::Local<v8::Value> operator() (mapnik::image_gray64f const& data)
{
Nan::EscapableHandleScope scope;
double val = mapnik::get_pixel<double>(data, x_, y_);
return scope.Escape(Nan::New<v8::Number>(val));
}
v8::Local<v8::Value> operator() (mapnik::image_rgba8 const& data)
{
Nan::EscapableHandleScope scope;
std::uint32_t val = mapnik::get_pixel<std::uint32_t>(data, x_, y_);
return scope.Escape(Nan::New<v8::Number>(val));
}
private:
int x_;
int y_;
};
/**
* Get a specific pixel and its value
* @name getPixel
* @instance
* @memberof Image
* @param {number} x - position within image from top left
* @param {number} y - position within image from top left
* @param {Object} [options] the only valid option is `get_color`, which
* should be a `boolean`. If set, the return is an Object with `rgba` values
* instead of a pixel number.
* @returns {number|Object} color number or object of rgba values
* @example
* // check for color after rendering image
* var img = new mapnik.Image(4, 4);
* var map = new mapnik.Map(4, 4);
* map.background = new mapnik.Color('green');
* map.render(img, {},function(err, img) {
* console.log(img.painted()); // false
* var pixel = img.getPixel(0,0);
* var values = img.getPixel(0,0, {get_color: true});
* console.log(pixel); // 4278222848
* console.log(values); // { premultiplied: false, a: 255, b: 0, g: 128, r: 0 }
* });
*/
NAN_METHOD(Image::getPixel)
{
int x = 0;
int y = 0;
bool get_color = false;
if (info.Length() >= 3) {
if (!info[2]->IsObject()) {
Nan::ThrowTypeError("optional third argument must be an options object");
return;
}
v8::Local<v8::Object> options = info[2]->ToObject();
if (options->Has(Nan::New("get_color").ToLocalChecked())) {
v8::Local<v8::Value> bind_opt = options->Get(Nan::New("get_color").ToLocalChecked());
if (!bind_opt->IsBoolean()) {
Nan::ThrowTypeError("optional arg 'color' must be a boolean");
return;
}
get_color = bind_opt->BooleanValue();
}
}
if (info.Length() >= 2) {
if (!info[0]->IsNumber()) {
Nan::ThrowTypeError("first arg, 'x' must be an integer");
return;
}
if (!info[1]->IsNumber()) {
Nan::ThrowTypeError("second arg, 'y' must be an integer");
return;
}
x = info[0]->IntegerValue();
y = info[1]->IntegerValue();
} else {
Nan::ThrowError("must supply x,y to query pixel color");
return;
}
Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder());
if (x >= 0 && x < static_cast<int>(im->this_->width())
&& y >= 0 && y < static_cast<int>(im->this_->height()))
{
if (get_color)
{
mapnik::color val = mapnik::get_pixel<mapnik::color>(*im->this_, x, y);
info.GetReturnValue().Set(Color::NewInstance(val));
} else {
visitor_get_pixel visitor(x, y);
info.GetReturnValue().Set(mapnik::util::apply_visitor(visitor, *im->this_));
}
}
return;
}
/**
* Set a pixels value
* @name setPixel
* @instance
* @memberof Image
* @param {number} x position within image from top left
* @param {number} y position within image from top left
* @param {Object|number} numeric or object representation of a color, typically used with {@link mapnik.Color}
* @example
* var gray = new mapnik.Image(256, 256);
* gray.setPixel(0,0,new mapnik.Color('white'));
* var pixel = gray.getPixel(0,0,{get_color:true});
* console.log(pixel); // { premultiplied: false, a: 255, b: 255, g: 255, r: 255 }
*/
NAN_METHOD(Image::setPixel)
{
if (info.Length() < 3 || (!info[0]->IsNumber() && !info[1]->IsNumber())) {
Nan::ThrowTypeError("expects three arguments: x, y, and pixel value");
return;
}
int x = info[0]->IntegerValue();
int y = info[1]->IntegerValue();
Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder());
if (x < 0 || x >= static_cast<int>(im->this_->width()) || y < 0 || y >= static_cast<int>(im->this_->height()))
{
Nan::ThrowTypeError("invalid pixel requested");
return;
}
if (info[2]->IsUint32())
{
std::uint32_t val = info[2]->Uint32Value();
mapnik::set_pixel<std::uint32_t>(*im->this_,x,y,val);
}
else if (info[2]->IsInt32())
{
std::int32_t val = info[2]->Int32Value();
mapnik::set_pixel<std::int32_t>(*im->this_,x,y,val);
}
else if (info[2]->IsNumber())
{
double val = info[2]->NumberValue();
mapnik::set_pixel<double>(*im->this_,x,y,val);
}
else if (info[2]->IsObject())
{
v8::Local<v8::Object> obj = info[2]->ToObject();
if (obj->IsNull() || obj->IsUndefined() || !Nan::New(Color::constructor)->HasInstance(obj))
{
Nan::ThrowTypeError("A numeric or color value is expected as third arg");
}
else
{
Color * color = Nan::ObjectWrap::Unwrap<Color>(obj);
mapnik::set_pixel(*im->this_,x,y,*(color->get()));
}
}
else
{
Nan::ThrowTypeError("A numeric or color value is expected as third arg");
}
return;
}
/**
* Compare the pixels of one image to the pixels of another. Returns the number
* of pixels that are different. So, if the images are identical then it returns `0`.
* And if the images share no common pixels it returns the total number of pixels
* in an image which is equivalent to `im.width()*im.height()`.
*
* @name compare
* @instance
* @memberof Image
* @param {mapnik.Image} image - another {@link mapnik.Image} instance to compare to
* @param {Object} [options]
* @param {number} [options.threshold=16] - A value that should be `0` or greater to
* determine if the pixels match. Defaults to 16 which means that `rgba(0,0,0,0)`
* would be considered the same as `rgba(15,15,15,0)`.
* @param {boolean} [options.alpha=true] - `alpha` value, along with `rgb`, is considered
* when comparing pixels
* @returns {number} quantified visual difference between these two images in "number of
* pixels" (i.e. `80` pixels are different);
* @example
* // start with the exact same images
* var img1 = new mapnik.Image(2,2);
* var img2 = new mapnik.Image(2,2);
* console.log(img1.compare(img2)); // 0
*
* // change 1 pixel in img2
* img2.setPixel(0,0, new mapnik.Color('green'));
* console.log(img1.compare(img2)); // 1
*
* // difference in color at first pixel
* img1.setPixel(0,0, new mapnik.Color('red'));
* console.log(img1.compare(img2)); // 1
*
* // two pixels different
* img2.setPixel(0,1, new mapnik.Color('red'));
* console.log(img1.compare(img2)); // 2
*
* // all pixels different
* img2.setPixel(1,1, new mapnik.Color('blue'));
* img2.setPixel(1,0, new mapnik.Color('blue'));
* console.log(img1.compare(img2)); // 4
*/
NAN_METHOD(Image::compare)
{
if (info.Length() < 1 || !info[0]->IsObject()) {
Nan::ThrowTypeError("first argument should be a mapnik.Image");
return;
}
v8::Local<v8::Object> obj = info[0]->ToObject();
if (obj->IsNull() || obj->IsUndefined() || !Nan::New(Image::constructor)->HasInstance(obj)) {
Nan::ThrowTypeError("mapnik.Image expected as first arg");
return;
}
int threshold = 16;
unsigned alpha = true;
if (info.Length() > 1) {
if (!info[1]->IsObject()) {
Nan::ThrowTypeError("optional second argument must be an options object");
return;
}
v8::Local<v8::Object> options = info[1]->ToObject();
if (options->Has(Nan::New("threshold").ToLocalChecked())) {
v8::Local<v8::Value> bind_opt = options->Get(Nan::New("threshold").ToLocalChecked());
if (!bind_opt->IsNumber()) {
Nan::ThrowTypeError("optional arg 'threshold' must be a number");
return;
}
threshold = bind_opt->IntegerValue();
}
if (options->Has(Nan::New("alpha").ToLocalChecked())) {
v8::Local<v8::Value> bind_opt = options->Get(Nan::New("alpha").ToLocalChecked());
if (!bind_opt->IsBoolean()) {
Nan::ThrowTypeError("optional arg 'alpha' must be a boolean");
return;
}
alpha = bind_opt->BooleanValue();
}
}
Image* im = Nan::ObjectWrap::Unwrap<Image>(info.This());
Image* im2 = Nan::ObjectWrap::Unwrap<Image>(obj);
if (im->this_->width() != im2->this_->width() ||
im->this_->height() != im2->this_->height()) {
Nan::ThrowTypeError("image dimensions do not match");
return;
}
unsigned difference = mapnik::compare(*im->this_, *im2->this_, threshold, alpha);
info.GetReturnValue().Set(Nan::New<v8::Integer>(difference));
}
/**
* Apply a filter to this image. This changes all pixel values. (synchronous)
*
* @name filterSync
* @instance
* @memberof Image
* @param {string} filter - can be `blur`, `emboss`, `sharpen`,
* `sobel`, or `gray`.
* @example
* var img = new mapnik.Image(5, 5);
* img.filter('blur');
* // your custom code with `img` having blur applied
*/
NAN_METHOD(Image::filterSync)
{
info.GetReturnValue().Set(_filterSync(info));
}
v8::Local<v8::Value> Image::_filterSync(Nan::NAN_METHOD_ARGS_TYPE info) {
Nan::EscapableHandleScope scope;
if (info.Length() < 1) {
Nan::ThrowTypeError("expects one argument: string filter argument");
return scope.Escape(Nan::Undefined());
}
Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder());
if (!info[0]->IsString())
{
Nan::ThrowTypeError("A string is expected for filter argument");
return scope.Escape(Nan::Undefined());
}
std::string filter = TOSTR(info[0]);
try
{
mapnik::filter::filter_image(*im->this_,filter);
}
catch(std::exception const& ex)
{
Nan::ThrowError(ex.what());
}
return scope.Escape(Nan::Undefined());
}
typedef struct {
uv_work_t request;
Image* im;
std::string filter;
bool error;
std::string error_name;
Nan::Persistent<v8::Function> cb;
} filter_image_baton_t;
/**
* Apply a filter to this image. Changes all pixel values.
*
* @name filter
* @instance
* @memberof Image
* @param {string} filter - can be `blur`, `emboss`, `sharpen`,
* `sobel`, or `gray`.
* @param {Function} callback - `function(err, img)`
* @example
* var img = new mapnik.Image(5, 5);
* img.filter('sobel', function(err, img) {
* if (err) throw err;
* // your custom `img` with sobel filter
* // https://en.wikipedia.org/wiki/Sobel_operator
* });
*/
NAN_METHOD(Image::filter)
{
if (info.Length() <= 1) {
info.GetReturnValue().Set(_filterSync(info));
return;
}
if (!info[info.Length()-1]->IsFunction()) {
Nan::ThrowTypeError("last argument must be a callback function");
return;
}
Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder());
if (!info[0]->IsString())
{
Nan::ThrowTypeError("A string is expected for filter argument");
return;
}
filter_image_baton_t *closure = new filter_image_baton_t();
closure->filter = TOSTR(info[0]);
// ensure callback is a function
v8::Local<v8::Value> callback = info[info.Length()-1];
closure->request.data = closure;
closure->im = im;
closure->error = false;
closure->cb.Reset(callback.As<v8::Function>());
uv_queue_work(uv_default_loop(), &closure->request, EIO_Filter, (uv_after_work_cb)EIO_AfterFilter);
im->Ref();
return;
}
void Image::EIO_Filter(uv_work_t* req)
{
filter_image_baton_t *closure = static_cast<filter_image_baton_t *>(req->data);
try
{
mapnik::filter::filter_image(*closure->im->this_,closure->filter);
}
catch(std::exception const& ex)
{
closure->error = true;
closure->error_name = ex.what();
}
}
void Image::EIO_AfterFilter(uv_work_t* req)
{
Nan::HandleScope scope;
filter_image_baton_t *closure = static_cast<filter_image_baton_t *>(req->data);
if (closure->error)
{
v8::Local<v8::Value> argv[1] = { Nan::Error(closure->error_name.c_str()) };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv);
}
else
{
v8::Local<v8::Value> argv[2] = { Nan::Null(), closure->im->handle() };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 2, argv);
}
closure->im->Unref();
closure->cb.Reset();
delete closure;
}
/**
* Fill this image with a given color. Changes all pixel values. (synchronous)
*
* @name fillSync
* @instance
* @memberof Image
* @param {mapnik.Color|number} color
* @example
* var img = new mapnik.Image(5,5);
* // blue pixels
* img.fillSync(new mapnik.Color('blue'));
* var colors = img.getPixel(0,0, {get_color: true});
* // blue value is filled
* console.log(colors.b); // 255
*/
NAN_METHOD(Image::fillSync)
{
info.GetReturnValue().Set(_fillSync(info));
}
v8::Local<v8::Value> Image::_fillSync(Nan::NAN_METHOD_ARGS_TYPE info) {
Nan::EscapableHandleScope scope;
if (info.Length() < 1 ) {
Nan::ThrowTypeError("expects one argument: Color object or a number");
return scope.Escape(Nan::Undefined());
}
Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder());
try
{
if (info[0]->IsUint32())
{
std::uint32_t val = info[0]->Uint32Value();
mapnik::fill<std::uint32_t>(*im->this_,val);
}
else if (info[0]->IsInt32())
{
std::int32_t val = info[0]->Int32Value();
mapnik::fill<std::int32_t>(*im->this_,val);
}
else if (info[0]->IsNumber())
{
double val = info[0]->NumberValue();
mapnik::fill<double>(*im->this_,val);
}
else if (info[0]->IsObject())
{
v8::Local<v8::Object> obj = info[0]->ToObject();
if (obj->IsNull() || obj->IsUndefined() || !Nan::New(Color::constructor)->HasInstance(obj))
{
Nan::ThrowTypeError("A numeric or color value is expected");
}
else
{
Color * color = Nan::ObjectWrap::Unwrap<Color>(obj);
mapnik::fill(*im->this_,*(color->get()));
}
}
else
{
Nan::ThrowTypeError("A numeric or color value is expected");
}
}
catch(std::exception const& ex)
{
Nan::ThrowError(ex.what());
}
return scope.Escape(Nan::Undefined());
}
enum fill_type : std::uint8_t
{
FILL_COLOR = 0,
FILL_UINT32,
FILL_INT32,
FILL_DOUBLE
};
typedef struct {
uv_work_t request;
Image* im;
fill_type type;
mapnik::color c;
std::uint32_t val_u32;
std::int32_t val_32;
double val_double;
//std::string format;
bool error;
std::string error_name;
Nan::Persistent<v8::Function> cb;
} fill_image_baton_t;
/**
* Fill this image with a given color. Changes all pixel values.
*
* @name fill
* @instance
* @memberof Image
* @param {mapnik.Color|number} color
* @param {Function} callback - `function(err, img)`
* @example
* var img = new mapnik.Image(5,5);
* img.fill(new mapnik.Color('blue'), function(err, img) {
* if (err) throw err;
* var colors = img.getPixel(0,0, {get_color: true});
* pixel is colored blue
* console.log(color.b); // 255
* });
*
* // or fill with rgb string
* img.fill('rgba(255,255,255,0)', function(err, img) { ... });
*/
NAN_METHOD(Image::fill)
{
if (info.Length() <= 1) {
info.GetReturnValue().Set(_fillSync(info));
return;
}
Image* im = Nan::ObjectWrap::Unwrap<Image>(info.Holder());
fill_image_baton_t *closure = new fill_image_baton_t();
if (info[0]->IsUint32())
{
closure->val_u32 = info[0]->Uint32Value();
closure->type = FILL_UINT32;
}
else if (info[0]->IsInt32())
{
closure->val_32 = info[0]->Int32Value();
closure->type = FILL_INT32;
}
else if (info[0]->IsNumber())
{
closure->val_double = info[0]->NumberValue();
closure->type = FILL_DOUBLE;
}
else if (info[0]->IsObject())
{
v8::Local<v8::Object> obj = info[0]->ToObject();
if (obj->IsNull() || obj->IsUndefined() || !Nan::New(Color::constructor)->HasInstance(obj))
{
delete closure;
Nan::ThrowTypeError("A numeric or color value is expected");
return;
}
else
{
Color * color = Nan::ObjectWrap::Unwrap<Color>(obj);
closure->c = *(color->get());
}
}
else
{
delete closure;
Nan::ThrowTypeError("A numeric or color value is expected");
return;
}
// ensure callback is a function
v8::Local<v8::Value> callback = info[info.Length()-1];
if (!info[info.Length()-1]->IsFunction()) {
delete closure;
Nan::ThrowTypeError("last argument must be a callback function");
return;
}
else
{
closure->request.data = closure;
closure->im = im;
closure->error = false;
closure->cb.Reset(callback.As<v8::Function>());
uv_queue_work(uv_default_loop(), &closure->request, EIO_Fill, (uv_after_work_cb)EIO_AfterFill);
im->Ref();
}
return;
}
void Image::EIO_Fill(uv_work_t* req)
{
fill_image_baton_t *closure = static_cast<fill_image_baton_t *>(req->data);
try
{
switch (closure->type)
{
case FILL_UINT32:
mapnik::fill(*closure->im->this_, closure->val_u32);
break;
case FILL_INT32:
mapnik::fill(*closure->im->this_, closure->val_32);
break;
default:
case FILL_DOUBLE:
mapnik::fill(*closure->im->this_, closure->val_double);
break;
case FILL_COLOR:
mapnik::fill(*closure->im->this_,closure->c);
break;
}
}
catch(std::exception const& ex)
{
closure->error = true;
closure->error_name = ex.what();
}
}
void Image::EIO_AfterFill(uv_work_t* req)
{
Nan::HandleScope scope;
fill_image_baton_t *closure = static_cast<fill_image_baton_t *>(req->data);
if (closure->error)
{
v8::Local<v8::Value> argv[1] = { Nan::Error(closure->error_name.c_str()) };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 1, argv);
}
else
{
v8::Local<v8::Value> argv[2] = { Nan::Null(), closure->im->handle() };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(closure->cb), 2, argv);