@rosepetal/node-red-contrib-image-tools 1.3.1 → 1.4.0

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.
@@ -15,46 +15,146 @@ const path = require('path');
15
15
 
16
16
  module.exports = function(RED) {
17
17
  const NodeUtils = require('../../lib/node-utils.js')(RED);
18
-
18
+
19
+ const dirCache = new Map();
20
+
21
+ async function getCachedDir(folderPath) {
22
+ if (dirCache.has(folderPath)) return dirCache.get(folderPath);
23
+ const map = new Map();
24
+ try {
25
+ const entries = await fs.readdir(folderPath, { withFileTypes: true });
26
+ const files = entries.filter(e => e.isFile());
27
+ const stats = await Promise.all(
28
+ files.map(async (f) => {
29
+ const st = await fs.stat(path.join(folderPath, f.name));
30
+ return { name: f.name, mtimeMs: st.mtimeMs };
31
+ })
32
+ );
33
+ for (const { name, mtimeMs } of stats) map.set(name, mtimeMs);
34
+ } catch {
35
+ // folder doesn't exist yet — empty cache is fine
36
+ }
37
+ dirCache.set(folderPath, map);
38
+ return map;
39
+ }
40
+
19
41
  function ImageOutNode(config) {
20
42
  RED.nodes.createNode(this, config);
21
43
  const node = this;
22
-
44
+
23
45
  // Initialize node state
24
- node.active = config.active !== false; // Default to true if not set
46
+ node.active = config.active !== false;
25
47
  let diskCheckErrorLogged = false;
26
-
27
- // Update node appearance based on active state
48
+
28
49
  updateNodeStatus();
29
-
50
+
30
51
  function updateNodeStatus() {
31
52
  if (!node.active) {
32
53
  node.status({ fill: "grey", shape: "dot", text: "inactive" });
33
54
  } else {
34
- node.status({}); // Clear status when active and idle
55
+ node.status({});
35
56
  }
36
57
  }
37
-
58
+
59
+ // Image encoding helper — shared by single and multiple modes
60
+ async function encodeImage(image, { format, quality, pngCompression, webpLossless, webpSmartSubsample, hasWebpEffort, webpEffort }) {
61
+ // Encoded buffer input (JPEG, PNG, WebP)
62
+ if (Buffer.isBuffer(image) && !image.width && !image.height) {
63
+ let inputFormat;
64
+ try {
65
+ const metadata = await sharp(image).metadata();
66
+ inputFormat = metadata.format;
67
+ } catch {
68
+ inputFormat = null;
69
+ }
70
+
71
+ const sameFormat = inputFormat === format || (inputFormat === 'jpeg' && format === 'jpg');
72
+ const needsWebpReencode = format === 'webp' && (webpLossless || hasWebpEffort);
73
+
74
+ if (sameFormat && !needsWebpReencode) {
75
+ return image;
76
+ }
77
+
78
+ const inst = sharp(image);
79
+ switch (format) {
80
+ case 'jpg': return inst.jpeg({ quality }).toBuffer();
81
+ case 'png': return inst.png({ compressionLevel: pngCompression }).toBuffer();
82
+ case 'webp': {
83
+ const wo = { quality };
84
+ if (webpLossless) wo.lossless = true;
85
+ if (!webpLossless && webpSmartSubsample) wo.smartSubsample = true;
86
+ if (hasWebpEffort) wo.effort = webpEffort;
87
+ return inst.webp(wo).toBuffer();
88
+ }
89
+ case 'bmp': throw new Error('BMP output requires raw image data, not an encoded buffer');
90
+ default: throw new Error(`Unsupported format: ${format}`);
91
+ }
92
+ }
93
+
94
+ // Raw image data
95
+ const validated = NodeUtils.validateImageStructure(image, node);
96
+ if (!validated) throw new Error("Invalid image structure");
97
+
98
+ const colorSpace = validated.colorSpace;
99
+ const channels = validated.channels;
100
+ let data = validated.data;
101
+
102
+ // BMP: encode raw pixels directly (no Sharp)
103
+ if (format === 'bmp') {
104
+ let nativeData = data;
105
+ if (colorSpace === 'RGB' || colorSpace === 'RGBA') {
106
+ nativeData = Buffer.from(data);
107
+ for (let i = 0; i < nativeData.length; i += channels) {
108
+ const t = nativeData[i]; nativeData[i] = nativeData[i + 2]; nativeData[i + 2] = t;
109
+ }
110
+ }
111
+ const buf = Buffer.isBuffer(nativeData) ? nativeData : Buffer.from(nativeData);
112
+ return encodeBmpRaw(buf, validated.width, validated.height, channels);
113
+ }
114
+
115
+ // BGR/BGRA → RGB/RGBA for Sharp
116
+ if (colorSpace === 'BGR' || colorSpace === 'BGRA') {
117
+ data = Buffer.from(data);
118
+ for (let i = 0; i < data.length; i += channels) {
119
+ const t = data[i]; data[i] = data[i + 2]; data[i + 2] = t;
120
+ }
121
+ }
122
+
123
+ const inst = sharp(data, {
124
+ raw: { width: validated.width, height: validated.height, channels }
125
+ });
126
+ if (colorSpace === 'GRAY') inst.toColourspace('b-w');
127
+
128
+ switch (format) {
129
+ case 'jpg': return inst.jpeg({ quality }).toBuffer();
130
+ case 'png': return inst.png({ compressionLevel: pngCompression }).toBuffer();
131
+ case 'webp': {
132
+ const wo = { quality };
133
+ if (webpLossless) wo.lossless = true;
134
+ if (!webpLossless && webpSmartSubsample) wo.smartSubsample = true;
135
+ if (hasWebpEffort) wo.effort = webpEffort;
136
+ return inst.webp(wo).toBuffer();
137
+ }
138
+ default: throw new Error(`Unsupported format: ${format}`);
139
+ }
140
+ }
141
+
38
142
  node.on('input', async function(msg, send, done) {
39
- // Skip processing if node is inactive
40
143
  if (!node.active) {
41
144
  if (done) done();
42
145
  return;
43
146
  }
44
-
147
+
45
148
  const startTime = Date.now();
46
-
149
+
47
150
  try {
48
151
  const evaluateProperty = (value, type, fallbackType = 'str') => {
49
152
  return new Promise((resolve, reject) => {
50
153
  const actualType = type || fallbackType;
51
154
  try {
52
155
  RED.util.evaluateNodeProperty(value, actualType, node, msg, (err, result) => {
53
- if (err) {
54
- reject(err);
55
- } else {
56
- resolve(result);
57
- }
156
+ if (err) reject(err);
157
+ else resolve(result);
58
158
  });
59
159
  } catch (err) {
60
160
  reject(err);
@@ -62,27 +162,23 @@ module.exports = function(RED) {
62
162
  });
63
163
  };
64
164
 
65
- // Resolve folder path (supports typed inputs)
66
- const folderPathType = config.folderPathType || 'str';
67
- let folderPath;
68
- if (['msg', 'flow', 'global', 'jsonata', 'env'].includes(folderPathType)) {
69
- folderPath = await evaluateProperty(config.folderPath, folderPathType);
70
- } else {
71
- folderPath = config.folderPath || '.';
72
- }
73
-
74
- if (folderPath === undefined || folderPath === null || String(folderPath).trim() === '') {
75
- throw new Error('Folder path is not configured or resolved.');
165
+ if (!sharp) {
166
+ throw new Error('Sharp is not available. Install "sharp" in your Node-RED userDir and restart Node-RED.');
76
167
  }
77
- folderPath = String(folderPath);
78
168
 
79
- try {
80
- await fs.mkdir(folderPath, { recursive: true });
81
- } catch (mkdirErr) {
82
- throw new Error(`Cannot create directory: ${mkdirErr.message}`);
83
- }
169
+ // Shared format config
170
+ let format = (config.outputFormat || 'jpg').toLowerCase();
171
+ if (!['jpg', 'png', 'webp', 'bmp'].includes(format)) format = 'jpg';
172
+ const quality = parseInt(config.outputQuality, 10) || 90;
173
+ const pngCompression = Math.max(0, Math.min(9, parseInt(config.pngCompression, 10) || 0));
174
+ const webpLossless = config.webpLossless === true || config.webpLossless === 'true';
175
+ const webpSmartSubsample = config.webpSmartSubsample === true || config.webpSmartSubsample === 'true';
176
+ const parsedEffort = parseInt(config.webpEffort, 10);
177
+ const hasWebpEffort = Number.isInteger(parsedEffort);
178
+ const webpEffort = hasWebpEffort ? Math.min(6, Math.max(0, parsedEffort)) : null;
179
+ const encodeOpts = { format, quality, pngCompression, webpLossless, webpSmartSubsample, hasWebpEffort, webpEffort };
84
180
 
85
- // Resolve optional maximum image count
181
+ // Shared max images
86
182
  let maxImages = 0;
87
183
  const maxImagesType = config.maxImagesType || 'num';
88
184
  const maxImagesConfigured = !(
@@ -90,18 +186,13 @@ module.exports = function(RED) {
90
186
  config.maxImages === null ||
91
187
  (typeof config.maxImages === 'string' && config.maxImages.trim() === '')
92
188
  );
93
-
94
189
  if (maxImagesConfigured || ['msg', 'flow', 'global', 'jsonata', 'env'].includes(maxImagesType)) {
95
190
  try {
96
191
  const resolvedMax = await evaluateProperty(config.maxImages, maxImagesType);
97
192
  if (resolvedMax !== undefined && resolvedMax !== null && resolvedMax !== '') {
98
193
  const numericMax = parseInt(resolvedMax, 10);
99
- if (Number.isNaN(numericMax)) {
100
- throw new Error(`Value "${resolvedMax}" is not a valid integer.`);
101
- }
102
- if (numericMax < 0) {
103
- throw new Error('Value must be zero or a positive integer.');
104
- }
194
+ if (Number.isNaN(numericMax)) throw new Error(`Value "${resolvedMax}" is not a valid integer.`);
195
+ if (numericMax < 0) throw new Error('Value must be zero or a positive integer.');
105
196
  maxImages = numericMax;
106
197
  }
107
198
  } catch (err) {
@@ -109,30 +200,206 @@ module.exports = function(RED) {
109
200
  }
110
201
  }
111
202
 
203
+ // ===== MULTIPLE MODE =====
204
+ if (config.mode === 'multiple') {
205
+ node.status({ fill: 'blue', shape: 'dot', text: 'saving...' });
206
+
207
+ const saveConfigType = config.saveConfigType || 'msg';
208
+ let saveConfig = await evaluateProperty(config.saveConfig || 'payload', saveConfigType);
209
+ if (!Array.isArray(saveConfig)) {
210
+ if (saveConfig && typeof saveConfig === 'object') {
211
+ saveConfig = [saveConfig];
212
+ } else {
213
+ throw new Error('Input must resolve to an array or object.');
214
+ }
215
+ }
216
+ if (saveConfig.length === 0) {
217
+ node.warn('Empty array — nothing to save.');
218
+ node.status({ fill: 'yellow', shape: 'ring', text: 'empty array' });
219
+ if (done) done();
220
+ return;
221
+ }
222
+
223
+ const imageField = config.imageField || 'bitmap';
224
+ const filenameField = config.filenameField || 'filename';
225
+ const filenameFieldType = config.filenameFieldType || 'item';
226
+ const outputDirField = config.outputDirField || 'outputDir';
227
+ const outputDirFieldType = config.outputDirFieldType || 'item';
228
+
229
+ let sharedFilename = null;
230
+ if (filenameFieldType !== 'item') {
231
+ sharedFilename = await evaluateProperty(filenameField, filenameFieldType);
232
+ }
233
+ let sharedOutputDir = null;
234
+ if (outputDirFieldType !== 'item') {
235
+ sharedOutputDir = await evaluateProperty(outputDirField, outputDirFieldType);
236
+ }
237
+
238
+ const results = [];
239
+ let skipped = 0;
240
+
241
+ for (let idx = 0; idx < saveConfig.length; idx++) {
242
+ try {
243
+ const item = saveConfig[idx];
244
+ if (!item || typeof item !== 'object') {
245
+ node.warn(`Item ${idx}: not an object, skipping.`);
246
+ skipped++;
247
+ continue;
248
+ }
249
+
250
+ const image = item[imageField];
251
+ if (!image) {
252
+ node.warn(`Item ${idx}: no image at "${imageField}", skipping.`);
253
+ skipped++;
254
+ continue;
255
+ }
256
+
257
+ // Resolve folder
258
+ const folderPath = String(
259
+ outputDirFieldType === 'item'
260
+ ? (item[outputDirField] ?? '')
261
+ : (sharedOutputDir ?? '')
262
+ ).trim();
263
+ if (!folderPath) {
264
+ node.warn(`Item ${idx}: empty folder path, skipping.`);
265
+ skipped++;
266
+ continue;
267
+ }
268
+ await fs.mkdir(folderPath, { recursive: true });
269
+
270
+ // Disk check
271
+ const diskInfo = await getDiskUsageInfo(folderPath);
272
+ if (diskInfo && diskInfo.usedRatio >= 0.9) {
273
+ const pct = (diskInfo.usedRatio * 100).toFixed(1);
274
+ node.warn(`Storage ${pct}% full, skipping remaining items.`);
275
+ node.status({ fill: 'yellow', shape: 'ring', text: `disk ${pct}% full` });
276
+ break;
277
+ }
278
+
279
+ // Resolve filename
280
+ const filenameRaw = String(
281
+ filenameFieldType === 'item'
282
+ ? (item[filenameField] ?? '')
283
+ : (sharedFilename ?? '')
284
+ ).trim();
285
+
286
+ // Determine per-item format & extension (filename ext can override)
287
+ let itemFormat = format;
288
+ let fileExtension = format === 'jpg' ? 'jpg' : format;
289
+ let baseFilename;
290
+
291
+ if (filenameRaw) {
292
+ if (/[\\/]/.test(filenameRaw)) {
293
+ node.warn(`Item ${idx}: filename contains path separators, skipping.`);
294
+ skipped++;
295
+ continue;
296
+ }
297
+ const parsed = path.parse(filenameRaw);
298
+ if (parsed.ext) {
299
+ const extLower = parsed.ext.slice(1).toLowerCase();
300
+ if (['jpg', 'jpeg', 'png', 'webp', 'bmp'].includes(extLower)) {
301
+ fileExtension = parsed.ext.slice(1);
302
+ itemFormat = extLower === 'jpeg' ? 'jpg' : extLower;
303
+ }
304
+ baseFilename = parsed.name;
305
+ } else {
306
+ baseFilename = parsed.base;
307
+ }
308
+ } else {
309
+ const ts = new Date()
310
+ .toISOString()
311
+ .replace(/[-:]/g, '')
312
+ .replace(/\.(\d{3})Z$/, '-$1Z')
313
+ .replace('T', '_');
314
+ baseFilename = `image_${ts}`;
315
+ }
316
+
317
+ let filename = `${baseFilename}.${fileExtension}`;
318
+ let filePath = path.join(folderPath, filename);
319
+
320
+ // Overwrite protection
321
+ if (config.overwriteProtection !== false) {
322
+ const dirMap = await getCachedDir(folderPath);
323
+ let counter = 2;
324
+ while (dirMap.has(filename)) {
325
+ filename = `${baseFilename}_${counter}.${fileExtension}`;
326
+ filePath = path.join(folderPath, filename);
327
+ counter++;
328
+ if (counter > 1000) throw new Error('Too many file variations');
329
+ }
330
+ }
331
+
332
+ // Encode & write
333
+ const itemEncodeOpts = itemFormat !== format
334
+ ? { ...encodeOpts, format: itemFormat }
335
+ : encodeOpts;
336
+ const outputBuffer = await encodeImage(image, itemEncodeOpts);
337
+ await fs.writeFile(filePath, outputBuffer);
338
+ dirCache.get(folderPath)?.set(filename, Date.now());
339
+
340
+ if (maxImages > 0) {
341
+ try {
342
+ await enforceMaxImages(folderPath, maxImages, dirCache.get(folderPath));
343
+ } catch (policyErr) {
344
+ node.warn(`Max images enforcement failed: ${policyErr.message}`);
345
+ }
346
+ }
347
+
348
+ results.push({ path: filePath, filename, format: itemFormat, extension: fileExtension });
349
+ } catch (itemErr) {
350
+ node.warn(`Item ${idx}: ${itemErr.message}`);
351
+ skipped++;
352
+ }
353
+ }
354
+
355
+ if (results.length === 0) {
356
+ throw new Error(`All ${saveConfig.length} items failed.`);
357
+ }
358
+
359
+ const elapsedMs = Date.now() - startTime;
360
+ const statusText = skipped > 0
361
+ ? `saved ${results.length}/${saveConfig.length} files (${elapsedMs}ms)`
362
+ : `saved ${results.length} files (${elapsedMs}ms)`;
363
+ node.status({ fill: 'green', shape: 'dot', text: statusText });
364
+
365
+ if (done) done();
366
+ return;
367
+ }
368
+
369
+ // ===== SINGLE MODE =====
370
+
371
+ // Resolve folder path
372
+ const folderPathType = config.folderPathType || 'str';
373
+ let folderPath;
374
+ if (['msg', 'flow', 'global', 'jsonata', 'env'].includes(folderPathType)) {
375
+ folderPath = await evaluateProperty(config.folderPath, folderPathType);
376
+ } else {
377
+ folderPath = config.folderPath || '.';
378
+ }
379
+ if (folderPath === undefined || folderPath === null || String(folderPath).trim() === '') {
380
+ throw new Error('Folder path is not configured or resolved.');
381
+ }
382
+ folderPath = String(folderPath);
383
+ try {
384
+ await fs.mkdir(folderPath, { recursive: true });
385
+ } catch (mkdirErr) {
386
+ throw new Error(`Cannot create directory: ${mkdirErr.message}`);
387
+ }
388
+
112
389
  // Retrieve input image
113
390
  const inputPath = config.inputPath || 'payload';
114
391
  const inputPathType = config.inputPathType || 'msg';
115
-
116
392
  let image;
117
393
  if (inputPathType === 'msg') {
118
394
  const { value, error } = NodeUtils.safeGetMessageProperty(msg, inputPath);
119
- if (error) {
120
- throw new Error(`Invalid inputPath "${inputPath}": ${error.message}`);
121
- }
395
+ if (error) throw new Error(`Invalid inputPath "${inputPath}": ${error.message}`);
122
396
  image = value;
123
397
  } else if (inputPathType === 'flow') {
124
398
  image = node.context().flow.get(inputPath);
125
399
  } else if (inputPathType === 'global') {
126
400
  image = node.context().global.get(inputPath);
127
401
  }
128
-
129
- if (!image) {
130
- throw new Error('No image data found at specified input path');
131
- }
132
-
133
- if (!sharp) {
134
- throw new Error('Sharp is not available. Install "sharp" in your Node-RED userDir and restart Node-RED.');
135
- }
402
+ if (!image) throw new Error('No image data found at specified input path');
136
403
 
137
404
  node.status({ fill: 'blue', shape: 'dot', text: 'saving...' });
138
405
 
@@ -144,22 +411,19 @@ module.exports = function(RED) {
144
411
  config.filenameFull === null ||
145
412
  (typeof config.filenameFull === 'string' && config.filenameFull.trim() === '')
146
413
  );
147
-
148
414
  if (hasFullNameConfig || ['msg', 'flow', 'global', 'jsonata', 'env'].includes(fullNameType)) {
149
415
  try {
150
416
  const evaluated = await evaluateProperty(config.filenameFull, fullNameType);
151
417
  if (evaluated !== undefined && evaluated !== null) {
152
418
  const trimmed = String(evaluated).trim();
153
- if (trimmed) {
154
- resolvedFullFilename = trimmed;
155
- }
419
+ if (trimmed) resolvedFullFilename = trimmed;
156
420
  }
157
421
  } catch (err) {
158
422
  throw new Error(`Unable to resolve full filename: ${err.message}`);
159
423
  }
160
424
  }
161
425
 
162
- // Resolve prefix when full filename not provided
426
+ // Resolve prefix
163
427
  const prefixType = config.filenamePrefixType || 'str';
164
428
  let prefixValue = config.filenamePrefix || '';
165
429
  if (['msg', 'flow', 'global', 'jsonata', 'env'].includes(prefixType)) {
@@ -173,27 +437,13 @@ module.exports = function(RED) {
173
437
  prefixValue = (prefixValue || '').trim();
174
438
  const prefix = prefixValue ? `${prefixValue}_` : 'image_';
175
439
 
176
- // Determine format & extension
177
- let format = (config.outputFormat || 'jpg').toLowerCase();
178
- if (!['jpg', 'png', 'webp'].includes(format)) {
179
- format = 'jpg';
180
- }
440
+ // Build filename
181
441
  let fileExtension = format === 'jpg' ? 'jpg' : format;
182
- const webpLossless = config.webpLossless === true || config.webpLossless === 'true';
183
- const webpSmartSubsample = config.webpSmartSubsample === true || config.webpSmartSubsample === 'true';
184
- const parsedEffort = parseInt(config.webpEffort, 10);
185
- const hasWebpEffort = Number.isInteger(parsedEffort);
186
- // Sharp expects 0-6 (6 = slowest/smallest); clamp to be safe
187
- const webpEffort = hasWebpEffort ? Math.min(6, Math.max(0, parsedEffort)) : null;
188
-
189
- // Build filename (timestamp-based fallback)
190
- const now = new Date();
191
- const timestamp = now.getFullYear().toString() +
192
- (now.getMonth() + 1).toString().padStart(2, '0') +
193
- now.getDate().toString().padStart(2, '0') + '_' +
194
- now.getHours().toString().padStart(2, '0') +
195
- now.getMinutes().toString().padStart(2, '0') +
196
- now.getSeconds().toString().padStart(2, '0');
442
+ const timestamp = new Date()
443
+ .toISOString()
444
+ .replace(/[-:]/g, '')
445
+ .replace(/\.(\d{3})Z$/, '-$1Z')
446
+ .replace('T', '_');
197
447
 
198
448
  let baseFilename;
199
449
  if (resolvedFullFilename) {
@@ -203,7 +453,7 @@ module.exports = function(RED) {
203
453
  const parsed = path.parse(resolvedFullFilename);
204
454
  if (parsed.ext) {
205
455
  const extLower = parsed.ext.slice(1).toLowerCase();
206
- if (!['jpg', 'jpeg', 'png', 'webp'].includes(extLower)) {
456
+ if (!['jpg', 'jpeg', 'png', 'webp', 'bmp'].includes(extLower)) {
207
457
  throw new Error(`Unsupported extension in filename: ${parsed.ext}`);
208
458
  }
209
459
  fileExtension = parsed.ext.slice(1);
@@ -226,14 +476,13 @@ module.exports = function(RED) {
226
476
  let filePath = path.join(folderPath, filename);
227
477
 
228
478
  if (config.overwriteProtection !== false) {
479
+ const dirMap = await getCachedDir(folderPath);
229
480
  let counter = 2;
230
- while (await fileExists(filePath)) {
481
+ while (dirMap.has(filename)) {
231
482
  filename = `${baseFilename}_${counter}.${fileExtension}`;
232
483
  filePath = path.join(folderPath, filename);
233
484
  counter += 1;
234
- if (counter > 1000) {
235
- throw new Error('Too many file variations exist');
236
- }
485
+ if (counter > 1000) throw new Error('Too many file variations exist');
237
486
  }
238
487
  }
239
488
 
@@ -246,129 +495,16 @@ module.exports = function(RED) {
246
495
  return;
247
496
  }
248
497
 
249
- // Convert image to buffer based on format
250
- let outputBuffer;
251
- const quality = parseInt(config.outputQuality, 10) || 90;
252
-
253
- // Check if image is already an encoded Buffer (JPEG, PNG, WebP)
254
- if (Buffer.isBuffer(image) && !image.width && !image.height) {
255
- // It's an encoded image buffer
256
- // We can either save it directly or re-encode if format is different
257
-
258
- // Try to detect the input format using Sharp metadata
259
- let inputFormat;
260
- try {
261
- const metadata = await sharp(image).metadata();
262
- inputFormat = metadata.format; // Will be 'jpeg', 'png', 'webp', etc.
263
- } catch (err) {
264
- // If we can't detect format, we'll re-encode anyway
265
- inputFormat = null;
266
- }
267
-
268
- // Check if we need to re-encode or can save directly
269
- const sameFormat =
270
- inputFormat === format ||
271
- (inputFormat === 'jpeg' && format === 'jpg');
272
-
273
- const needsWebpReencode =
274
- format === 'webp' && (webpLossless || hasWebpEffort);
275
-
276
- if (sameFormat && !needsWebpReencode) {
277
- // Same format and no special WebP options: save directly (fastest)
278
- outputBuffer = image;
279
- } else {
280
- // Different format or unknown input, re-encode using Sharp
281
- const sharpInstance = sharp(image);
282
-
283
- switch (format) {
284
- case 'jpg':
285
- outputBuffer = await sharpInstance.jpeg({ quality }).toBuffer();
286
- break;
287
- case 'png':
288
- const pngOptions = config.pngOptimize ?
289
- { compressionLevel: 9, palette: true } :
290
- { compressionLevel: 6 };
291
- outputBuffer = await sharpInstance.png(pngOptions).toBuffer();
292
- break;
293
- case 'webp':
294
- {
295
- const webpOptions = { quality };
296
- if (webpLossless) webpOptions.lossless = true;
297
- if (!webpLossless && webpSmartSubsample) webpOptions.smartSubsample = true;
298
- if (hasWebpEffort) webpOptions.effort = webpEffort;
299
- outputBuffer = await sharpInstance.webp(webpOptions).toBuffer();
300
- }
301
- break;
302
- default:
303
- throw new Error(`Unsupported format: ${format}`);
304
- }
305
- }
306
- } else {
307
- // It's raw image data - validate and process as before
308
- const validatedImage = NodeUtils.validateImageStructure(image, node);
309
- if (!validatedImage) {
310
- throw new Error("Invalid image structure");
311
- }
312
-
313
- // Convert from raw image format to Sharp-compatible format
314
- const colorSpace = validatedImage.colorSpace;
315
- const channels = validatedImage.channels;
316
- let data = validatedImage.data;
317
-
318
- // BGR/BGRA → RGB/RGBA for Sharp
319
- if (colorSpace === 'BGR' || colorSpace === 'BGRA') {
320
- data = Buffer.from(data); // Copy to avoid mutating shared memory
321
- for (let i = 0; i < data.length; i += channels) {
322
- const t = data[i];
323
- data[i] = data[i + 2];
324
- data[i + 2] = t;
325
- }
326
- }
327
-
328
- const sharpInstance = sharp(data, {
329
- raw: {
330
- width: validatedImage.width,
331
- height: validatedImage.height,
332
- channels: channels
333
- }
334
- });
335
-
336
- // Apply colorspace conversion if needed
337
- if (colorSpace === 'GRAY') {
338
- sharpInstance.toColourspace('b-w');
339
- }
340
-
341
- // Encode based on selected format
342
- switch (format) {
343
- case 'jpg':
344
- outputBuffer = await sharpInstance.jpeg({ quality }).toBuffer();
345
- break;
346
- case 'png':
347
- const pngOptions = config.pngOptimize ?
348
- { compressionLevel: 9, palette: true } :
349
- { compressionLevel: 6 };
350
- outputBuffer = await sharpInstance.png(pngOptions).toBuffer();
351
- break;
352
- case 'webp':
353
- {
354
- const webpOptions = { quality };
355
- if (webpLossless) webpOptions.lossless = true;
356
- if (!webpLossless && webpSmartSubsample) webpOptions.smartSubsample = true;
357
- if (hasWebpEffort) webpOptions.effort = webpEffort;
358
- outputBuffer = await sharpInstance.webp(webpOptions).toBuffer();
359
- }
360
- break;
361
- default:
362
- throw new Error(`Unsupported format: ${format}`);
363
- }
364
- }
365
-
498
+ // Encode image (format may have been overridden by filename extension)
499
+ const outputBuffer = await encodeImage(image, { ...encodeOpts, format });
500
+
366
501
  // Write file to disk
367
502
  await fs.writeFile(filePath, outputBuffer);
503
+ dirCache.get(folderPath)?.set(filename, Date.now());
368
504
 
369
505
  if (maxImages > 0) {
370
506
  try {
371
- await enforceMaxImages(folderPath, maxImages);
507
+ await enforceMaxImages(folderPath, maxImages, dirCache.get(folderPath));
372
508
  } catch (policyErr) {
373
509
  node.warn(`Max images enforcement failed: ${policyErr.message}`);
374
510
  }
@@ -380,39 +516,27 @@ module.exports = function(RED) {
380
516
  if (config.debugEnabled) {
381
517
  try {
382
518
  const debugResult = await NodeUtils.debugImageDisplay(
383
- outputBuffer,
384
- format,
385
- quality,
386
- node,
387
- true,
388
- config.debugWidth || 200
519
+ outputBuffer, format, quality, node, true, config.debugWidth || 200
389
520
  );
390
-
391
521
  if (debugResult) {
392
- const statusText = renameOccurred ?
393
- `saved: ${filename} (avoided overwrite)` :
394
- `saved: ${filename}`;
395
-
396
- node.status({
397
- fill: "green",
398
- shape: "dot",
399
- text: statusText + ` | ${format} debug`
400
- });
522
+ const statusText = renameOccurred
523
+ ? `saved: ${filename} (avoided overwrite)`
524
+ : `saved: ${filename}`;
525
+ node.status({ fill: "green", shape: "dot", text: statusText + ` | ${format} debug` });
401
526
  }
402
527
  } catch (debugError) {
403
528
  node.warn(`Debug display error: ${debugError.message}`);
404
529
  }
405
530
  } else {
406
531
  const elapsedMs = Date.now() - startTime;
407
- const statusText = renameOccurred ?
408
- `saved: ${filename} (${elapsedMs}ms, avoided overwrite)` :
409
- `saved: ${filename} (${elapsedMs}ms)`;
410
-
532
+ const statusText = renameOccurred
533
+ ? `saved: ${filename} (${elapsedMs}ms, avoided overwrite)`
534
+ : `saved: ${filename} (${elapsedMs}ms)`;
411
535
  node.status({ fill: "green", shape: "dot", text: statusText });
412
536
  }
413
-
537
+
414
538
  if (done) done();
415
-
539
+
416
540
  } catch (err) {
417
541
  node.status({ fill: "red", shape: "ring", text: "Error" });
418
542
  const { message, hint } = NodeUtils.explainError(err, 'image-out', {
@@ -422,22 +546,10 @@ module.exports = function(RED) {
422
546
  outputFormat: config.outputFormat || 'jpg'
423
547
  });
424
548
  node.error(`Error saving image: ${message}`, msg);
425
- if (hint) {
426
- node.warn(`Hint: ${hint}`);
427
- }
549
+ if (hint) node.warn(`Hint: ${hint}`);
428
550
  if (done) done(err);
429
551
  }
430
552
  });
431
-
432
- // Helper function to check if file exists
433
- async function fileExists(filePath) {
434
- try {
435
- await fs.access(filePath);
436
- return true;
437
- } catch {
438
- return false;
439
- }
440
- }
441
553
 
442
554
  async function getDiskUsageInfo(targetPath) {
443
555
  try {
@@ -471,57 +583,128 @@ module.exports = function(RED) {
471
583
  }
472
584
  }
473
585
 
474
- async function enforceMaxImages(folderPath, maxCount) {
475
- if (maxCount <= 0) {
586
+ async function enforceMaxImages(folderPath, maxCount, cachedMap) {
587
+ if (maxCount <= 0) return;
588
+
589
+ const entries = await fs.readdir(folderPath, { withFileTypes: true });
590
+ const diskFiles = new Set();
591
+ for (const e of entries) {
592
+ if (e.isFile()) diskFiles.add(e.name);
593
+ }
594
+ if (diskFiles.size <= maxCount) {
595
+ if (cachedMap) {
596
+ for (const name of cachedMap.keys()) {
597
+ if (!diskFiles.has(name)) cachedMap.delete(name);
598
+ }
599
+ }
476
600
  return;
477
601
  }
478
602
 
479
- try {
480
- const entries = await fs.readdir(folderPath, { withFileTypes: true });
481
- const files = entries
482
- .filter((entry) => entry.isFile())
483
- .map((entry) => entry.name);
484
-
485
- if (files.length <= maxCount) {
486
- return;
603
+ if (cachedMap) {
604
+ for (const name of cachedMap.keys()) {
605
+ if (!diskFiles.has(name)) cachedMap.delete(name);
606
+ }
607
+ const unknown = [];
608
+ for (const name of diskFiles) {
609
+ if (!cachedMap.has(name)) unknown.push(name);
487
610
  }
611
+ if (unknown.length > 0) {
612
+ const stats = await Promise.all(
613
+ unknown.map(async (name) => {
614
+ const st = await fs.stat(path.join(folderPath, name));
615
+ return { name, mtimeMs: st.mtimeMs };
616
+ })
617
+ );
618
+ for (const { name, mtimeMs } of stats) cachedMap.set(name, mtimeMs);
619
+ }
620
+ }
488
621
 
489
- const fileStats = [];
490
- for (const name of files) {
491
- try {
492
- const fullPath = path.join(folderPath, name);
493
- const stats = await fs.stat(fullPath);
494
- fileStats.push({
495
- name,
496
- path: fullPath,
497
- mtime: stats.mtimeMs,
498
- });
499
- } catch (err) {
500
- node.warn(`Unable to inspect file ${name}: ${err.message}`);
501
- }
622
+ let sorted;
623
+ if (cachedMap && cachedMap.size > 0) {
624
+ sorted = Array.from(cachedMap.entries()).map(([name, mtimeMs]) => ({ name, mtimeMs }));
625
+ } else {
626
+ sorted = await Promise.all(
627
+ Array.from(diskFiles).map(async (name) => {
628
+ const st = await fs.stat(path.join(folderPath, name));
629
+ return { name, mtimeMs: st.mtimeMs };
630
+ })
631
+ );
632
+ }
633
+ sorted.sort((a, b) => a.mtimeMs - b.mtimeMs);
634
+
635
+ const toRemove = sorted.length - maxCount;
636
+ for (let i = 0; i < toRemove; i++) {
637
+ try {
638
+ await fs.unlink(path.join(folderPath, sorted[i].name));
639
+ } catch (err) {
640
+ if (err.code !== 'ENOENT') throw err;
502
641
  }
642
+ cachedMap?.delete(sorted[i].name);
643
+ }
644
+ }
503
645
 
504
- fileStats.sort((a, b) => a.mtime - b.mtime);
646
+ function encodeBmpRaw(pixelData, width, height, channels) {
647
+ const bitsPerPixel = channels * 8;
648
+ const rowBytes = width * channels;
649
+ const rowPadding = (4 - (rowBytes % 4)) % 4;
650
+ const paddedRowSize = rowBytes + rowPadding;
651
+
652
+ const hasPalette = channels === 1;
653
+ const paletteSize = hasPalette ? 256 * 4 : 0;
654
+ const headerSize = 14;
655
+ const infoHeaderSize = 40;
656
+ const pixelDataOffset = headerSize + infoHeaderSize + paletteSize;
657
+ const pixelDataSize = paddedRowSize * height;
658
+ const fileSize = pixelDataOffset + pixelDataSize;
659
+
660
+ const buf = Buffer.alloc(fileSize);
661
+
662
+ // File header
663
+ buf.write('BM', 0);
664
+ buf.writeUInt32LE(fileSize, 2);
665
+ buf.writeUInt32LE(0, 6); // reserved
666
+ buf.writeUInt32LE(pixelDataOffset, 10);
667
+
668
+ // Info header (BITMAPINFOHEADER)
669
+ buf.writeUInt32LE(infoHeaderSize, 14);
670
+ buf.writeInt32LE(width, 18);
671
+ buf.writeInt32LE(height, 22); // positive = bottom-up
672
+ buf.writeUInt16LE(1, 26); // planes
673
+ buf.writeUInt16LE(bitsPerPixel, 28);
674
+ buf.writeUInt32LE(0, 30); // compression (BI_RGB)
675
+ buf.writeUInt32LE(pixelDataSize, 34);
676
+ buf.writeInt32LE(2835, 38); // X pixels per meter (~72 DPI)
677
+ buf.writeInt32LE(2835, 42); // Y pixels per meter
678
+ buf.writeUInt32LE(hasPalette ? 256 : 0, 46);
679
+ buf.writeUInt32LE(0, 50); // important colors
680
+
681
+ // Grayscale palette
682
+ if (hasPalette) {
683
+ let offset = headerSize + infoHeaderSize;
684
+ for (let i = 0; i < 256; i++) {
685
+ buf[offset++] = i; // B
686
+ buf[offset++] = i; // G
687
+ buf[offset++] = i; // R
688
+ buf[offset++] = 0; // reserved
689
+ }
690
+ }
505
691
 
506
- while (fileStats.length > maxCount) {
507
- const oldest = fileStats.shift();
508
- if (!oldest) {
509
- break;
510
- }
511
- try {
512
- await fs.unlink(oldest.path);
513
- } catch (err) {
514
- throw new Error(`Failed to remove ${oldest.name}: ${err.message}`);
515
- }
692
+ // Pixel data (bottom-up row order)
693
+ const padBytes = Buffer.alloc(rowPadding);
694
+ for (let y = height - 1; y >= 0; y--) {
695
+ const srcOffset = y * rowBytes;
696
+ const dstOffset = pixelDataOffset + (height - 1 - y) * paddedRowSize;
697
+ pixelData.copy(buf, dstOffset, srcOffset, srcOffset + rowBytes);
698
+ if (rowPadding > 0) {
699
+ padBytes.copy(buf, dstOffset + rowBytes);
516
700
  }
517
- } catch (err) {
518
- throw new Error(`Unable to read folder "${folderPath}": ${err.message}`);
519
701
  }
702
+
703
+ return buf;
520
704
  }
521
705
 
522
706
  // Handle cleanup
523
707
  node.on('close', function() {
524
- // Clear any debug images
525
708
  try {
526
709
  RED.comms.publish("debug-image", {
527
710
  id: node.id,
@@ -532,7 +715,7 @@ module.exports = function(RED) {
532
715
  }
533
716
  });
534
717
  }
535
-
718
+
536
719
  // Register HTTP endpoint for button state changes
537
720
  RED.httpAdmin.post("/image-out/:id", RED.auth.needsPermission("flows.write"), function(req, res) {
538
721
  const node = RED.nodes.getNode(req.params.id);
@@ -540,29 +723,28 @@ module.exports = function(RED) {
540
723
  if (typeof node.active === "undefined") {
541
724
  node.active = true;
542
725
  }
543
-
726
+
544
727
  let desiredState;
545
728
  if (req.body && Object.prototype.hasOwnProperty.call(req.body, 'active')) {
546
729
  desiredState = !!req.body.active;
547
730
  } else {
548
- desiredState = !node.active; // Legacy behaviour
731
+ desiredState = !node.active;
549
732
  }
550
733
 
551
734
  node.active = desiredState;
552
-
553
- // Update node status
735
+
554
736
  if (!node.active) {
555
737
  node.status({ fill: "grey", shape: "dot", text: "inactive" });
556
738
  } else {
557
739
  node.status({});
558
740
  }
559
-
741
+
560
742
  res.json({ active: node.active });
561
743
  } else {
562
744
  res.sendStatus(404);
563
745
  }
564
746
  });
565
-
747
+
566
748
  RED.nodes.registerType("rp-image-out", ImageOutNode);
567
749
  RED.nodes.registerType("image-out", ImageOutNode); // legacy compat
568
750
  };