From ebc61ab3b45da91d053d07e793cf3d79fc41b2f9 Mon Sep 17 00:00:00 2001 From: Martijn Gastkemper Date: Tue, 1 Aug 2023 17:36:29 +0200 Subject: [PATCH] Fix parsing empty and zero width/height value - Fix Sharp error when zero is given - Remove hexadecimal width / height value support - Add tests for empty value --- test/resizeImage.test.js | 16 ++++++++++++++++ util/resizeImage.js | 11 +++++++---- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/test/resizeImage.test.js b/test/resizeImage.test.js index 5a9fd48..18d4dfd 100644 --- a/test/resizeImage.test.js +++ b/test/resizeImage.test.js @@ -42,6 +42,22 @@ describe("resizeImage", () => { const output = await resizeImage(input, "png", "png", 50); expect(output.equals(expectedOutput)).toBe(true); }); + it("It can handle an empty string height", async () => { + const input = fs.readFileSync(__dirname + "/fixtures/pixelme.png"); + const expectedOutput = fs.readFileSync( + __dirname + "/fixtures/pixelme50x.png" + ); + const output = await resizeImage(input, "png", "png", "50", ""); + expect(output.equals(expectedOutput)).toBe(true); + }); + it("It can handle height 0", async () => { + const input = fs.readFileSync(__dirname + "/fixtures/pixelme.png"); + const expectedOutput = fs.readFileSync( + __dirname + "/fixtures/pixelme50x.png" + ); + const output = await resizeImage(input, "png", "png", "50", "0"); + expect(output.equals(expectedOutput)).toBe(true); + }); }); describe("Given an image with Orientation header", () => { diff --git a/util/resizeImage.js b/util/resizeImage.js index 490181e..5eaf13b 100644 --- a/util/resizeImage.js +++ b/util/resizeImage.js @@ -29,11 +29,14 @@ function resizeImage( const resizeOptions = { fit: fit }; - if (width) { - resizeOptions.width = parseInt(width); + const parsedWidth = width ? parseInt(width, 10) : 0; + if (parsedWidth > 0) { + resizeOptions.width = parsedWidth; } - if (height) { - resizeOptions.height = parseInt(height); + + const parsedHeight = height ? parseInt(height, 10) : 0; + if (parsedHeight > 0) { + resizeOptions.height = parsedHeight; } const sharp = SHARP(body).withMetadata().resize(resizeOptions);