@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.
- package/.gitattributes +6 -0
- package/.github/workflows/build-prebuild.yml +326 -0
- package/LICENSE +13 -0
- package/README.md +161 -0
- package/artifacts/darwin-arm64/package.json +25 -0
- package/artifacts/linux-arm64/package.json +26 -0
- package/artifacts/linux-x64/package.json +26 -0
- package/artifacts/linuxmusl-x64/package.json +26 -0
- package/assets/flow_time_example.gif +0 -0
- package/assets/nodes/io/array-in-demo.gif +0 -0
- package/assets/nodes/io/array-out-demo.gif +0 -0
- package/assets/nodes/io/array-select-demo.gif +0 -0
- package/assets/nodes/io/image-in-demo.gif +0 -0
- package/assets/nodes/mix/concat-demo.gif +0 -0
- package/assets/nodes/mix/mosaic-demo.gif +0 -0
- package/assets/nodes/transform/crop-demo.gif +0 -0
- package/assets/nodes/transform/filter-demo.gif +0 -0
- package/assets/nodes/transform/padding-demo.gif +0 -0
- package/assets/nodes/transform/resize-demo.gif +0 -0
- package/assets/nodes/transform/rotate-demo.gif +0 -0
- package/docs/nodes/blend/add-mask.md +275 -0
- package/docs/nodes/blend/add-masks.md +284 -0
- package/docs/nodes/blend/blend.md +248 -0
- package/docs/nodes/io/array-in.md +119 -0
- package/docs/nodes/io/array-out.md +150 -0
- package/docs/nodes/io/array-select.md +157 -0
- package/docs/nodes/io/image-in.md +131 -0
- package/docs/nodes/io/image-out.md +179 -0
- package/docs/nodes/io/queue.md +57 -0
- package/docs/nodes/io/save-file.md +30 -0
- package/docs/nodes/mix/advanced-mosaic.md +108 -0
- package/docs/nodes/mix/concat.md +127 -0
- package/docs/nodes/mix/mosaic.md +146 -0
- package/docs/nodes/specialized/cropBB.md +271 -0
- package/docs/nodes/specialized/image-align.md +426 -0
- package/docs/nodes/transform/crop.md +132 -0
- package/docs/nodes/transform/draw.md +77 -0
- package/docs/nodes/transform/filter.md +84 -0
- package/docs/nodes/transform/padding.md +133 -0
- package/docs/nodes/transform/resize.md +158 -0
- package/docs/nodes/transform/rotate.md +121 -0
- package/docs/nodes/util/block-detect.md +46 -0
- package/install.sh +144 -0
- package/node-red-contrib-image-tools/lib/cpp-bridge.js +224 -0
- package/node-red-contrib-image-tools/lib/node-utils.js +529 -0
- package/node-red-contrib-image-tools/nodes/blend/add-bbs.html +590 -0
- package/node-red-contrib-image-tools/nodes/blend/add-bbs.js +241 -0
- package/node-red-contrib-image-tools/nodes/blend/add-mask.html +449 -0
- package/node-red-contrib-image-tools/nodes/blend/add-mask.js +170 -0
- package/node-red-contrib-image-tools/nodes/blend/add-masks.html +703 -0
- package/node-red-contrib-image-tools/nodes/blend/add-masks.js +321 -0
- package/node-red-contrib-image-tools/nodes/blend/blend.html +552 -0
- package/node-red-contrib-image-tools/nodes/blend/blend.js +124 -0
- package/node-red-contrib-image-tools/nodes/io/array-in.html +110 -0
- package/node-red-contrib-image-tools/nodes/io/array-in.js +113 -0
- package/node-red-contrib-image-tools/nodes/io/array-out.html +125 -0
- package/node-red-contrib-image-tools/nodes/io/array-out.js +213 -0
- package/node-red-contrib-image-tools/nodes/io/array-select.html +156 -0
- package/node-red-contrib-image-tools/nodes/io/array-select.js +187 -0
- package/node-red-contrib-image-tools/nodes/io/folder-in.html +248 -0
- package/node-red-contrib-image-tools/nodes/io/folder-in.js +335 -0
- package/node-red-contrib-image-tools/nodes/io/image-in.html +146 -0
- package/node-red-contrib-image-tools/nodes/io/image-in.js +143 -0
- package/node-red-contrib-image-tools/nodes/io/image-out.html +506 -0
- package/node-red-contrib-image-tools/nodes/io/image-out.js +545 -0
- package/node-red-contrib-image-tools/nodes/io/queue.html +119 -0
- package/node-red-contrib-image-tools/nodes/io/queue.js +191 -0
- package/node-red-contrib-image-tools/nodes/io/save-file.html +243 -0
- package/node-red-contrib-image-tools/nodes/io/save-file.js +440 -0
- package/node-red-contrib-image-tools/nodes/mix/advanced-mosaic.html +2149 -0
- package/node-red-contrib-image-tools/nodes/mix/advanced-mosaic.js +195 -0
- package/node-red-contrib-image-tools/nodes/mix/concat.html +390 -0
- package/node-red-contrib-image-tools/nodes/mix/concat.js +112 -0
- package/node-red-contrib-image-tools/nodes/mix/mosaic.html +550 -0
- package/node-red-contrib-image-tools/nodes/mix/mosaic.js +151 -0
- package/node-red-contrib-image-tools/nodes/specialized/cropBB.html +268 -0
- package/node-red-contrib-image-tools/nodes/specialized/cropBB.js +277 -0
- package/node-red-contrib-image-tools/nodes/specialized/image-align.html +528 -0
- package/node-red-contrib-image-tools/nodes/specialized/image-align.js +306 -0
- package/node-red-contrib-image-tools/nodes/transform/crop.html +410 -0
- package/node-red-contrib-image-tools/nodes/transform/crop.js +149 -0
- package/node-red-contrib-image-tools/nodes/transform/draw.html +719 -0
- package/node-red-contrib-image-tools/nodes/transform/draw.js +509 -0
- package/node-red-contrib-image-tools/nodes/transform/filter.html +578 -0
- package/node-red-contrib-image-tools/nodes/transform/filter.js +177 -0
- package/node-red-contrib-image-tools/nodes/transform/padding.html +475 -0
- package/node-red-contrib-image-tools/nodes/transform/padding.js +142 -0
- package/node-red-contrib-image-tools/nodes/transform/resize.html +429 -0
- package/node-red-contrib-image-tools/nodes/transform/resize.js +162 -0
- package/node-red-contrib-image-tools/nodes/transform/rotate.html +299 -0
- package/node-red-contrib-image-tools/nodes/transform/rotate.js +141 -0
- package/node-red-contrib-image-tools/nodes/util/block-detect.html +85 -0
- package/node-red-contrib-image-tools/nodes/util/block-detect.js +136 -0
- package/node-red-contrib-image-tools/nodes/util/clean-debug.html +201 -0
- package/node-red-contrib-image-tools/nodes/util/clean-debug.js +393 -0
- package/node-red-contrib-image-tools/package.json +64 -0
- package/npm/darwin-arm64/lib/.gitkeep +1 -0
- package/npm/darwin-arm64/package.json +25 -0
- package/npm/darwin-x64/lib/.gitkeep +1 -0
- package/npm/darwin-x64/package.json +25 -0
- package/npm/linux-arm64/lib/.gitkeep +1 -0
- package/npm/linux-arm64/package.json +26 -0
- package/npm/linux-x64/lib/.gitkeep +1 -0
- package/npm/linux-x64/package.json +26 -0
- package/npm/linuxmusl-x64/lib/.gitkeep +1 -0
- package/npm/linuxmusl-x64/package.json +26 -0
- package/npm/win32-x64/lib/.gitkeep +1 -0
- package/npm/win32-x64/package.json +25 -0
- package/package.json +74 -0
- package/rosepetal-image-engine/binding.gyp +153 -0
- package/rosepetal-image-engine/package.json +19 -0
- package/rosepetal-image-engine/src/add-bbs.cpp +433 -0
- package/rosepetal-image-engine/src/add-mask.cpp +240 -0
- package/rosepetal-image-engine/src/add-masks.cpp +638 -0
- package/rosepetal-image-engine/src/advanced-mosaic.cpp +740 -0
- package/rosepetal-image-engine/src/blend.cpp +200 -0
- package/rosepetal-image-engine/src/concat.cpp +329 -0
- package/rosepetal-image-engine/src/crop.cpp +139 -0
- package/rosepetal-image-engine/src/draw.cpp +414 -0
- package/rosepetal-image-engine/src/filter.cpp +230 -0
- package/rosepetal-image-engine/src/filters/kernels.h +171 -0
- package/rosepetal-image-engine/src/image-align.cpp +551 -0
- package/rosepetal-image-engine/src/main.cpp +36 -0
- package/rosepetal-image-engine/src/mosaic.cpp +373 -0
- package/rosepetal-image-engine/src/padding.cpp +124 -0
- package/rosepetal-image-engine/src/resize.cpp +210 -0
- package/rosepetal-image-engine/src/rotate.cpp +177 -0
- package/rosepetal-image-engine/src/utils.h +563 -0
- package/rosepetal-image-engine/test-formats.js +119 -0
- package/scripts/build-opencv-static.ps1 +166 -0
- package/scripts/build-opencv-static.sh +147 -0
|
@@ -0,0 +1,545 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file Node.js logic for the Image-Out node with timestamp-based naming.
|
|
3
|
+
* Saves images to filesystem with automatic timestamp naming and overwrite protection.
|
|
4
|
+
* @author Rosepetal
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
const sharp = require('sharp');
|
|
8
|
+
const fs = require('fs').promises;
|
|
9
|
+
const path = require('path');
|
|
10
|
+
|
|
11
|
+
module.exports = function(RED) {
|
|
12
|
+
const NodeUtils = require('../../lib/node-utils.js')(RED);
|
|
13
|
+
|
|
14
|
+
function ImageOutNode(config) {
|
|
15
|
+
RED.nodes.createNode(this, config);
|
|
16
|
+
const node = this;
|
|
17
|
+
|
|
18
|
+
// Initialize node state
|
|
19
|
+
node.active = config.active !== false; // Default to true if not set
|
|
20
|
+
let diskCheckErrorLogged = false;
|
|
21
|
+
|
|
22
|
+
// Update node appearance based on active state
|
|
23
|
+
updateNodeStatus();
|
|
24
|
+
|
|
25
|
+
function updateNodeStatus() {
|
|
26
|
+
if (!node.active) {
|
|
27
|
+
node.status({ fill: "grey", shape: "dot", text: "inactive" });
|
|
28
|
+
} else {
|
|
29
|
+
node.status({}); // Clear status when active and idle
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
node.on('input', async function(msg, send, done) {
|
|
34
|
+
// Skip processing if node is inactive
|
|
35
|
+
if (!node.active) {
|
|
36
|
+
if (done) done();
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const startTime = Date.now();
|
|
41
|
+
|
|
42
|
+
try {
|
|
43
|
+
const evaluateProperty = (value, type, fallbackType = 'str') => {
|
|
44
|
+
return new Promise((resolve, reject) => {
|
|
45
|
+
const actualType = type || fallbackType;
|
|
46
|
+
try {
|
|
47
|
+
RED.util.evaluateNodeProperty(value, actualType, node, msg, (err, result) => {
|
|
48
|
+
if (err) {
|
|
49
|
+
reject(err);
|
|
50
|
+
} else {
|
|
51
|
+
resolve(result);
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
} catch (err) {
|
|
55
|
+
reject(err);
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
// Resolve folder path (supports typed inputs)
|
|
61
|
+
const folderPathType = config.folderPathType || 'str';
|
|
62
|
+
let folderPath;
|
|
63
|
+
if (['msg', 'flow', 'global', 'jsonata', 'env'].includes(folderPathType)) {
|
|
64
|
+
folderPath = await evaluateProperty(config.folderPath, folderPathType);
|
|
65
|
+
} else {
|
|
66
|
+
folderPath = config.folderPath || '.';
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
if (folderPath === undefined || folderPath === null || String(folderPath).trim() === '') {
|
|
70
|
+
throw new Error('Folder path is not configured or resolved.');
|
|
71
|
+
}
|
|
72
|
+
folderPath = String(folderPath);
|
|
73
|
+
|
|
74
|
+
try {
|
|
75
|
+
await fs.mkdir(folderPath, { recursive: true });
|
|
76
|
+
} catch (mkdirErr) {
|
|
77
|
+
throw new Error(`Cannot create directory: ${mkdirErr.message}`);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Resolve optional maximum image count
|
|
81
|
+
let maxImages = 0;
|
|
82
|
+
const maxImagesType = config.maxImagesType || 'num';
|
|
83
|
+
const maxImagesConfigured = !(
|
|
84
|
+
config.maxImages === undefined ||
|
|
85
|
+
config.maxImages === null ||
|
|
86
|
+
(typeof config.maxImages === 'string' && config.maxImages.trim() === '')
|
|
87
|
+
);
|
|
88
|
+
|
|
89
|
+
if (maxImagesConfigured || ['msg', 'flow', 'global', 'jsonata', 'env'].includes(maxImagesType)) {
|
|
90
|
+
try {
|
|
91
|
+
const resolvedMax = await evaluateProperty(config.maxImages, maxImagesType);
|
|
92
|
+
if (resolvedMax !== undefined && resolvedMax !== null && resolvedMax !== '') {
|
|
93
|
+
const numericMax = parseInt(resolvedMax, 10);
|
|
94
|
+
if (Number.isNaN(numericMax)) {
|
|
95
|
+
throw new Error(`Value "${resolvedMax}" is not a valid integer.`);
|
|
96
|
+
}
|
|
97
|
+
if (numericMax < 0) {
|
|
98
|
+
throw new Error('Value must be zero or a positive integer.');
|
|
99
|
+
}
|
|
100
|
+
maxImages = numericMax;
|
|
101
|
+
}
|
|
102
|
+
} catch (err) {
|
|
103
|
+
throw new Error(`Unable to resolve max images: ${err.message}`);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// Retrieve input image
|
|
108
|
+
const inputPath = config.inputPath || 'payload';
|
|
109
|
+
const inputPathType = config.inputPathType || 'msg';
|
|
110
|
+
|
|
111
|
+
let image;
|
|
112
|
+
if (inputPathType === 'msg') {
|
|
113
|
+
image = RED.util.getMessageProperty(msg, inputPath);
|
|
114
|
+
} else if (inputPathType === 'flow') {
|
|
115
|
+
image = node.context().flow.get(inputPath);
|
|
116
|
+
} else if (inputPathType === 'global') {
|
|
117
|
+
image = node.context().global.get(inputPath);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
if (!image) {
|
|
121
|
+
throw new Error('No image data found at specified input path');
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
node.status({ fill: 'blue', shape: 'dot', text: 'saving...' });
|
|
125
|
+
|
|
126
|
+
// Resolve optional full filename override
|
|
127
|
+
let resolvedFullFilename = null;
|
|
128
|
+
const fullNameType = config.filenameFullType || 'str';
|
|
129
|
+
const hasFullNameConfig = !(
|
|
130
|
+
config.filenameFull === undefined ||
|
|
131
|
+
config.filenameFull === null ||
|
|
132
|
+
(typeof config.filenameFull === 'string' && config.filenameFull.trim() === '')
|
|
133
|
+
);
|
|
134
|
+
|
|
135
|
+
if (hasFullNameConfig || ['msg', 'flow', 'global', 'jsonata', 'env'].includes(fullNameType)) {
|
|
136
|
+
try {
|
|
137
|
+
const evaluated = await evaluateProperty(config.filenameFull, fullNameType);
|
|
138
|
+
if (evaluated !== undefined && evaluated !== null) {
|
|
139
|
+
const trimmed = String(evaluated).trim();
|
|
140
|
+
if (trimmed) {
|
|
141
|
+
resolvedFullFilename = trimmed;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
} catch (err) {
|
|
145
|
+
throw new Error(`Unable to resolve full filename: ${err.message}`);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// Resolve prefix when full filename not provided
|
|
150
|
+
const prefixType = config.filenamePrefixType || 'str';
|
|
151
|
+
let prefixValue = config.filenamePrefix || '';
|
|
152
|
+
if (['msg', 'flow', 'global', 'jsonata', 'env'].includes(prefixType)) {
|
|
153
|
+
try {
|
|
154
|
+
const evaluatedPrefix = await evaluateProperty(config.filenamePrefix, prefixType);
|
|
155
|
+
prefixValue = evaluatedPrefix !== undefined && evaluatedPrefix !== null ? String(evaluatedPrefix) : '';
|
|
156
|
+
} catch (err) {
|
|
157
|
+
throw new Error(`Unable to resolve filename prefix: ${err.message}`);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
prefixValue = (prefixValue || '').trim();
|
|
161
|
+
const prefix = prefixValue ? `${prefixValue}_` : 'image_';
|
|
162
|
+
|
|
163
|
+
// Determine format & extension
|
|
164
|
+
let format = (config.outputFormat || 'jpg').toLowerCase();
|
|
165
|
+
if (!['jpg', 'png', 'webp'].includes(format)) {
|
|
166
|
+
format = 'jpg';
|
|
167
|
+
}
|
|
168
|
+
let fileExtension = format === 'jpg' ? 'jpg' : format;
|
|
169
|
+
const webpLossless = config.webpLossless === true || config.webpLossless === 'true';
|
|
170
|
+
const webpSmartSubsample = config.webpSmartSubsample === true || config.webpSmartSubsample === 'true';
|
|
171
|
+
const parsedEffort = parseInt(config.webpEffort, 10);
|
|
172
|
+
const hasWebpEffort = Number.isInteger(parsedEffort);
|
|
173
|
+
// Sharp expects 0-6 (6 = slowest/smallest); clamp to be safe
|
|
174
|
+
const webpEffort = hasWebpEffort ? Math.min(6, Math.max(0, parsedEffort)) : null;
|
|
175
|
+
|
|
176
|
+
// Build filename (timestamp-based fallback)
|
|
177
|
+
const now = new Date();
|
|
178
|
+
const timestamp = now.getFullYear().toString() +
|
|
179
|
+
(now.getMonth() + 1).toString().padStart(2, '0') +
|
|
180
|
+
now.getDate().toString().padStart(2, '0') + '_' +
|
|
181
|
+
now.getHours().toString().padStart(2, '0') +
|
|
182
|
+
now.getMinutes().toString().padStart(2, '0') +
|
|
183
|
+
now.getSeconds().toString().padStart(2, '0');
|
|
184
|
+
|
|
185
|
+
let baseFilename;
|
|
186
|
+
if (resolvedFullFilename) {
|
|
187
|
+
if (/[\\/]/.test(resolvedFullFilename)) {
|
|
188
|
+
throw new Error('Full filename must not include path separators');
|
|
189
|
+
}
|
|
190
|
+
const parsed = path.parse(resolvedFullFilename);
|
|
191
|
+
if (parsed.ext) {
|
|
192
|
+
const extLower = parsed.ext.slice(1).toLowerCase();
|
|
193
|
+
if (!['jpg', 'jpeg', 'png', 'webp'].includes(extLower)) {
|
|
194
|
+
throw new Error(`Unsupported extension in filename: ${parsed.ext}`);
|
|
195
|
+
}
|
|
196
|
+
fileExtension = parsed.ext.slice(1);
|
|
197
|
+
format = extLower === 'jpeg' ? 'jpg' : extLower;
|
|
198
|
+
baseFilename = parsed.name;
|
|
199
|
+
} else {
|
|
200
|
+
baseFilename = parsed.base;
|
|
201
|
+
}
|
|
202
|
+
} else {
|
|
203
|
+
baseFilename = `${prefix}${timestamp}`;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
if (!baseFilename || !String(baseFilename).trim()) {
|
|
207
|
+
throw new Error('Filename could not be determined.');
|
|
208
|
+
}
|
|
209
|
+
baseFilename = String(baseFilename).trim();
|
|
210
|
+
|
|
211
|
+
let filename = `${baseFilename}.${fileExtension}`;
|
|
212
|
+
const originalFilename = filename;
|
|
213
|
+
let filePath = path.join(folderPath, filename);
|
|
214
|
+
|
|
215
|
+
if (config.overwriteProtection !== false) {
|
|
216
|
+
let counter = 2;
|
|
217
|
+
while (await fileExists(filePath)) {
|
|
218
|
+
filename = `${baseFilename}_${counter}.${fileExtension}`;
|
|
219
|
+
filePath = path.join(folderPath, filename);
|
|
220
|
+
counter += 1;
|
|
221
|
+
if (counter > 1000) {
|
|
222
|
+
throw new Error('Too many file variations exist');
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const diskInfo = await getDiskUsageInfo(folderPath);
|
|
228
|
+
if (diskInfo && diskInfo.usedRatio >= 0.9) {
|
|
229
|
+
const usedPercent = (diskInfo.usedRatio * 100).toFixed(1);
|
|
230
|
+
node.warn(`Storage at "${folderPath}" is ${usedPercent}% full. Skipping image save to avoid exhausting disk space.`);
|
|
231
|
+
node.status({ fill: "yellow", shape: "ring", text: `disk ${usedPercent}% full` });
|
|
232
|
+
if (done) done();
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// Convert image to buffer based on format
|
|
237
|
+
let outputBuffer;
|
|
238
|
+
const quality = parseInt(config.outputQuality, 10) || 90;
|
|
239
|
+
|
|
240
|
+
// Check if image is already an encoded Buffer (JPEG, PNG, WebP)
|
|
241
|
+
if (Buffer.isBuffer(image) && !image.width && !image.height) {
|
|
242
|
+
// It's an encoded image buffer
|
|
243
|
+
// We can either save it directly or re-encode if format is different
|
|
244
|
+
|
|
245
|
+
// Try to detect the input format using Sharp metadata
|
|
246
|
+
let inputFormat;
|
|
247
|
+
try {
|
|
248
|
+
const metadata = await sharp(image).metadata();
|
|
249
|
+
inputFormat = metadata.format; // Will be 'jpeg', 'png', 'webp', etc.
|
|
250
|
+
} catch (err) {
|
|
251
|
+
// If we can't detect format, we'll re-encode anyway
|
|
252
|
+
inputFormat = null;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// Check if we need to re-encode or can save directly
|
|
256
|
+
const sameFormat =
|
|
257
|
+
inputFormat === format ||
|
|
258
|
+
(inputFormat === 'jpeg' && format === 'jpg');
|
|
259
|
+
|
|
260
|
+
const needsWebpReencode =
|
|
261
|
+
format === 'webp' && (webpLossless || hasWebpEffort);
|
|
262
|
+
|
|
263
|
+
if (sameFormat && !needsWebpReencode) {
|
|
264
|
+
// Same format and no special WebP options: save directly (fastest)
|
|
265
|
+
outputBuffer = image;
|
|
266
|
+
} else {
|
|
267
|
+
// Different format or unknown input, re-encode using Sharp
|
|
268
|
+
const sharpInstance = sharp(image);
|
|
269
|
+
|
|
270
|
+
switch (format) {
|
|
271
|
+
case 'jpg':
|
|
272
|
+
outputBuffer = await sharpInstance.jpeg({ quality }).toBuffer();
|
|
273
|
+
break;
|
|
274
|
+
case 'png':
|
|
275
|
+
const pngOptions = config.pngOptimize ?
|
|
276
|
+
{ compressionLevel: 9, palette: true } :
|
|
277
|
+
{ compressionLevel: 6 };
|
|
278
|
+
outputBuffer = await sharpInstance.png(pngOptions).toBuffer();
|
|
279
|
+
break;
|
|
280
|
+
case 'webp':
|
|
281
|
+
{
|
|
282
|
+
const webpOptions = { quality };
|
|
283
|
+
if (webpLossless) webpOptions.lossless = true;
|
|
284
|
+
if (!webpLossless && webpSmartSubsample) webpOptions.smartSubsample = true;
|
|
285
|
+
if (hasWebpEffort) webpOptions.effort = webpEffort;
|
|
286
|
+
outputBuffer = await sharpInstance.webp(webpOptions).toBuffer();
|
|
287
|
+
}
|
|
288
|
+
break;
|
|
289
|
+
default:
|
|
290
|
+
throw new Error(`Unsupported format: ${format}`);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
} else {
|
|
294
|
+
// It's raw image data - validate and process as before
|
|
295
|
+
const validatedImage = NodeUtils.validateImageStructure(image, node);
|
|
296
|
+
if (!validatedImage) {
|
|
297
|
+
throw new Error("Invalid image structure");
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// Convert from raw image format to Sharp-compatible format
|
|
301
|
+
const colorSpace = validatedImage.colorSpace;
|
|
302
|
+
const channels = validatedImage.channels;
|
|
303
|
+
let data = validatedImage.data;
|
|
304
|
+
|
|
305
|
+
// BGR/BGRA → RGB/RGBA for Sharp
|
|
306
|
+
if (colorSpace === 'BGR' || colorSpace === 'BGRA') {
|
|
307
|
+
data = Buffer.from(data); // Copy to avoid mutating shared memory
|
|
308
|
+
for (let i = 0; i < data.length; i += channels) {
|
|
309
|
+
const t = data[i];
|
|
310
|
+
data[i] = data[i + 2];
|
|
311
|
+
data[i + 2] = t;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
const sharpInstance = sharp(data, {
|
|
316
|
+
raw: {
|
|
317
|
+
width: validatedImage.width,
|
|
318
|
+
height: validatedImage.height,
|
|
319
|
+
channels: channels
|
|
320
|
+
}
|
|
321
|
+
});
|
|
322
|
+
|
|
323
|
+
// Apply colorspace conversion if needed
|
|
324
|
+
if (colorSpace === 'GRAY') {
|
|
325
|
+
sharpInstance.toColourspace('b-w');
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// Encode based on selected format
|
|
329
|
+
switch (format) {
|
|
330
|
+
case 'jpg':
|
|
331
|
+
outputBuffer = await sharpInstance.jpeg({ quality }).toBuffer();
|
|
332
|
+
break;
|
|
333
|
+
case 'png':
|
|
334
|
+
const pngOptions = config.pngOptimize ?
|
|
335
|
+
{ compressionLevel: 9, palette: true } :
|
|
336
|
+
{ compressionLevel: 6 };
|
|
337
|
+
outputBuffer = await sharpInstance.png(pngOptions).toBuffer();
|
|
338
|
+
break;
|
|
339
|
+
case 'webp':
|
|
340
|
+
{
|
|
341
|
+
const webpOptions = { quality };
|
|
342
|
+
if (webpLossless) webpOptions.lossless = true;
|
|
343
|
+
if (!webpLossless && webpSmartSubsample) webpOptions.smartSubsample = true;
|
|
344
|
+
if (hasWebpEffort) webpOptions.effort = webpEffort;
|
|
345
|
+
outputBuffer = await sharpInstance.webp(webpOptions).toBuffer();
|
|
346
|
+
}
|
|
347
|
+
break;
|
|
348
|
+
default:
|
|
349
|
+
throw new Error(`Unsupported format: ${format}`);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// Write file to disk
|
|
354
|
+
await fs.writeFile(filePath, outputBuffer);
|
|
355
|
+
|
|
356
|
+
if (maxImages > 0) {
|
|
357
|
+
try {
|
|
358
|
+
await enforceMaxImages(folderPath, maxImages);
|
|
359
|
+
} catch (policyErr) {
|
|
360
|
+
node.warn(`Max images enforcement failed: ${policyErr.message}`);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
const renameOccurred = config.overwriteProtection !== false && filename !== originalFilename;
|
|
365
|
+
|
|
366
|
+
// Debug display if enabled
|
|
367
|
+
if (config.debugEnabled) {
|
|
368
|
+
try {
|
|
369
|
+
const debugResult = await NodeUtils.debugImageDisplay(
|
|
370
|
+
outputBuffer,
|
|
371
|
+
format,
|
|
372
|
+
quality,
|
|
373
|
+
node,
|
|
374
|
+
true,
|
|
375
|
+
config.debugWidth || 200
|
|
376
|
+
);
|
|
377
|
+
|
|
378
|
+
if (debugResult) {
|
|
379
|
+
const statusText = renameOccurred ?
|
|
380
|
+
`saved: ${filename} (avoided overwrite)` :
|
|
381
|
+
`saved: ${filename}`;
|
|
382
|
+
|
|
383
|
+
node.status({
|
|
384
|
+
fill: "green",
|
|
385
|
+
shape: "dot",
|
|
386
|
+
text: statusText + ` | ${format} debug`
|
|
387
|
+
});
|
|
388
|
+
}
|
|
389
|
+
} catch (debugError) {
|
|
390
|
+
node.warn(`Debug display error: ${debugError.message}`);
|
|
391
|
+
}
|
|
392
|
+
} else {
|
|
393
|
+
const elapsedMs = Date.now() - startTime;
|
|
394
|
+
const statusText = renameOccurred ?
|
|
395
|
+
`saved: ${filename} (${elapsedMs}ms, avoided overwrite)` :
|
|
396
|
+
`saved: ${filename} (${elapsedMs}ms)`;
|
|
397
|
+
|
|
398
|
+
node.status({ fill: "green", shape: "dot", text: statusText });
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
if (done) done();
|
|
402
|
+
|
|
403
|
+
} catch (err) {
|
|
404
|
+
node.status({ fill: "red", shape: "ring", text: "Error" });
|
|
405
|
+
node.error(`Error saving image: ${err.message}`, msg);
|
|
406
|
+
if (done) done(err);
|
|
407
|
+
}
|
|
408
|
+
});
|
|
409
|
+
|
|
410
|
+
// Helper function to check if file exists
|
|
411
|
+
async function fileExists(filePath) {
|
|
412
|
+
try {
|
|
413
|
+
await fs.access(filePath);
|
|
414
|
+
return true;
|
|
415
|
+
} catch {
|
|
416
|
+
return false;
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
async function getDiskUsageInfo(targetPath) {
|
|
421
|
+
try {
|
|
422
|
+
const stats = await fs.statfs(targetPath);
|
|
423
|
+
const blockSize = Number(stats.bsize) || 0;
|
|
424
|
+
const totalBlocks = Number(stats.blocks) || 0;
|
|
425
|
+
const availableBlocks = Number(
|
|
426
|
+
stats.bavail !== undefined ? stats.bavail :
|
|
427
|
+
stats.bfree !== undefined ? stats.bfree : 0
|
|
428
|
+
);
|
|
429
|
+
|
|
430
|
+
const totalBytes = totalBlocks * blockSize;
|
|
431
|
+
const availableBytes = availableBlocks * blockSize;
|
|
432
|
+
|
|
433
|
+
if (totalBytes <= 0) {
|
|
434
|
+
return null;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
const usedRatio = 1 - (availableBytes / totalBytes);
|
|
438
|
+
return {
|
|
439
|
+
totalBytes,
|
|
440
|
+
availableBytes,
|
|
441
|
+
usedRatio
|
|
442
|
+
};
|
|
443
|
+
} catch (err) {
|
|
444
|
+
if (!diskCheckErrorLogged) {
|
|
445
|
+
node.warn(`Disk usage check failed for "${targetPath}": ${err.message}`);
|
|
446
|
+
diskCheckErrorLogged = true;
|
|
447
|
+
}
|
|
448
|
+
return null;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
async function enforceMaxImages(folderPath, maxCount) {
|
|
453
|
+
if (maxCount <= 0) {
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
try {
|
|
458
|
+
const entries = await fs.readdir(folderPath, { withFileTypes: true });
|
|
459
|
+
const files = entries
|
|
460
|
+
.filter((entry) => entry.isFile())
|
|
461
|
+
.map((entry) => entry.name);
|
|
462
|
+
|
|
463
|
+
if (files.length <= maxCount) {
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
const fileStats = [];
|
|
468
|
+
for (const name of files) {
|
|
469
|
+
try {
|
|
470
|
+
const fullPath = path.join(folderPath, name);
|
|
471
|
+
const stats = await fs.stat(fullPath);
|
|
472
|
+
fileStats.push({
|
|
473
|
+
name,
|
|
474
|
+
path: fullPath,
|
|
475
|
+
mtime: stats.mtimeMs,
|
|
476
|
+
});
|
|
477
|
+
} catch (err) {
|
|
478
|
+
node.warn(`Unable to inspect file ${name}: ${err.message}`);
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
fileStats.sort((a, b) => a.mtime - b.mtime);
|
|
483
|
+
|
|
484
|
+
while (fileStats.length > maxCount) {
|
|
485
|
+
const oldest = fileStats.shift();
|
|
486
|
+
if (!oldest) {
|
|
487
|
+
break;
|
|
488
|
+
}
|
|
489
|
+
try {
|
|
490
|
+
await fs.unlink(oldest.path);
|
|
491
|
+
} catch (err) {
|
|
492
|
+
throw new Error(`Failed to remove ${oldest.name}: ${err.message}`);
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
} catch (err) {
|
|
496
|
+
throw new Error(`Unable to read folder "${folderPath}": ${err.message}`);
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
// Handle cleanup
|
|
501
|
+
node.on('close', function() {
|
|
502
|
+
// Clear any debug images
|
|
503
|
+
try {
|
|
504
|
+
RED.comms.publish("debug-image", {
|
|
505
|
+
id: node.id,
|
|
506
|
+
data: null
|
|
507
|
+
});
|
|
508
|
+
} catch (err) {
|
|
509
|
+
// Ignore cleanup errors
|
|
510
|
+
}
|
|
511
|
+
});
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
// Register HTTP endpoint for button state changes
|
|
515
|
+
RED.httpAdmin.post("/image-out/:id", RED.auth.needsPermission("flows.write"), function(req, res) {
|
|
516
|
+
const node = RED.nodes.getNode(req.params.id);
|
|
517
|
+
if (node != null) {
|
|
518
|
+
if (typeof node.active === "undefined") {
|
|
519
|
+
node.active = true;
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
let desiredState;
|
|
523
|
+
if (req.body && Object.prototype.hasOwnProperty.call(req.body, 'active')) {
|
|
524
|
+
desiredState = !!req.body.active;
|
|
525
|
+
} else {
|
|
526
|
+
desiredState = !node.active; // Legacy behaviour
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
node.active = desiredState;
|
|
530
|
+
|
|
531
|
+
// Update node status
|
|
532
|
+
if (!node.active) {
|
|
533
|
+
node.status({ fill: "grey", shape: "dot", text: "inactive" });
|
|
534
|
+
} else {
|
|
535
|
+
node.status({});
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
res.json({ active: node.active });
|
|
539
|
+
} else {
|
|
540
|
+
res.sendStatus(404);
|
|
541
|
+
}
|
|
542
|
+
});
|
|
543
|
+
|
|
544
|
+
RED.nodes.registerType("image-out", ImageOutNode);
|
|
545
|
+
};
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
<script type="text/javascript">
|
|
2
|
+
RED.nodes.registerType('queue', {
|
|
3
|
+
category: 'RP Image',
|
|
4
|
+
color: '#87CEEB',
|
|
5
|
+
defaults: {
|
|
6
|
+
name: { value: "" },
|
|
7
|
+
mode: { value: "queue-size" },
|
|
8
|
+
maxQueueSize: { value: 0 },
|
|
9
|
+
intervalMilliseconds: { value: 0 },
|
|
10
|
+
timeout: { value: 0 }
|
|
11
|
+
},
|
|
12
|
+
inputs: 1,
|
|
13
|
+
outputs: 1,
|
|
14
|
+
icon: "font-awesome/fa-clock-o",
|
|
15
|
+
label: function() {
|
|
16
|
+
if (this.name) return this.name;
|
|
17
|
+
return "Queue";
|
|
18
|
+
},
|
|
19
|
+
oneditprepare: function() {
|
|
20
|
+
const modeField = $("#node-input-mode");
|
|
21
|
+
const queueRow = $("#node-row-maxQueueSize");
|
|
22
|
+
const timeoutRow = $("#node-row-timeout");
|
|
23
|
+
const queueTip = $("#node-tip-maxQueueSize");
|
|
24
|
+
const timeoutTip = $("#node-tip-timeout");
|
|
25
|
+
|
|
26
|
+
function toggleModeFields() {
|
|
27
|
+
const mode = modeField.val();
|
|
28
|
+
if (mode === 'timeout') {
|
|
29
|
+
queueRow.hide();
|
|
30
|
+
queueTip.hide();
|
|
31
|
+
timeoutRow.show();
|
|
32
|
+
timeoutTip.show();
|
|
33
|
+
} else {
|
|
34
|
+
queueRow.show();
|
|
35
|
+
queueTip.show();
|
|
36
|
+
timeoutRow.hide();
|
|
37
|
+
timeoutTip.hide();
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
modeField.on("change", toggleModeFields);
|
|
42
|
+
toggleModeFields();
|
|
43
|
+
}
|
|
44
|
+
});
|
|
45
|
+
</script>
|
|
46
|
+
|
|
47
|
+
<script type="text/x-red" data-template-name="queue">
|
|
48
|
+
<div class="form-row">
|
|
49
|
+
<label for="node-input-name"><i class="fa fa-tag"></i> Name</label>
|
|
50
|
+
<input type="text" id="node-input-name" placeholder="Name">
|
|
51
|
+
</div>
|
|
52
|
+
|
|
53
|
+
<hr>
|
|
54
|
+
|
|
55
|
+
<div class="form-row">
|
|
56
|
+
<label for="node-input-mode"><i class="fa fa-exchange"></i> Mode</label>
|
|
57
|
+
<select id="node-input-mode">
|
|
58
|
+
<option value="queue-size">Queue Size Limit</option>
|
|
59
|
+
<option value="timeout">Timeout</option>
|
|
60
|
+
</select>
|
|
61
|
+
</div>
|
|
62
|
+
<div class="form-tips">
|
|
63
|
+
<b>Tip:</b> Pick a mode to decide whether the node caps how many messages can wait or keeps unlimited entries that expire after a timeout.
|
|
64
|
+
</div>
|
|
65
|
+
|
|
66
|
+
<div class="form-row" id="node-row-maxQueueSize">
|
|
67
|
+
<label for="node-input-maxQueueSize"><i class="fa fa-list"></i> Max Queue Size</label>
|
|
68
|
+
<input type="number" id="node-input-maxQueueSize" min="0" step="1" style="width: 70%;" placeholder="0">
|
|
69
|
+
</div>
|
|
70
|
+
<div class="form-tips" id="node-tip-maxQueueSize">
|
|
71
|
+
<b>Tip:</b> When using the queue-size mode, this field limits how many messages are buffered; extra messages are dropped until space frees up.
|
|
72
|
+
</div>
|
|
73
|
+
|
|
74
|
+
<div class="form-row" id="node-row-timeout">
|
|
75
|
+
<label for="node-input-timeout"><i class="fa fa-hourglass-half"></i> Timeout (ms)</label>
|
|
76
|
+
<input type="number" id="node-input-timeout" min="0" step="1" style="width: 70%;" placeholder="0">
|
|
77
|
+
</div>
|
|
78
|
+
<div class="form-tips" id="node-tip-timeout">
|
|
79
|
+
<b>Tip:</b> Timeout mode keeps buffering all messages but removes entries that stay longer than this value, keeping the data fresh.
|
|
80
|
+
</div>
|
|
81
|
+
|
|
82
|
+
<div class="form-row">
|
|
83
|
+
<label for="node-input-intervalMilliseconds"><i class="fa fa-clock-o"></i> Interval (ms)</label>
|
|
84
|
+
<input type="number" id="node-input-intervalMilliseconds" min="0" step="1" style="width: 70%;" placeholder="0">
|
|
85
|
+
</div>
|
|
86
|
+
<div class="form-tips">
|
|
87
|
+
<b>Tip:</b> Interval enforces a minimum delay between forwarded messages; set to 0 to send as fast as possible.
|
|
88
|
+
</div>
|
|
89
|
+
</script>
|
|
90
|
+
|
|
91
|
+
<script type="text/x-red" data-help-name="queue">
|
|
92
|
+
<p>Buffers incoming messages and releases them with optional rate limiting and expiration control.</p>
|
|
93
|
+
|
|
94
|
+
<h3>Mode</h3>
|
|
95
|
+
<p>Choose between a queue-size limit or a timeout strategy; only the controls for the selected mode are applied.</p>
|
|
96
|
+
|
|
97
|
+
<h3>Configuration</h3>
|
|
98
|
+
<dl class="message-properties">
|
|
99
|
+
<dt>Mode <span class="property-type">enum</span></dt>
|
|
100
|
+
<dd>Select <code>Queue Size Limit</code> to cap the number of buffered messages or <code>Timeout</code> to drop entries after a duration.</dd>
|
|
101
|
+
<dt>Max Queue Size <span class="property-type">number</span></dt>
|
|
102
|
+
<dd>Valid only in queue-size mode. Determines how many messages can be held before incoming data is ignored.</dd>
|
|
103
|
+
<dt>Timeout (ms) <span class="property-type">number</span></dt>
|
|
104
|
+
<dd>Valid only in timeout mode. Messages that stay longer than this millisecond value are removed before they reach the output.</dd>
|
|
105
|
+
<dt>Interval (ms) <span class="property-type">number</span></dt>
|
|
106
|
+
<dd>Minimum time to wait between forwarded messages. Zero means send immediately when data is available.</dd>
|
|
107
|
+
</dl>
|
|
108
|
+
|
|
109
|
+
<h3>Behavior</h3>
|
|
110
|
+
<ul>
|
|
111
|
+
<li>Messages are processed in FIFO order while respecting the selected mode.</li>
|
|
112
|
+
<li>Queue-size mode enforces a hard cap, rejecting excess messages.</li>
|
|
113
|
+
<li>Timeout mode keeps buffering but evicts stale entries before sending.</li>
|
|
114
|
+
<li>The interval ensures a steady pace by adding delays between sends when configured.</li>
|
|
115
|
+
</ul>
|
|
116
|
+
|
|
117
|
+
<h3>Status</h3>
|
|
118
|
+
<p>The node status reflects whether the queue is idle, holding messages, or actively sending.</p>
|
|
119
|
+
</script>
|