This commit is contained in:
sebseb7
2025-12-21 23:18:51 +01:00
parent 4ed5bc3415
commit 07764c376b

View File

@@ -148,24 +148,41 @@ app.post('/upload', authenticate, upload.single('image'), async (req, res) => {
// Check if we need to modify the image
const shouldRotate = settings.rotation && settings.rotation !== 0;
const shouldCrop = settings.crop && settings.crop.width > 0 && settings.crop.height > 0;
// Crop if width/height > 0, OR if left/top > 0 (then we calculate width/height)
const hasCropOffset = settings.crop && (settings.crop.left > 0 || settings.crop.top > 0);
const hasCropSize = settings.crop && settings.crop.width > 0 && settings.crop.height > 0;
const shouldCrop = hasCropOffset || hasCropSize;
if (shouldRotate || shouldCrop) {
console.log(`Applying transformations for ${cameraId}:`, { rotation: settings.rotation, crop: settings.crop });
let pipeline = sharp(req.file.path);
let imageBuffer = fs.readFileSync(req.file.path);
// Apply rotation first if needed
if (shouldRotate) {
pipeline = pipeline.rotate(settings.rotation);
imageBuffer = await sharp(imageBuffer).rotate(settings.rotation).toBuffer();
}
// Apply crop on the (potentially rotated) image
if (shouldCrop) {
// crop format: { left, top, width, height }
pipeline = pipeline.extract(settings.crop);
const metadata = await sharp(imageBuffer).metadata();
// Calculate crop params, ensure at least 1px dimensions
const cropParams = {
left: Math.min(settings.crop.left || 0, metadata.width - 1),
top: Math.min(settings.crop.top || 0, metadata.height - 1),
width: settings.crop.width > 0
? settings.crop.width
: Math.max(1, metadata.width - (settings.crop.left || 0)),
height: settings.crop.height > 0
? settings.crop.height
: Math.max(1, metadata.height - (settings.crop.top || 0))
};
console.log(`Calculated crop params:`, cropParams);
imageBuffer = await sharp(imageBuffer).extract(cropParams).toBuffer();
}
// Overwrite the original file with transformed version
const buffer = await pipeline.toBuffer();
fs.writeFileSync(req.file.path, buffer);
// Write final result
fs.writeFileSync(req.file.path, imageBuffer);
console.log(`Transformed image saved to ${req.file.path}`);
}
} catch (transformError) {