1- import { canvasToFile , drawFileInCanvas , followExifOrientation , getExifOrientation , handleMaxWidthOrHeight , getNewCanvasAndCtx } from './utils'
1+ import { canvasToFile , drawFileInCanvas , followExifOrientation , getExifOrientation , handleMaxWidthOrHeight , getNewCanvasAndCtx , cleanupMemory } from './utils'
22
33/**
44 * Compress an image file.
@@ -17,39 +17,49 @@ export default async function compress (file, options) {
1717 const maxSizeByte = options . maxSizeMB * 1024 * 1024
1818
1919 // drawFileInCanvas
20- let [ img , canvas ] = await drawFileInCanvas ( file )
20+ let [ img , origCanvas ] = await drawFileInCanvas ( file )
2121
2222 // handleMaxWidthOrHeight
23- canvas = handleMaxWidthOrHeight ( canvas , options )
23+ let maxWidthOrHeightFixedCanvas = handleMaxWidthOrHeight ( origCanvas , options )
2424
2525 // exifOrientation
2626 options . exifOrientation = options . exifOrientation || await getExifOrientation ( file )
27- canvas = followExifOrientation ( canvas , options . exifOrientation )
27+ let orientationFixedCanvas = followExifOrientation ( maxWidthOrHeightFixedCanvas , options . exifOrientation )
2828
2929 let quality = 1
30-
31- let tempFile = await canvasToFile ( canvas , file . type , file . name , file . lastModified , quality )
30+
31+ let tempFile = await canvasToFile ( orientationFixedCanvas , file . type , file . name , file . lastModified , quality )
3232 // check if we need to compress or resize
3333 if ( tempFile . size <= maxSizeByte ) {
3434 // no need to compress
3535 return tempFile
3636 }
3737
3838 let compressedFile = tempFile
39+ let newCanvas , ctx
40+ let canvas = orientationFixedCanvas
3941 while ( remainingTrials -- && compressedFile . size > maxSizeByte ) {
40- const newWidth = canvas . width * 0.9
41- const newHeight = canvas . height * 0.9
42- const [ newCanvas , ctx ] = getNewCanvasAndCtx ( newWidth , newHeight )
42+ const newWidth = canvas . width * 0.9 ;
43+ const newHeight = canvas . height * 0.9 ;
44+ [ newCanvas , ctx ] = getNewCanvasAndCtx ( newWidth , newHeight )
4345
4446 ctx . drawImage ( canvas , 0 , 0 , newWidth , newHeight )
4547
4648 if ( file . type === 'image/jpeg' ) {
4749 quality *= 0.9
4850 }
4951 compressedFile = await canvasToFile ( newCanvas , file . type , file . name , file . lastModified , quality )
50-
52+ cleanupMemory ( canvas )
5153 canvas = newCanvas
5254 }
5355
56+ // garbage clean canvas for safari
57+ // ref: https://bugs.webkit.org/show_bug.cgi?id=195325
58+ cleanupMemory ( canvas )
59+ cleanupMemory ( newCanvas )
60+ cleanupMemory ( maxWidthOrHeightFixedCanvas )
61+ cleanupMemory ( orientationFixedCanvas )
62+ cleanupMemory ( origCanvas )
63+
5464 return compressedFile
5565}
0 commit comments