@rosepetal/node-red-contrib-image-tools 1.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/.gitattributes +6 -0
  2. package/.github/workflows/build-prebuild.yml +326 -0
  3. package/LICENSE +13 -0
  4. package/README.md +161 -0
  5. package/artifacts/darwin-arm64/package.json +25 -0
  6. package/artifacts/linux-arm64/package.json +26 -0
  7. package/artifacts/linux-x64/package.json +26 -0
  8. package/artifacts/linuxmusl-x64/package.json +26 -0
  9. package/assets/flow_time_example.gif +0 -0
  10. package/assets/nodes/io/array-in-demo.gif +0 -0
  11. package/assets/nodes/io/array-out-demo.gif +0 -0
  12. package/assets/nodes/io/array-select-demo.gif +0 -0
  13. package/assets/nodes/io/image-in-demo.gif +0 -0
  14. package/assets/nodes/mix/concat-demo.gif +0 -0
  15. package/assets/nodes/mix/mosaic-demo.gif +0 -0
  16. package/assets/nodes/transform/crop-demo.gif +0 -0
  17. package/assets/nodes/transform/filter-demo.gif +0 -0
  18. package/assets/nodes/transform/padding-demo.gif +0 -0
  19. package/assets/nodes/transform/resize-demo.gif +0 -0
  20. package/assets/nodes/transform/rotate-demo.gif +0 -0
  21. package/docs/nodes/blend/add-mask.md +275 -0
  22. package/docs/nodes/blend/add-masks.md +284 -0
  23. package/docs/nodes/blend/blend.md +248 -0
  24. package/docs/nodes/io/array-in.md +119 -0
  25. package/docs/nodes/io/array-out.md +150 -0
  26. package/docs/nodes/io/array-select.md +157 -0
  27. package/docs/nodes/io/image-in.md +131 -0
  28. package/docs/nodes/io/image-out.md +179 -0
  29. package/docs/nodes/io/queue.md +57 -0
  30. package/docs/nodes/io/save-file.md +30 -0
  31. package/docs/nodes/mix/advanced-mosaic.md +108 -0
  32. package/docs/nodes/mix/concat.md +127 -0
  33. package/docs/nodes/mix/mosaic.md +146 -0
  34. package/docs/nodes/specialized/cropBB.md +271 -0
  35. package/docs/nodes/specialized/image-align.md +426 -0
  36. package/docs/nodes/transform/crop.md +132 -0
  37. package/docs/nodes/transform/draw.md +77 -0
  38. package/docs/nodes/transform/filter.md +84 -0
  39. package/docs/nodes/transform/padding.md +133 -0
  40. package/docs/nodes/transform/resize.md +158 -0
  41. package/docs/nodes/transform/rotate.md +121 -0
  42. package/docs/nodes/util/block-detect.md +46 -0
  43. package/install.sh +144 -0
  44. package/node-red-contrib-image-tools/lib/cpp-bridge.js +224 -0
  45. package/node-red-contrib-image-tools/lib/node-utils.js +529 -0
  46. package/node-red-contrib-image-tools/nodes/blend/add-bbs.html +590 -0
  47. package/node-red-contrib-image-tools/nodes/blend/add-bbs.js +241 -0
  48. package/node-red-contrib-image-tools/nodes/blend/add-mask.html +449 -0
  49. package/node-red-contrib-image-tools/nodes/blend/add-mask.js +170 -0
  50. package/node-red-contrib-image-tools/nodes/blend/add-masks.html +703 -0
  51. package/node-red-contrib-image-tools/nodes/blend/add-masks.js +321 -0
  52. package/node-red-contrib-image-tools/nodes/blend/blend.html +552 -0
  53. package/node-red-contrib-image-tools/nodes/blend/blend.js +124 -0
  54. package/node-red-contrib-image-tools/nodes/io/array-in.html +110 -0
  55. package/node-red-contrib-image-tools/nodes/io/array-in.js +113 -0
  56. package/node-red-contrib-image-tools/nodes/io/array-out.html +125 -0
  57. package/node-red-contrib-image-tools/nodes/io/array-out.js +213 -0
  58. package/node-red-contrib-image-tools/nodes/io/array-select.html +156 -0
  59. package/node-red-contrib-image-tools/nodes/io/array-select.js +187 -0
  60. package/node-red-contrib-image-tools/nodes/io/folder-in.html +248 -0
  61. package/node-red-contrib-image-tools/nodes/io/folder-in.js +335 -0
  62. package/node-red-contrib-image-tools/nodes/io/image-in.html +146 -0
  63. package/node-red-contrib-image-tools/nodes/io/image-in.js +143 -0
  64. package/node-red-contrib-image-tools/nodes/io/image-out.html +506 -0
  65. package/node-red-contrib-image-tools/nodes/io/image-out.js +545 -0
  66. package/node-red-contrib-image-tools/nodes/io/queue.html +119 -0
  67. package/node-red-contrib-image-tools/nodes/io/queue.js +191 -0
  68. package/node-red-contrib-image-tools/nodes/io/save-file.html +243 -0
  69. package/node-red-contrib-image-tools/nodes/io/save-file.js +440 -0
  70. package/node-red-contrib-image-tools/nodes/mix/advanced-mosaic.html +2149 -0
  71. package/node-red-contrib-image-tools/nodes/mix/advanced-mosaic.js +195 -0
  72. package/node-red-contrib-image-tools/nodes/mix/concat.html +390 -0
  73. package/node-red-contrib-image-tools/nodes/mix/concat.js +112 -0
  74. package/node-red-contrib-image-tools/nodes/mix/mosaic.html +550 -0
  75. package/node-red-contrib-image-tools/nodes/mix/mosaic.js +151 -0
  76. package/node-red-contrib-image-tools/nodes/specialized/cropBB.html +268 -0
  77. package/node-red-contrib-image-tools/nodes/specialized/cropBB.js +277 -0
  78. package/node-red-contrib-image-tools/nodes/specialized/image-align.html +528 -0
  79. package/node-red-contrib-image-tools/nodes/specialized/image-align.js +306 -0
  80. package/node-red-contrib-image-tools/nodes/transform/crop.html +410 -0
  81. package/node-red-contrib-image-tools/nodes/transform/crop.js +149 -0
  82. package/node-red-contrib-image-tools/nodes/transform/draw.html +719 -0
  83. package/node-red-contrib-image-tools/nodes/transform/draw.js +509 -0
  84. package/node-red-contrib-image-tools/nodes/transform/filter.html +578 -0
  85. package/node-red-contrib-image-tools/nodes/transform/filter.js +177 -0
  86. package/node-red-contrib-image-tools/nodes/transform/padding.html +475 -0
  87. package/node-red-contrib-image-tools/nodes/transform/padding.js +142 -0
  88. package/node-red-contrib-image-tools/nodes/transform/resize.html +429 -0
  89. package/node-red-contrib-image-tools/nodes/transform/resize.js +162 -0
  90. package/node-red-contrib-image-tools/nodes/transform/rotate.html +299 -0
  91. package/node-red-contrib-image-tools/nodes/transform/rotate.js +141 -0
  92. package/node-red-contrib-image-tools/nodes/util/block-detect.html +85 -0
  93. package/node-red-contrib-image-tools/nodes/util/block-detect.js +136 -0
  94. package/node-red-contrib-image-tools/nodes/util/clean-debug.html +201 -0
  95. package/node-red-contrib-image-tools/nodes/util/clean-debug.js +393 -0
  96. package/node-red-contrib-image-tools/package.json +64 -0
  97. package/npm/darwin-arm64/lib/.gitkeep +1 -0
  98. package/npm/darwin-arm64/package.json +25 -0
  99. package/npm/darwin-x64/lib/.gitkeep +1 -0
  100. package/npm/darwin-x64/package.json +25 -0
  101. package/npm/linux-arm64/lib/.gitkeep +1 -0
  102. package/npm/linux-arm64/package.json +26 -0
  103. package/npm/linux-x64/lib/.gitkeep +1 -0
  104. package/npm/linux-x64/package.json +26 -0
  105. package/npm/linuxmusl-x64/lib/.gitkeep +1 -0
  106. package/npm/linuxmusl-x64/package.json +26 -0
  107. package/npm/win32-x64/lib/.gitkeep +1 -0
  108. package/npm/win32-x64/package.json +25 -0
  109. package/package.json +74 -0
  110. package/rosepetal-image-engine/binding.gyp +153 -0
  111. package/rosepetal-image-engine/package.json +19 -0
  112. package/rosepetal-image-engine/src/add-bbs.cpp +433 -0
  113. package/rosepetal-image-engine/src/add-mask.cpp +240 -0
  114. package/rosepetal-image-engine/src/add-masks.cpp +638 -0
  115. package/rosepetal-image-engine/src/advanced-mosaic.cpp +740 -0
  116. package/rosepetal-image-engine/src/blend.cpp +200 -0
  117. package/rosepetal-image-engine/src/concat.cpp +329 -0
  118. package/rosepetal-image-engine/src/crop.cpp +139 -0
  119. package/rosepetal-image-engine/src/draw.cpp +414 -0
  120. package/rosepetal-image-engine/src/filter.cpp +230 -0
  121. package/rosepetal-image-engine/src/filters/kernels.h +171 -0
  122. package/rosepetal-image-engine/src/image-align.cpp +551 -0
  123. package/rosepetal-image-engine/src/main.cpp +36 -0
  124. package/rosepetal-image-engine/src/mosaic.cpp +373 -0
  125. package/rosepetal-image-engine/src/padding.cpp +124 -0
  126. package/rosepetal-image-engine/src/resize.cpp +210 -0
  127. package/rosepetal-image-engine/src/rotate.cpp +177 -0
  128. package/rosepetal-image-engine/src/utils.h +563 -0
  129. package/rosepetal-image-engine/test-formats.js +119 -0
  130. package/scripts/build-opencv-static.ps1 +166 -0
  131. package/scripts/build-opencv-static.sh +147 -0
