@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,248 @@
1
+ <script type="text/javascript">
2
+ RED.nodes.registerType('folder-in', {
3
+ category: 'RP Image',
4
+ color: '#A6C8A6',
5
+ defaults: {
6
+ name: { value: "" },
7
+ folderPath: { value: "", required: true },
8
+ folderPathType: { value: "str" },
9
+ interval: { value: 1000, required: true, validate: RED.validators.number() },
10
+ intervalType: { value: "num" },
11
+ mode: { value: "loop" },
12
+ outputPath: { value: "payload" },
13
+ outputPathType: { value: "msg" },
14
+ debugEnabled: { value: false },
15
+ debugWidth: { value: 200 },
16
+ debugWidthType: { value: "num" }
17
+ },
18
+ inputs: 0,
19
+ outputs: 1,
20
+ icon: "font-awesome/fa-folder-open",
21
+ align: "left",
22
+ button: {
23
+ enabled: function() {
24
+ return !this.changed;
25
+ },
26
+ onclick: function() {
27
+ const node = this;
28
+ const label = this.name || "folder-in";
29
+
30
+ $.ajax({
31
+ url: "folder-in/" + this.id,
32
+ type: "POST",
33
+ success: function(resp, textStatus, xhr) {
34
+ RED.notify("Toggled " + label, "success");
35
+ },
36
+ error: function(jqXHR, textStatus, errorThrown) {
37
+ if (jqXHR.status == 404) {
38
+ RED.notify("Node not deployed", "error");
39
+ } else if (jqXHR.status == 500) {
40
+ RED.notify("Toggle failed", "error");
41
+ } else if (jqXHR.status == 0) {
42
+ RED.notify("No response from server", "error");
43
+ } else {
44
+ RED.notify("Unexpected error: " + textStatus, "error");
45
+ }
46
+ }
47
+ });
48
+ }
49
+ },
50
+ label: function() {
51
+ return this.name || this.folderPath.split('/').pop() || "folder in";
52
+ },
53
+ labelStyle: function() {
54
+ return this.name ? "node_label_italic" : "";
55
+ },
56
+ oneditprepare: function() {
57
+ // Initialize TypedInput for folder path
58
+ $("#node-input-folderPath").typedInput({
59
+ default: 'str',
60
+ types: ['str', 'msg', 'flow', 'global'],
61
+ typeField: "#node-input-folderPathType"
62
+ });
63
+
64
+ // Initialize TypedInput for interval
65
+ $("#node-input-interval").typedInput({
66
+ default: 'num',
67
+ types: ['num', 'msg', 'flow', 'global'],
68
+ typeField: "#node-input-intervalType"
69
+ });
70
+
71
+ // Initialize TypedInput for output path
72
+ $("#node-input-outputPath").typedInput({
73
+ default: 'msg',
74
+ types: ['msg', 'flow', 'global'],
75
+ typeField: "#node-input-outputPathType"
76
+ });
77
+
78
+ // Debug display logic
79
+ const debugCheckbox = $('#node-input-debugEnabled');
80
+ const debugWidthRow = $('#debug-width-row');
81
+
82
+ // Initialize debug width TypedInput
83
+ $("#node-input-debugWidth").typedInput({
84
+ default: 'num',
85
+ types: ['num', 'msg', 'flow', 'global'],
86
+ typeField: "#node-input-debugWidthType"
87
+ });
88
+
89
+ // Show/hide debug width based on checkbox
90
+ function updateDebugWidthVisibility() {
91
+ if (debugCheckbox.prop('checked')) {
92
+ debugWidthRow.show();
93
+ } else {
94
+ debugWidthRow.hide();
95
+ }
96
+ }
97
+
98
+ debugCheckbox.change(function() {
99
+ updateDebugWidthVisibility();
100
+ });
101
+
102
+ // Initialize visibility
103
+ updateDebugWidthVisibility();
104
+ }
105
+ });
106
+ </script>
107
+
108
+ <script type="text/x-red" data-template-name="folder-in">
109
+ <div class="form-row">
110
+ <label for="node-input-name"><i class="fa fa-tag"></i> Name</label>
111
+ <input type="text" id="node-input-name" placeholder="Name">
112
+ </div>
113
+
114
+ <div class="form-row">
115
+ <label for="node-input-folderPath"><i class="fa fa-folder-open"></i> Folder Path</label>
116
+ <input type="text" id="node-input-folderPath" style="width: 70%;" placeholder="/path/to/image/folder">
117
+ <input type="hidden" id="node-input-folderPathType">
118
+ </div>
119
+
120
+ <hr>
121
+
122
+ <div class="form-row">
123
+ <label for="node-input-interval"><i class="fa fa-clock-o"></i> Interval (ms)</label>
124
+ <input type="text" id="node-input-interval" style="width: 120px;">
125
+ <input type="hidden" id="node-input-intervalType">
126
+ </div>
127
+
128
+ <div class="form-row">
129
+ <label for="node-input-mode"><i class="fa fa-repeat"></i> Mode</label>
130
+ <select id="node-input-mode" style="width: 200px;">
131
+ <option value="loop">Loop (repeat images)</option>
132
+ <option value="one-shot">One-shot (stop at end)</option>
133
+ </select>
134
+ </div>
135
+
136
+ <hr>
137
+
138
+ <div class="form-row">
139
+ <label for="node-input-outputPath"><i class="fa fa-sign-out"></i> Output to</label>
140
+ <input type="text" id="node-input-outputPath" style="width: 70%;">
141
+ <input type="hidden" id="node-input-outputPathType">
142
+ </div>
143
+
144
+ <!-- Debug Configuration -->
145
+ <div class="form-row">
146
+ <label for="node-input-debugEnabled"><i class="fa fa-bug"></i> Debug</label>
147
+ <input type="checkbox" id="node-input-debugEnabled" style="display:inline-block; width:auto; vertical-align:baseline;">
148
+ <label for="node-input-debugEnabled" style="width:auto; margin-left:5px;">Show loaded images</label>
149
+ </div>
150
+ <div class="form-row" id="debug-width-row" style="display: none;">
151
+ <label for="node-input-debugWidth"><i class="fa fa-arrows-h"></i> Debug Width</label>
152
+ <input type="text" id="node-input-debugWidth" style="width: 120px;">
153
+ <input type="hidden" id="node-input-debugWidthType">
154
+ </div>
155
+ </script>
156
+
157
+ <script type="text/x-red" data-help-name="folder-in">
158
+ <p>Scans a folder for image files and emits them one by one at configurable intervals. Features a toggle button to start/stop emission.</p>
159
+
160
+ <h3>Details</h3>
161
+ <p>This node reads all image files from a specified folder and emits them sequentially at a configurable rate. It can operate in two modes: loop (continuously repeat images) or one-shot (stop after all images). The node features a physical button on the left side (like the inject node) to start and stop the emission process.</p>
162
+
163
+ <p><strong>Supported Image Formats:</strong> JPEG, PNG, WebP, BMP, GIF, TIFF</p>
164
+
165
+ <h3>Properties</h3>
166
+ <dl class="message-properties">
167
+ <dt>Folder Path <span class="property-type">string | msg | flow | global</span></dt>
168
+ <dd>The path to the folder containing image files. Can be a static string (absolute or relative path) or dynamically resolved from message properties, flow context, or global context. The node will scan this folder and find all supported image files.</dd>
169
+
170
+ <dt>Interval (ms) <span class="property-type">number</span></dt>
171
+ <dd>The time interval in milliseconds between each image emission. For example, 1000 = 1 second between images. Minimum recommended: 100ms.</dd>
172
+
173
+ <dt>Mode <span class="property-type">loop | one-shot</span></dt>
174
+ <dd>
175
+ <ul>
176
+ <li><strong>Loop:</strong> After emitting the last image, restart from the first image and continue indefinitely until stopped.</li>
177
+ <li><strong>One-shot:</strong> Stop automatically after emitting all images once.</li>
178
+ </ul>
179
+ </dd>
180
+
181
+ <dt>Output to <span class="property-type">msg | flow | global</span></dt>
182
+ <dd>The location where the resulting image object will be stored. Defaults to <code>msg.payload</code>.</dd>
183
+
184
+ <dt>Debug <span class="property-type">boolean</span></dt>
185
+ <dd>Enable inline image preview display for debugging purposes.</dd>
186
+ </dl>
187
+
188
+ <h3>Button Control</h3>
189
+ <p>Click the button on the left side of the node to toggle between running and stopped states:</p>
190
+ <ul>
191
+ <li><strong>Stopped (grey):</strong> No images are being emitted. Click to start.</li>
192
+ <li><strong>Running (green):</strong> Images are being emitted at the configured interval. Click to stop.</li>
193
+ </ul>
194
+ <p><strong>Note:</strong> This node does not have an input connector. It operates independently using only the button control.</p>
195
+
196
+ <h3>Outputs</h3>
197
+ <p>The node sets the property specified in 'Output to' with the processed image object using the standard format:</p>
198
+ <pre>{
199
+ data: Buffer, // Raw pixel data
200
+ width: number, // Image width in pixels
201
+ height: number, // Image height in pixels
202
+ channels: number, // Channel count (1, 3, 4)
203
+ colorSpace: string, // "GRAY", "RGB", "RGBA"
204
+ dtype: string // "uint8"
205
+ }</pre>
206
+
207
+ <p>Additionally, each message includes metadata in <code>msg._folderIn</code>:</p>
208
+ <pre>{
209
+ fileName: string, // Name of the current image file
210
+ filePath: string, // Full path to the current image file
211
+ index: number, // Current image index (0-based)
212
+ total: number // Total number of images in folder
213
+ }</pre>
214
+
215
+ <h3>Examples</h3>
216
+ <ul>
217
+ <li><strong>Slideshow:</strong> Set folder to <code>/images/slideshow</code>, interval to 2000ms (2 seconds), mode to "loop" for continuous slideshow</li>
218
+ <li><strong>Batch Processing:</strong> Set mode to "one-shot" and connect to processing nodes to automatically process all images in a folder</li>
219
+ <li><strong>Animation Preview:</strong> Set interval to 100ms to quickly preview a sequence of images</li>
220
+ <li><strong>Dataset Loading:</strong> Use "one-shot" mode to load a complete dataset for AI/ML processing</li>
221
+ </ul>
222
+
223
+ <h3>Status Display</h3>
224
+ <p>The node displays its current state and progress:</p>
225
+ <ul>
226
+ <li><strong>Stopped:</strong> Node is not emitting images</li>
227
+ <li><strong>Scanning folder:</strong> Reading directory contents</li>
228
+ <li><strong>Loading [filename]:</strong> Currently loading an image</li>
229
+ <li><strong>[n/total]: [filename]:</strong> Successfully emitted image n of total</li>
230
+ <li><strong>Completed all images:</strong> One-shot mode finished</li>
231
+ <li><strong>Error:</strong> Error occurred during operation</li>
232
+ </ul>
233
+
234
+ <h3>Error Handling</h3>
235
+ <p>If the folder path is invalid, contains no images, or an image cannot be read, the node will display a warning in the debug panel and update its status accordingly.</p>
236
+
237
+ <h3>Performance</h3>
238
+ <p>Image loading is performed asynchronously using Sharp for optimal performance. Each image is loaded on demand, so memory usage remains low even with large folders.</p>
239
+
240
+ <h3>Tips</h3>
241
+ <ul>
242
+ <li>Use relative paths for portability across systems</li>
243
+ <li>Images are emitted in alphabetical order by filename</li>
244
+ <li>Connect to transform nodes (resize, crop, etc.) for automated batch processing</li>
245
+ <li>Use the metadata in <code>msg._folderIn</code> to track progress or create custom workflows</li>
246
+ <li>Adjust interval based on your processing pipeline speed to avoid message queue buildup</li>
247
+ </ul>
248
+ </script>
@@ -0,0 +1,335 @@
1
+ /**
2
+ * @file Node.js logic for the Folder-In node with interval-based image emission.
3
+ * Scans a folder for images and emits them one by one at configurable intervals.
4
+ * Features a toggle button (like inject node) to start/stop emission.
5
+ * @author Rosepetal
6
+ */
7
+
8
+ const { performance } = require('perf_hooks');
9
+ const sharp = require('sharp');
10
+ const fs = require('fs').promises;
11
+ const path = require('path');
12
+
13
+ module.exports = function(RED) {
14
+ const NodeUtils = require('../../lib/node-utils.js')(RED);
15
+
16
+ function FolderInNode(config) {
17
+ RED.nodes.createNode(this, config);
18
+ const node = this;
19
+
20
+ // Node state
21
+ let running = false;
22
+ let intervalTimer = null;
23
+ let imageFiles = [];
24
+ let currentIndex = 0;
25
+ let folderPath = null;
26
+
27
+ // Supported image extensions
28
+ const IMAGE_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.webp', '.bmp', '.gif', '.tiff'];
29
+
30
+ /**
31
+ * Scans the configured folder for image files
32
+ */
33
+ async function scanFolder() {
34
+ try {
35
+ // Resolve folder path
36
+ if (config.folderPathType === 'msg' || config.folderPathType === 'flow' || config.folderPathType === 'global') {
37
+ // For dynamic paths, we need a message context - skip scan if not available
38
+ node.warn("Dynamic folder paths require message input to resolve");
39
+ return [];
40
+ } else {
41
+ folderPath = config.folderPath;
42
+ }
43
+
44
+ if (!folderPath) {
45
+ node.warn("Folder path is not configured");
46
+ return [];
47
+ }
48
+
49
+ // Read directory contents
50
+ const files = await fs.readdir(folderPath);
51
+
52
+ // Filter for image files and sort alphabetically
53
+ const images = files
54
+ .filter(file => {
55
+ const ext = path.extname(file).toLowerCase();
56
+ return IMAGE_EXTENSIONS.includes(ext);
57
+ })
58
+ .sort()
59
+ .map(file => path.join(folderPath, file));
60
+
61
+ if (images.length === 0) {
62
+ node.warn(`No image files found in folder: ${folderPath}`);
63
+ }
64
+
65
+ return images;
66
+ } catch (err) {
67
+ node.error(`Error scanning folder: ${err.message}`);
68
+ return [];
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Loads and emits the next image
74
+ */
75
+ async function emitNextImage() {
76
+ if (imageFiles.length === 0) {
77
+ node.warn("No images to emit");
78
+ stopEmission();
79
+ return;
80
+ }
81
+
82
+ try {
83
+ const startTime = performance.now();
84
+ const filePath = imageFiles[currentIndex];
85
+ const fileName = path.basename(filePath);
86
+
87
+ node.status({ fill: "blue", shape: "dot", text: `Loading ${fileName}...` });
88
+
89
+ // Check file accessibility
90
+ await fs.access(filePath, fs.constants.R_OK);
91
+
92
+ // Read encoded file once so we can reuse it for both decoding and debug preview
93
+ const fileBuffer = await fs.readFile(filePath);
94
+
95
+ // Use Sharp to decode image with full metadata
96
+ const sharpInstance = sharp(fileBuffer);
97
+ const decodeStart = performance.now();
98
+ const { data, info } = await sharpInstance
99
+ .clone()
100
+ .raw()
101
+ .toBuffer({ resolveWithObject: true });
102
+ const decodeMs = performance.now() - decodeStart;
103
+
104
+ // Determine colorSpace from Sharp info
105
+ let colorSpace;
106
+ switch (info.channels) {
107
+ case 1: colorSpace = 'GRAY'; break;
108
+ case 3: colorSpace = 'RGB'; break;
109
+ case 4: colorSpace = 'RGBA'; break;
110
+ default: throw new Error(`Unsupported number of channels: ${info.channels}`);
111
+ }
112
+
113
+ // Create complete image structure
114
+ const outputImageObject = {
115
+ data: data,
116
+ width: info.width,
117
+ height: info.height,
118
+ channels: info.channels,
119
+ colorSpace: colorSpace,
120
+ dtype: "uint8"
121
+ };
122
+
123
+ // Create new message
124
+ const msg = {};
125
+ const outputPath = config.outputPath || "payload";
126
+ const outputPathType = config.outputPathType || "msg";
127
+
128
+ if (outputPathType === 'msg') {
129
+ RED.util.setMessageProperty(msg, outputPath, outputImageObject);
130
+ } else if (outputPathType === 'flow') {
131
+ node.context().flow.set(outputPath, outputImageObject);
132
+ } else if (outputPathType === 'global') {
133
+ node.context().global.set(outputPath, outputImageObject);
134
+ }
135
+
136
+ // Add metadata to message
137
+ msg._folderIn = {
138
+ fileName: fileName,
139
+ filePath: filePath,
140
+ index: currentIndex,
141
+ total: imageFiles.length
142
+ };
143
+
144
+ // Debug image display if enabled
145
+ let debugFormat = null;
146
+ const debugEnabled = config.debugEnabled === true || config.debugEnabled === 'true';
147
+ if (debugEnabled) {
148
+ try {
149
+ let debugWidthRaw = config.debugWidth;
150
+ const debugWidthType = config.debugWidthType || 'num';
151
+
152
+ try {
153
+ debugWidthRaw = NodeUtils.resolveDimension(
154
+ node,
155
+ debugWidthType,
156
+ config.debugWidth,
157
+ msg
158
+ );
159
+ } catch (resolveErr) {
160
+ node.warn(`Debug width resolution failed (${resolveErr.message}); using default 200`);
161
+ }
162
+
163
+ const debugWidth = Math.max(1, parseInt(debugWidthRaw, 10) || 200);
164
+
165
+ // Prefer sending the original encoded buffer when format is supported
166
+ let debugSource = outputImageObject;
167
+ let debugFormatHint = 'raw';
168
+
169
+ if (info && info.format) {
170
+ const normalizedFormat = info.format.toLowerCase();
171
+ if (normalizedFormat === 'jpeg' || normalizedFormat === 'jpg') {
172
+ debugSource = fileBuffer;
173
+ debugFormatHint = 'jpg';
174
+ } else if (normalizedFormat === 'png') {
175
+ debugSource = fileBuffer;
176
+ debugFormatHint = 'png';
177
+ } else if (normalizedFormat === 'webp') {
178
+ debugSource = fileBuffer;
179
+ debugFormatHint = 'webp';
180
+ }
181
+ }
182
+
183
+ const debugResult = await NodeUtils.debugImageDisplay(
184
+ debugSource,
185
+ debugFormatHint,
186
+ 90,
187
+ node,
188
+ debugEnabled,
189
+ debugWidth
190
+ );
191
+
192
+ if (debugResult) {
193
+ debugFormat = debugResult.formatMessage;
194
+ msg._folderIn.debug = debugFormat;
195
+ }
196
+ } catch (debugError) {
197
+ node.warn(`Debug display error: ${debugError.message}`);
198
+ }
199
+ }
200
+
201
+ // Update status
202
+ const statusParts = [`${currentIndex + 1}/${imageFiles.length}: ${fileName}`];
203
+ if (debugFormat) {
204
+ statusParts.push(debugFormat);
205
+ }
206
+ node.status({ fill: "green", shape: "dot", text: statusParts.join(' | ') });
207
+
208
+ const totalTime = performance.now() - startTime;
209
+ const taskMs = Math.max(0, totalTime - decodeMs);
210
+ NodeUtils.recordPerformanceMetrics(node, msg, {
211
+ convertMs: decodeMs,
212
+ taskMs: taskMs
213
+ }, totalTime);
214
+
215
+ // Send message
216
+ node.send(msg);
217
+
218
+ // Advance to next image
219
+ currentIndex++;
220
+
221
+ // Handle loop vs one-shot mode
222
+ if (currentIndex >= imageFiles.length) {
223
+ if (config.mode === 'loop') {
224
+ // Loop mode: restart from beginning
225
+ currentIndex = 0;
226
+ } else {
227
+ // One-shot mode: stop emission
228
+ stopEmission();
229
+ node.status({ fill: "grey", shape: "ring", text: "Completed all images" });
230
+ }
231
+ }
232
+
233
+ } catch (err) {
234
+ node.error(`Error loading image: ${err.message}`);
235
+ node.status({ fill: "red", shape: "ring", text: `Error: ${err.message}` });
236
+ }
237
+ }
238
+
239
+ /**
240
+ * Starts the interval-based emission
241
+ */
242
+ async function startEmission() {
243
+ if (running) return;
244
+
245
+ node.status({ fill: "yellow", shape: "dot", text: "Scanning folder..." });
246
+
247
+ // Scan folder for images
248
+ imageFiles = await scanFolder();
249
+
250
+ if (imageFiles.length === 0) {
251
+ node.status({ fill: "red", shape: "ring", text: "No images found" });
252
+ return;
253
+ }
254
+
255
+ // Reset index
256
+ currentIndex = 0;
257
+ running = true;
258
+
259
+ // Get interval value
260
+ let intervalMs = config.interval || 1000;
261
+ if (config.intervalType === 'msg' || config.intervalType === 'flow' || config.intervalType === 'global') {
262
+ // For dynamic intervals, use default for now - can be enhanced with message input
263
+ intervalMs = config.interval || 1000;
264
+ }
265
+ intervalMs = parseInt(intervalMs);
266
+
267
+ node.status({ fill: "green", shape: "dot", text: `Started (${imageFiles.length} images, ${intervalMs}ms)` });
268
+
269
+ // Emit first image immediately
270
+ await emitNextImage();
271
+
272
+ // Start interval timer for subsequent images
273
+ if (running) { // Check if still running after first emit
274
+ intervalTimer = setInterval(emitNextImage, intervalMs);
275
+ }
276
+ }
277
+
278
+ /**
279
+ * Stops the interval-based emission
280
+ */
281
+ function stopEmission() {
282
+ if (!running) return;
283
+
284
+ running = false;
285
+ if (intervalTimer) {
286
+ clearInterval(intervalTimer);
287
+ intervalTimer = null;
288
+ }
289
+
290
+ node.status({ fill: "grey", shape: "ring", text: "Stopped" });
291
+ }
292
+
293
+ /**
294
+ * Toggles emission on/off
295
+ */
296
+ function toggleEmission() {
297
+ if (running) {
298
+ stopEmission();
299
+ } else {
300
+ startEmission();
301
+ }
302
+ }
303
+
304
+ // HTTP endpoint for button clicks (like inject node)
305
+ RED.httpAdmin.post("/folder-in/:id", RED.auth.needsPermission('folder-in.write'), function(req, res) {
306
+ const nodeId = req.params.id;
307
+ const targetNode = RED.nodes.getNode(nodeId);
308
+
309
+ if (targetNode) {
310
+ try {
311
+ targetNode.toggleEmission();
312
+ res.sendStatus(200);
313
+ } catch(err) {
314
+ res.sendStatus(500);
315
+ targetNode.error("Failed to toggle: " + err.toString());
316
+ }
317
+ } else {
318
+ res.sendStatus(404);
319
+ }
320
+ });
321
+
322
+ // Make toggle function accessible to HTTP endpoint
323
+ node.toggleEmission = toggleEmission;
324
+
325
+ // Cleanup on node close
326
+ node.on('close', function() {
327
+ stopEmission();
328
+ });
329
+
330
+ // Initial status
331
+ node.status({ fill: "grey", shape: "ring", text: "Stopped" });
332
+ }
333
+
334
+ RED.nodes.registerType("folder-in", FolderInNode);
335
+ };