From 3fe2c5685b798fb2b74324c32de675060fb296f0 Mon Sep 17 00:00:00 2001 From: Ian Chien Date: Tue, 24 Jun 2025 06:45:56 +0000 Subject: [PATCH] fix: reject loadImage when src is null or invalid MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Description: - To handle non-string/non-Buffer sources while fetching image. - Add test cases for '', null, and undefined inputs to loadImage() Test Result: ``` npm run test ... ✔ rejects when loadImage is called with null ✔ rejects when loadImage is called with undefined ✔ rejects when loadImage is called with empty string 291 passing (302ms) 6 pending ``` --- CHANGELOG.md | 1 + lib/image.js | 4 ++++ test/image.test.js | 18 ++++++++++++++++++ 3 files changed, 23 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b16096f69..aafa96fe8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ project adheres to [Semantic Versioning](http://semver.org/). ### Added ### Fixed * `roundRect()` shape incorrect when radii were large relative to rectangle size (#2400) +* Reject loadImage when src is null or invalid (#2304) 3.2.0 ================== diff --git a/lib/image.js b/lib/image.js index 9ffa3c794..72243439c 100644 --- a/lib/image.js +++ b/lib/image.js @@ -63,6 +63,10 @@ Object.defineProperty(Image.prototype, 'src', { } } else if (Buffer.isBuffer(val)) { setSource(this, val) + } else { + const err = new Error("Invalid image source") + if (typeof this.onerror === 'function') this.onerror(err) + else throw err } }, diff --git a/test/image.test.js b/test/image.test.js index a5d6f415c..edae78beb 100644 --- a/test/image.test.js +++ b/test/image.test.js @@ -516,6 +516,24 @@ describe('Image', function () { img.src = path.join(bmpDir, 'bomb.bmp') }) + it('rejects when loadImage is called with null', async function () { + await assert.rejects( + loadImage(null), + ) + }) + + it('rejects when loadImage is called with undefined', async function () { + await assert.rejects( + loadImage(undefined), + ) + }) + + it('rejects when loadImage is called with empty string', async function () { + await assert.rejects( + loadImage(''), + ) + }) + function testImgd (img, data) { const ctx = createCanvas(img.width, img.height).getContext('2d') ctx.drawImage(img, 0, 0)