@@ -0,0 +1,200 @@
1
+ #include <napi.h>
2
+ #include <opencv2/opencv.hpp>
3
+ #include "utils.h"
4
+
5
+
6
+
7
+
8
+ /*------------------------------------------------------------------------*/
9
+ class BlendWorker final : public Napi::AsyncWorker {
10
+ public:
11
+ BlendWorker(Napi::Function cb,
12
+ const Napi::Value& jsImg1,
13
+ const Napi::Value& jsImg2,
14
+ double opacity,
15
+ std::string outputFormat,
16
+ int quality = 90,
17
+ bool pngOptimize = false,
18
+ bool alphaCompositing = false,
19
+ bool removeBackground = false,
20
+ std::string backgroundColor = "#ffffff",
21
+ double colorTolerance = 0.1)
22
+ : Napi::AsyncWorker(cb),
23
+ opacity(opacity),
24
+ outputFormat(std::move(outputFormat)),
25
+ quality(quality), pngOptimize(pngOptimize),
26
+ alphaCompositing(alphaCompositing),
27
+ removeBackground(removeBackground),
28
+ backgroundColor(std::move(backgroundColor)),
29
+ colorTolerance(colorTolerance)
30
+ {
31
+ // Timing and conversion
32
+ const int64 t0 = cv::getTickCount();
33
+
34
+ // Convert JavaScript inputs to OpenCV Mats
35
+ mat1 = ConvertToMat(jsImg1);
36
+ mat2 = ConvertToMat(jsImg2);
37
+
38
+ // Detect channel formats
39
+ format1 = DetectChannelFormatShared(jsImg1, mat1);
40
+ format2 = DetectChannelFormatShared(jsImg2, mat2);
41
+
42
+ // Determine output channel format - force BGRA for alpha compositing
43
+ if (alphaCompositing) {
44
+ outputChannel = "BGRA";
45
+ } else {
46
+ outputChannel = DetermineOutputFormat(format1, format2);
47
+ }
48
+
49
+ convertMs = (cv::getTickCount() - t0) / cv::getTickFrequency() * 1e3;
50
+ }
51
+
52
+ protected:
53
+ void Execute() override {
54
+ const int64 t0 = cv::getTickCount();
55
+
56
+ // Convert both images to the same target format
57
+ cv::Mat img1 = ConvertToTargetFormatShared(mat1, format1, outputChannel);
58
+ cv::Mat img2 = ConvertToTargetFormatShared(mat2, format2, outputChannel);
59
+
60
+ // Apply background removal to image2 if requested
61
+ if (alphaCompositing && removeBackground) {
62
+ cv::Scalar bgColor = parseColorString(backgroundColor);
63
+ img2 = removeColorBackground(img2, bgColor, colorTolerance);
64
+ // Update img2 to BGRA format after background removal
65
+ if (img2.channels() != 4) {
66
+ cv::cvtColor(img2, img2, cv::COLOR_BGR2BGRA);
67
+ }
68
+ }
69
+
70
+ // Ensure both images have the same dimensions (resize smaller to match larger)
71
+ cv::Size targetSize;
72
+ if (img1.size() != img2.size()) {
73
+ // Use the larger dimensions
74
+ targetSize.width = std::max(img1.cols, img2.cols);
75
+ targetSize.height = std::max(img1.rows, img2.rows);
76
+
77
+ if (img1.size() != targetSize) {
78
+ cv::resize(img1, img1, targetSize);
79
+ }
80
+ if (img2.size() != targetSize) {
81
+ cv::resize(img2, img2, targetSize);
82
+ }
83
+ }
84
+
85
+ // Choose blending algorithm based on mode
86
+ if (alphaCompositing) {
87
+ // Use proper alpha compositing: img1 as base, img2 as overlay
88
+ result = alphaComposite(img1, img2, opacity);
89
+ } else {
90
+ // Use traditional addWeighted blending
91
+ // Formula: result = img1 * opacity + img2 * (1 - opacity)
92
+ cv::addWeighted(img1, opacity, img2, 1.0 - opacity, 0.0, result);
93
+ }
94
+
95
+ taskMs = (cv::getTickCount() - t0) / cv::getTickFrequency() * 1e3;
96
+
97
+ // Multi-format encoding if needed
98
+ if (outputFormat != "raw") {
99
+ cv::Mat tmp = ToBgrForJpg(result, outputChannel);
100
+ encodeMs = EncodeToFormat(tmp, encodedBuf, outputFormat, quality, pngOptimize);
101
+ }
102
+ }
103
+
104
+ void OnOK() override {
105
+ Napi::Env env = Env();
106
+ Napi::Value jsImg = (outputFormat != "raw") ? VectorToBuffer(env, std::move(encodedBuf))
107
+ : MatToRawJS(env, result, outputChannel);
108
+
109
+ Napi::Object out = Napi::Object::New(env);
110
+ out.Set("image", jsImg);
111
+ out.Set("timing", MakeTimingJS(env, convertMs, taskMs, encodeMs));
112
+ Callback().Call({env.Null(), out});
113
+ }
114
+
115
+ private:
116
+ cv::Mat mat1, mat2, result;
117
+ std::string format1, format2, outputChannel;
118
+ double opacity;
119
+ std::string outputFormat;
120
+ int quality;
121
+ bool pngOptimize;
122
+ bool alphaCompositing;
123
+ bool removeBackground;
124
+ std::string backgroundColor;
125
+ double colorTolerance;
126
+ double convertMs = 0, taskMs = 0, encodeMs = 0;
127
+ std::vector<uchar> encodedBuf;
128
+ };
129
+
130
+ /*------------------------------------------------------------------------*/
131
+ Napi::Value Blend(const Napi::CallbackInfo& info) {
132
+ Napi::Env env = info.Env();
133
+
134
+ // Fast parameter validation - now supports up to 11 parameters
135
+ if (info.Length() < 4 || info.Length() > 11 || !info[info.Length() - 1].IsFunction()) {
136
+ Napi::TypeError::New(env, "blend(image1, image2, opacity, [outputFormat], [quality], [pngOptimize], [alphaCompositing], [removeBackground], [backgroundColor], [colorTolerance], callback)")
137
+ .ThrowAsJavaScriptException();
138
+ return env.Null();
139
+ }
140
+
141
+ // Extract required parameters
142
+ Napi::Value jsImg1 = info[0];
143
+ Napi::Value jsImg2 = info[1];
144
+ double opacity = info[2].As<Napi::Number>().DoubleValue();
145
+
146
+ // Clamp opacity to valid range [0.0, 1.0]
147
+ opacity = std::max(0.0, std::min(1.0, opacity));
148
+
149
+ // Handle optional parameters
150
+ std::string outputFormat = "raw";
151
+ int quality = 90;
152
+ bool pngOptimize = false;
153
+ bool alphaCompositing = false;
154
+ bool removeBackground = false;
155
+ std::string backgroundColor = "#ffffff";
156
+ double colorTolerance = 0.1;
157
+ size_t cbIdx = 3;
158
+
159
+ if (info.Length() >= 5) {
160
+ outputFormat = info[3].As<Napi::String>().Utf8Value();
161
+ cbIdx = 4;
162
+ }
163
+
164
+ if (info.Length() >= 6) {
165
+ quality = info[4].As<Napi::Number>().Int32Value();
166
+ cbIdx = 5;
167
+ }
168
+
169
+ if (info.Length() >= 7) {
170
+ pngOptimize = info[5].As<Napi::Boolean>().Value();
171
+ cbIdx = 6;
172
+ }
173
+
174
+ if (info.Length() >= 8) {
175
+ alphaCompositing = info[6].As<Napi::Boolean>().Value();
176
+ cbIdx = 7;
177
+ }
178
+
179
+ if (info.Length() >= 9) {
180
+ removeBackground = info[7].As<Napi::Boolean>().Value();
181
+ cbIdx = 8;
182
+ }
183
+
184
+ if (info.Length() >= 10) {
185
+ backgroundColor = info[8].As<Napi::String>().Utf8Value();
186
+ cbIdx = 9;
187
+ }
188
+
189
+ if (info.Length() == 11) {
190
+ colorTolerance = info[9].As<Napi::Number>().DoubleValue();
191
+ // Clamp tolerance to valid range [0.0, 1.0]
192
+ colorTolerance = std::max(0.0, std::min(1.0, colorTolerance));
193
+ cbIdx = 10;
194
+ }
195
+
196
+ // Create and queue worker
197
+ (new BlendWorker(info[cbIdx].As<Napi::Function>(), jsImg1, jsImg2, opacity, outputFormat, quality, pngOptimize,
198
+ alphaCompositing, removeBackground, backgroundColor, colorTolerance))->Queue();
199
+ return env.Undefined();
200
+ }
@@ -0,0 +1,329 @@
1
+ #include <napi.h>
2
+ #include <opencv2/opencv.hpp>
3
+ #include "utils.h"
4
+ #include <unordered_map>
5
+
6
+ // Direction and strategy enums for faster comparisons
7
+ enum class Direction { RIGHT, LEFT, UP, DOWN };
8
+ enum class Strategy { RESIZE, PAD_START, PAD_END, PAD_BOTH };
9
+
10
+ // Helper function to detect channel format for individual images
11
+ std::string DetectChannelFormat(const Napi::Value& jsImg, const cv::Mat& mat) {
12
+ if (jsImg.IsObject() && !jsImg.IsBuffer()) {
13
+ Napi::Object obj = jsImg.As<Napi::Object>();
14
+
15
+ // Check for new colorSpace field first
16
+ if (obj.Has("colorSpace")) {
17
+ return obj.Get("colorSpace").As<Napi::String>().Utf8Value();
18
+ }
19
+ // Default based on channel count
20
+ else {
21
+ const int channels = mat.channels();
22
+ return (channels == 4) ? "BGRA" : (channels == 3) ? "BGR" : "GRAY";
23
+ }
24
+ } else {
25
+ // Buffer input - determine from OpenCV Mat
26
+ const int channels = mat.channels();
27
+ return (channels == 4) ? "BGRA" : (channels == 3) ? "BGR" : "GRAY";
28
+ }
29
+ }
30
+
31
+ // Helper function to determine the best output channel format from a list
32
+ std::string DetermineOutputFormat(const std::vector<std::string>& channels) {
33
+ bool hasRGBA = false, hasBGRA = false, hasRGB = false, hasBGR = false;
34
+
35
+ for (const auto& ch : channels) {
36
+ if (ch == "RGBA") hasRGBA = true;
37
+ else if (ch == "BGRA") hasBGRA = true;
38
+ else if (ch == "RGB") hasRGB = true;
39
+ else if (ch == "BGR") hasBGR = true;
40
+ }
41
+
42
+ // Priority: RGBA > BGRA > RGB > BGR > GRAY
43
+ if (hasRGBA) return "RGBA";
44
+ if (hasBGRA) return "BGRA";
45
+ if (hasRGB) return "RGB";
46
+ if (hasBGR) return "BGR";
47
+ return "GRAY";
48
+ }
49
+
50
+ // Helper function to prepare pad color for specific channel format
51
+ cv::Scalar PreparePadColor(const cv::Scalar& originalColor, const std::string& channelFormat) {
52
+ cv::Scalar padColor = originalColor;
53
+ if (channelFormat == "RGB" || channelFormat == "RGBA") {
54
+ std::swap(padColor[0], padColor[2]); // Swap R and B
55
+ }
56
+ return padColor;
57
+ }
58
+
59
+ // Helper function to convert image to target channel format
60
+ cv::Mat ConvertToTargetFormat(const cv::Mat& src, const std::string& srcFormat, const std::string& targetFormat) {
61
+ if (srcFormat == targetFormat) {
62
+ return src; // No conversion needed
63
+ }
64
+
65
+ cv::Mat dst;
66
+
67
+ // Convert to target format
68
+ if (srcFormat == "GRAY" && targetFormat == "BGR") {
69
+ cv::cvtColor(src, dst, cv::COLOR_GRAY2BGR);
70
+ } else if (srcFormat == "GRAY" && targetFormat == "RGB") {
71
+ cv::cvtColor(src, dst, cv::COLOR_GRAY2RGB);
72
+ } else if (srcFormat == "GRAY" && targetFormat == "BGRA") {
73
+ cv::cvtColor(src, dst, cv::COLOR_GRAY2BGRA);
74
+ } else if (srcFormat == "GRAY" && targetFormat == "RGBA") {
75
+ cv::cvtColor(src, dst, cv::COLOR_GRAY2RGBA);
76
+ } else if (srcFormat == "BGR" && targetFormat == "RGB") {
77
+ cv::cvtColor(src, dst, cv::COLOR_BGR2RGB);
78
+ } else if (srcFormat == "RGB" && targetFormat == "BGR") {
79
+ cv::cvtColor(src, dst, cv::COLOR_RGB2BGR);
80
+ } else if (srcFormat == "BGR" && targetFormat == "BGRA") {
81
+ cv::cvtColor(src, dst, cv::COLOR_BGR2BGRA);
82
+ } else if (srcFormat == "BGR" && targetFormat == "RGBA") {
83
+ cv::cvtColor(src, dst, cv::COLOR_BGR2RGBA);
84
+ } else if (srcFormat == "RGB" && targetFormat == "RGBA") {
85
+ cv::cvtColor(src, dst, cv::COLOR_RGB2RGBA);
86
+ } else if (srcFormat == "RGB" && targetFormat == "BGRA") {
87
+ cv::cvtColor(src, dst, cv::COLOR_RGB2BGRA);
88
+ } else if (srcFormat == "BGRA" && targetFormat == "BGR") {
89
+ cv::cvtColor(src, dst, cv::COLOR_BGRA2BGR);
90
+ } else if (srcFormat == "RGBA" && targetFormat == "RGB") {
91
+ cv::cvtColor(src, dst, cv::COLOR_RGBA2RGB);
92
+ } else if (srcFormat == "BGRA" && targetFormat == "RGBA") {
93
+ cv::cvtColor(src, dst, cv::COLOR_BGRA2RGBA);
94
+ } else if (srcFormat == "RGBA" && targetFormat == "BGRA") {
95
+ cv::cvtColor(src, dst, cv::COLOR_RGBA2BGRA);
96
+ } else {
97
+ // Fallback: return source if no conversion available
98
+ dst = src;
99
+ }
100
+
101
+ return dst;
102
+ }
103
+
104
+ /*------------------------------------------------------------------------*/
105
+ class ConcatWorker final : public Napi::AsyncWorker {
106
+ public:
107
+ ConcatWorker(Napi::Function cb,
108
+ const std::vector<Napi::Value>& jsImgs,
109
+ std::string dir,
110
+ std::string strat,
111
+ cv::Scalar padRGB,
112
+ std::string outputFormat,
113
+ int quality = 90,
114
+ bool pngOptimize = false)
115
+ : Napi::AsyncWorker(cb),
116
+ padColorRGB(padRGB),
117
+ outputFormat(std::move(outputFormat)),
118
+ quality(quality),
119
+ pngOptimize(pngOptimize)
120
+ {
121
+ // Convert string enums to faster integer types
122
+ if (dir == "right") direction = Direction::RIGHT;
123
+ else if (dir == "left") direction = Direction::LEFT;
124
+ else if (dir == "up") direction = Direction::UP;
125
+ else direction = Direction::DOWN;
126
+
127
+ if (strat.find("resize") != std::string::npos) strategy = Strategy::RESIZE;
128
+ else if (strat == "pad-start") strategy = Strategy::PAD_START;
129
+ else if (strat == "pad-end") strategy = Strategy::PAD_END;
130
+ else strategy = Strategy::PAD_BOTH;
131
+
132
+ // Timing and conversion
133
+ const int64 t0 = cv::getTickCount();
134
+ const size_t imgCount = jsImgs.size();
135
+ mats.reserve(imgCount);
136
+ channels.reserve(imgCount);
137
+
138
+ // Process all images and detect their channel formats
139
+ for (size_t i = 0; i < imgCount; ++i) {
140
+ mats.emplace_back(ConvertToMat(jsImgs[i]));
141
+ channels.push_back(DetectChannelFormat(jsImgs[i], mats[i]));
142
+ }
143
+
144
+ // Determine output channel format
145
+ outputChannel = DetermineOutputFormat(channels);
146
+
147
+ convertMs = (cv::getTickCount() - t0) / cv::getTickFrequency() * 1e3;
148
+
149
+ // Store original pad color (channel-specific preparation will be done per image)
150
+ padClrImg = padColorRGB;
151
+
152
+ // Pre-calculate max dimensions after channel format detection
153
+ // (dimensions shouldn't change with channel conversion)
154
+ for (const auto& m : mats) {
155
+ maxW = std::max(maxW, m.cols);
156
+ maxH = std::max(maxH, m.rows);
157
+ }
158
+ }
159
+
160
+ protected:
161
+ void Execute() override {
162
+ const int64 t0 = cv::getTickCount();
163
+
164
+ const bool isHorizontal = (direction == Direction::RIGHT || direction == Direction::LEFT);
165
+ const int baseSize = isHorizontal ? maxH : maxW;
166
+
167
+ // Prepare tiles with optimized preprocessing
168
+ std::vector<cv::Mat> tiles;
169
+ tiles.reserve(mats.size());
170
+
171
+ for (size_t i = 0; i < mats.size(); ++i) {
172
+ auto& m = mats[i];
173
+ const std::string& imgChannel = channels[i];
174
+
175
+ // Convert image to target output format first
176
+ cv::Mat convertedMat = ConvertToTargetFormat(m, imgChannel, outputChannel);
177
+ cv::Mat processed;
178
+
179
+ // Debug: log the converted image properties
180
+ // std::cout << "Image " << i << ": " << imgChannel << " -> " << outputChannel
181
+ // << " size: " << convertedMat.cols << "x" << convertedMat.rows
182
+ // << " channels: " << convertedMat.channels() << " type: " << convertedMat.type() << std::endl;
183
+
184
+ // Prepare pad color for the target output format
185
+ cv::Scalar imgPadColor = PreparePadColor(padColorRGB, outputChannel);
186
+
187
+ // Directly handle resize case without branches
188
+ if (strategy == Strategy::RESIZE) {
189
+ if (isHorizontal) {
190
+ double scale = static_cast<double>(baseSize) / convertedMat.rows;
191
+ cv::resize(convertedMat, processed, cv::Size(static_cast<int>(convertedMat.cols * scale), baseSize));
192
+ } else {
193
+ double scale = static_cast<double>(baseSize) / convertedMat.cols;
194
+ cv::resize(convertedMat, processed, cv::Size(baseSize, static_cast<int>(convertedMat.rows * scale)));
195
+ }
196
+ } else {
197
+ // Handle padding cases
198
+ const int delta = isHorizontal ? (baseSize - convertedMat.rows) : (baseSize - convertedMat.cols);
199
+ if (delta <= 0) {
200
+ processed = convertedMat; // No padding needed
201
+ } else {
202
+ int before = 0, after = 0;
203
+
204
+ switch (strategy) {
205
+ case Strategy::PAD_START:
206
+ before = delta;
207
+ break;
208
+ case Strategy::PAD_END:
209
+ after = delta;
210
+ break;
211
+ case Strategy::PAD_BOTH:
212
+ before = delta / 2;
213
+ after = delta - before;
214
+ break;
215
+ default: break;
216
+ }
217
+
218
+ if (isHorizontal) {
219
+ cv::copyMakeBorder(convertedMat, processed, before, after, 0, 0, cv::BORDER_CONSTANT, imgPadColor);
220
+ } else {
221
+ cv::copyMakeBorder(convertedMat, processed, 0, 0, before, after, cv::BORDER_CONSTANT, imgPadColor);
222
+ }
223
+ }
224
+ }
225
+
226
+ tiles.push_back(std::move(processed));
227
+ }
228
+
229
+ // Perform concatenation based on direction
230
+ if (isHorizontal) {
231
+ cv::hconcat(tiles, result);
232
+ if (direction == Direction::LEFT) {
233
+ cv::flip(result, result, 1);
234
+ }
235
+ } else {
236
+ if (direction == Direction::UP) {
237
+ std::reverse(tiles.begin(), tiles.end());
238
+ }
239
+ cv::vconcat(tiles, result);
240
+ }
241
+
242
+ taskMs = (cv::getTickCount() - t0) / cv::getTickFrequency() * 1e3;
243
+
244
+ // Multi-format encoding if needed
245
+ if (outputFormat != "raw") {
246
+ cv::Mat tmp = ToBgrForJpg(result, outputChannel);
247
+ encodeMs = EncodeToFormat(tmp, encodedBuf, outputFormat, quality, pngOptimize);
248
+ }
249
+ }
250
+
251
+ void OnOK() override {
252
+ Napi::Env env = Env();
253
+ Napi::Value jsImg = (outputFormat != "raw") ? VectorToBuffer(env, std::move(encodedBuf))
254
+ : MatToRawJS(env, result, outputChannel);
255
+
256
+ Napi::Object out = Napi::Object::New(env);
257
+ out.Set("image", jsImg);
258
+ out.Set("timing", MakeTimingJS(env, convertMs, taskMs, encodeMs));
259
+ Callback().Call({env.Null(), out});
260
+ }
261
+
262
+ private:
263
+ std::vector<cv::Mat> mats;
264
+ std::vector<std::string> channels;
265
+ cv::Mat result;
266
+ Direction direction;
267
+ Strategy strategy;
268
+ std::string outputChannel;
269
+ cv::Scalar padColorRGB, padClrImg;
270
+ std::string outputFormat;
271
+ int quality;
272
+ bool pngOptimize;
273
+ double convertMs = 0, taskMs = 0, encodeMs = 0;
274
+ std::vector<uchar> encodedBuf;
275
+ int maxW = 0, maxH = 0;
276
+ };
277
+
278
+ /*------------------------------------------------------------------------*/
279
+ Napi::Value Concat(const Napi::CallbackInfo& info) {
280
+ Napi::Env env = info.Env();
281
+
282
+ // Fast parameter validation
283
+ if (info.Length() < 5 || info.Length() > 8 || !info[0].IsArray() || !info[1].IsString() ||
284
+ !info[2].IsString() || !info[3].IsString() || !info[info.Length() - 1].IsFunction()) {
285
+ Napi::TypeError::New(env, "concat(array, direction, strategy, padHex, [outputFormat], [quality], [pngOptimize], cb)")
286
+ .ThrowAsJavaScriptException();
287
+ return env.Null();
288
+ }
289
+
290
+ // Process input array efficiently
291
+ auto arr = info[0].As<Napi::Array>();
292
+ const uint32_t len = arr.Length();
293
+ std::vector<Napi::Value> raw;
294
+ raw.reserve(len);
295
+
296
+ for (uint32_t i = 0; i < len; ++i) {
297
+ raw.push_back(arr.Get(i));
298
+ }
299
+
300
+ // Extract other parameters
301
+ std::string dir = info[1].As<Napi::String>();
302
+ std::string st = info[2].As<Napi::String>();
303
+ cv::Scalar pad = ParseColor(info[3].As<Napi::String>());
304
+
305
+ // Handle parameters
306
+ std::string outputFormat = "raw";
307
+ int quality = 90;
308
+ bool pngOptimize = false;
309
+ size_t cbIdx = 4;
310
+
311
+ if (info.Length() >= 6) {
312
+ outputFormat = info[4].As<Napi::String>().Utf8Value();
313
+ cbIdx = 5;
314
+ }
315
+
316
+ if (info.Length() >= 7) {
317
+ quality = info[5].As<Napi::Number>().Int32Value();
318
+ cbIdx = 6;
319
+ }
320
+
321
+ if (info.Length() == 8) {
322
+ pngOptimize = info[6].As<Napi::Boolean>().Value();
323
+ cbIdx = 7;
324
+ }
325
+
326
+ // Create and queue worker
327
+ (new ConcatWorker(info[cbIdx].As<Napi::Function>(), raw, dir, st, pad, outputFormat, quality, pngOptimize))->Queue();
328
+ return env.Undefined();
329
+ }
@@ -0,0 +1,139 @@
1
+ // ───────── src/crop.cpp ───────────────────────────────────────────────
2
+ #include <napi.h>
3
+ #include <opencv2/opencv.hpp>
4
+ #include <cmath>
5
+ #include "utils.h" // ConvertToMat, ToBgrForJpg, EncodeToJpgFast…
6
+
7
+ /*────────────────────────── Worker ───────────────────────────────────*/
8
+ class CropWorker : public Napi::AsyncWorker {
9
+ public:
10
+ CropWorker(Napi::Function cb,
11
+ const Napi::Value& imgVal,
12
+ double x,double y,double width,double height,
13
+ bool normalized,std::string outputFormat,int quality = 90,bool pngOptimize = false)
14
+ : Napi::AsyncWorker(cb),
15
+ x_(x),y_(y),width_(width),height_(height),
16
+ normalized_(normalized),outputFormat_(std::move(outputFormat)),quality_(quality),pngOptimize_(pngOptimize)
17
+ {
18
+ /* ─ medir convertMs ─ */
19
+ const int64 t0 = cv::getTickCount();
20
+ input_ = ConvertToMat(imgVal); // zero-copy
21
+ convertMs_ = (cv::getTickCount()-t0)/cv::getTickFrequency()*1e3;
22
+
23
+ if (imgVal.IsObject() && !imgVal.IsBuffer()) {
24
+ Napi::Object obj = imgVal.As<Napi::Object>();
25
+
26
+ // Check for colorSpace field
27
+ if (obj.Has("colorSpace")) {
28
+ channel_ = obj.Get("colorSpace").As<Napi::String>().Utf8Value();
29
+ }
30
+ // Default based on channel count
31
+ else {
32
+ channel_ = (input_.channels() == 4) ? "BGRA"
33
+ : (input_.channels() == 3) ? "BGR"
34
+ : "GRAY";
35
+ }
36
+ } else {
37
+ // Buffer input - determine from OpenCV Mat
38
+ channel_ = (input_.channels() == 4) ? "BGRA"
39
+ : (input_.channels() == 3) ? "BGR"
40
+ : "GRAY";
41
+ }
42
+ }
43
+
44
+ protected:
45
+ void Execute() override {
46
+ /* ─ medir taskMs (recorte) ─ */
47
+ const int64 t0 = cv::getTickCount();
48
+
49
+ const int W=input_.cols, H=input_.rows;
50
+ int x = normalized_? int(std::round(x_*W)) : int(std::lround(x_));
51
+ int y = normalized_? int(std::round(y_*H)) : int(std::lround(y_));
52
+ int width = normalized_? int(std::round(width_*W)) : int(std::lround(width_));
53
+ int height = normalized_? int(std::round(height_*H)) : int(std::lround(height_));
54
+
55
+ // Clamp position and dimensions to valid ranges
56
+ x = std::clamp(x, 0, W-1);
57
+ y = std::clamp(y, 0, H-1);
58
+ width = std::clamp(width, 1, W-x); // Ensure width doesn't exceed image boundary
59
+ height = std::clamp(height, 1, H-y); // Ensure height doesn't exceed image boundary
60
+
61
+ result_ = input_(cv::Rect(x, y, width, height));
62
+
63
+ taskMs_ = (cv::getTickCount()-t0)/cv::getTickFrequency()*1e3;
64
+
65
+ /* ─ Multi-format encoding (encodeMs) ─ */
66
+ if(outputFormat_ != "raw"){
67
+ const cv::Mat& srcForEncoding = (channel_=="BGR")? result_
68
+ : ToBgrForJpg(result_,channel_);
69
+ encodeMs_ = EncodeToFormat(srcForEncoding, encodedBuf_, outputFormat_, quality_, pngOptimize_);
70
+ }
71
+ }
72
+
73
+ void OnOK() override {
74
+ Napi::Env env = Env();
75
+ Napi::Value jsImg = (outputFormat_ != "raw")
76
+ ? VectorToBuffer(env,std::move(encodedBuf_)) // 0-copy
77
+ : MatToRawJS(env,result_.clone(),channel_); // contiguo
78
+
79
+ Napi::Object out = Napi::Object::New(env);
80
+ out.Set("image", jsImg);
81
+ out.Set("timing", MakeTimingJS(env,convertMs_,taskMs_,encodeMs_));
82
+ Callback().Call({ env.Null(), out });
83
+ }
84
+
85
+ void OnError(const Napi::Error& e) override {
86
+ Callback().Call({ e.Value(), Env().Null() });
87
+ }
88
+
89
+ private:
90
+ cv::Mat input_, result_;
91
+ double x_, y_, width_, height_;
92
+ bool normalized_;
93
+ std::string outputFormat_;
94
+ int quality_;
95
+ bool pngOptimize_;
96
+ std::string channel_;
97
+
98
+ double convertMs_{0.0}, taskMs_{0.0}, encodeMs_{0.0};
99
+ std::vector<uchar> encodedBuf_;
100
+ };
101
+
102
+ /*──────── binding: crop(image,x,y,width,height,normalized,[outputFormat],[quality],cb) ─*/
103
+ Napi::Value Crop(const Napi::CallbackInfo& info)
104
+ {
105
+ Napi::Env env = info.Env();
106
+ if(info.Length()<7||info.Length()>10||!info[info.Length()-1].IsFunction())
107
+ return Napi::TypeError::New(env,
108
+ "crop(image,x,y,width,height,normalized,[outputFormat],[quality],[pngOptimize],callback)").Value();
109
+
110
+ int i=0;
111
+ Napi::Value img = info[i++];
112
+ double x = info[i++].As<Napi::Number>(),
113
+ y = info[i++].As<Napi::Number>(),
114
+ width = info[i++].As<Napi::Number>(),
115
+ height = info[i++].As<Napi::Number>();
116
+ bool norm = info[i++].As<Napi::Boolean>();
117
+
118
+ // Handle parameters
119
+ std::string outputFormat = "raw";
120
+ int quality = 90;
121
+ bool pngOptimize = false;
122
+
123
+ if (info.Length() >= 8) {
124
+ outputFormat = info[i++].As<Napi::String>().Utf8Value();
125
+ }
126
+
127
+ if (info.Length() >= 9) {
128
+ quality = info[i++].As<Napi::Number>().Int32Value();
129
+ }
130
+
131
+ if (info.Length() == 10) {
132
+ pngOptimize = info[i++].As<Napi::Boolean>().Value();
133
+ }
134
+
135
+ Napi::Function cb = info[i].As<Napi::Function>();
136
+
137
+ (new CropWorker(cb,img,x,y,width,height,norm,outputFormat,quality,pngOptimize))->Queue();
138
+ return env.Undefined();
139
+ }