From ec905fba544003d087d8be6ddf4a454107fffbd2 Mon Sep 17 00:00:00 2001 From: Hedger Wang Date: Fri, 5 May 2023 18:08:56 -0700 Subject: [PATCH 1/3] Clean unused canvas to prevent memory leak --- lib/image-compression.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lib/image-compression.js b/lib/image-compression.js index f811826..f6e1717 100644 --- a/lib/image-compression.js +++ b/lib/image-compression.js @@ -89,6 +89,9 @@ export default async function compress(file, options, previousProgress = 0) { if (process.env.BUILD === 'development') { console.log('no need to compress'); } + cleanupCanvasMemory(maxWidthOrHeightFixedCanvas); + cleanupCanvasMemory(orientationFixedCanvas); + cleanupCanvasMemory(origCanvas); setProgress(100); return tempFile; } From 2891e73a0080408551bc38c87d2a43d7e0f7f025 Mon Sep 17 00:00:00 2001 From: Hedger Wang Date: Fri, 5 May 2023 18:10:46 -0700 Subject: [PATCH 2/3] Clean unused canvas to avoid memory leak. --- lib/utils.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/utils.js b/lib/utils.js index a0335be..37ba2b8 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -315,8 +315,8 @@ export async function isAutoOrientationInBrowser() { const testImageCanvas = (await drawFileInCanvas(testImageFile))[1]; const testImageFile2 = await canvasToFile(testImageCanvas, testImageFile.type, testImageFile.name, testImageFile.lastModified); cleanupCanvasMemory(testImageCanvas); - const img = (await drawFileInCanvas(testImageFile2))[0]; - // console.log('img', img.width, img.height) + const [img, fileCanvas] = (await drawFileInCanvas(testImageFile2)); + cleanupCanvasMemory(fileCanvas); isAutoOrientationInBrowser.cachedResult = img.width === 1 && img.height === 2; return isAutoOrientationInBrowser.cachedResult; From 5046881fd9146d47ceb50902401f3c7561f6bf89 Mon Sep 17 00:00:00 2001 From: Hedger Wang Date: Mon, 8 May 2023 10:51:51 -0700 Subject: [PATCH 3/3] Fix `cleanupCanvasMemory` The function `cleanupCanvasMemory` does not really cleans up the memory when the canvas size is set as `0`. The right way to clean up the memory is to size the size to `1` instead. --- lib/utils.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lib/utils.js b/lib/utils.js index 37ba2b8..9399f27 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -292,9 +292,11 @@ export function cleanupCanvasMemory(canvas) { // garbage clean canvas for safari // ref: https://bugs.webkit.org/show_bug.cgi?id=195325 // eslint-disable-next-line no-param-reassign - canvas.width = 0; + canvas.width = 1; // eslint-disable-next-line no-param-reassign - canvas.height = 0; + canvas.height = 1; + const ctx = canvas.getContext('2d'); + ctx && ctx.clearRect(0, 0, 1, 1); } // Check if browser supports automatic image orientation