From 07764c376b965485e5a99a5a2aa28acccf8983a7 Mon Sep 17 00:00:00 2001 From: sebseb7 Date: Sun, 21 Dec 2025 23:18:51 +0100 Subject: [PATCH] u --- server.js | 33 +++++++++++++++++++++++++-------- 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/server.js b/server.js index b763153..c605191 100644 --- a/server.js +++ b/server.js @@ -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) {