Skip to content

Commit f171d80

Browse files
committed
fix: update code to make it work in webworker mode
1 parent 93ce771 commit f171d80

File tree

2 files changed

+112
-90
lines changed

2 files changed

+112
-90
lines changed

lib/index.js

Lines changed: 51 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
import compress from './image-compression'
1+
import './polyfill';
2+
3+
import compress from './image-compression';
24
import {
35
canvasToFile,
46
drawFileInCanvas,
@@ -11,15 +13,18 @@ import {
1113
followExifOrientation,
1214
CustomFile,
1315
cleanupCanvasMemory,
14-
isAutoOrientationInBrowser
15-
} from './utils'
16-
import { compressOnWebWorker } from './web-worker'
16+
isAutoOrientationInBrowser,
17+
approximateBelowMaximumCanvasSizeOfBrowser,
18+
getBrowserName,
19+
} from './utils';
20+
// eslint-disable-next-line import/no-cycle
21+
import { compressOnWebWorker } from './web-worker';
1722

1823
/**
1924
* Compress an image file.
2025
*
2126
* @param {File} file
22-
* @param {Object} options - { maxSizeMB=Number.POSITIVE_INFINITY, maxWidthOrHeight, useWebWorker=false, maxIteration = 10, exifOrientation, fileType }
27+
* @param {Object} opts - { maxSizeMB=Number.POSITIVE_INFINITY, maxWidthOrHeight, useWebWorker=false, maxIteration = 10, exifOrientation, fileType }
2328
* @param {number} [options.maxSizeMB=Number.POSITIVE_INFINITY]
2429
* @param {number} [options.maxWidthOrHeight=undefined]
2530
* @param {boolean} [options.useWebWorker=false]
@@ -29,73 +34,74 @@ import { compressOnWebWorker } from './web-worker'
2934
* @param {string} [options.fileType] - default to be the original mime type from the image file
3035
* @returns {Promise<File | Blob>}
3136
*/
32-
async function imageCompression (file, options) {
37+
async function imageCompression(file, options) {
38+
const opts = { ...options };
3339

34-
let compressedFile
35-
let progress = 0
36-
let onProgress
40+
let compressedFile;
41+
let progress = 0;
42+
const { onProgress } = opts;
3743

38-
options.maxSizeMB = options.maxSizeMB || Number.POSITIVE_INFINITY
39-
const useWebWorker = typeof options.useWebWorker === 'boolean' ? options.useWebWorker : true
40-
delete options.useWebWorker
41-
onProgress = options.onProgress
42-
options.onProgress = (aProgress) => {
43-
progress = aProgress
44+
opts.maxSizeMB = opts.maxSizeMB || Number.POSITIVE_INFINITY;
45+
const useWebWorker = typeof opts.useWebWorker === 'boolean' ? opts.useWebWorker : true;
46+
delete opts.useWebWorker;
47+
opts.onProgress = (aProgress) => {
48+
progress = aProgress;
4449
if (typeof onProgress === 'function') {
45-
onProgress(progress)
50+
onProgress(progress);
4651
}
47-
}
52+
};
4853

4954
if (!(file instanceof Blob || file instanceof CustomFile)) {
50-
throw new Error('The file given is not an instance of Blob or File')
55+
throw new Error('The file given is not an instance of Blob or File');
5156
} else if (!/^image/.test(file.type)) {
52-
throw new Error('The file given is not an image')
57+
throw new Error('The file given is not an image');
5358
}
5459

5560
// try run in web worker, fall back to run in main thread
56-
const inWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope
61+
// eslint-disable-next-line no-undef, no-restricted-globals
62+
const inWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;
5763

5864
// if ((useWebWorker && typeof Worker === 'function') || inWebWorker) {
59-
// console.log('run compression in web worker')
65+
// console.log('run compression in web worker');
6066
// } else {
61-
// console.log('run compression in main thread')
67+
// console.log('run compression in main thread');
6268
// }
6369

6470
if (useWebWorker && typeof Worker === 'function' && !inWebWorker) {
6571
try {
66-
// console.log(1)
6772
// "compressOnWebWorker" is kind of like a recursion to call "imageCompression" again inside web worker
68-
compressedFile = await compressOnWebWorker(file, options)
73+
compressedFile = await compressOnWebWorker(file, opts);
6974
} catch (e) {
70-
// console.warn('Run compression in web worker failed:', e, ', fall back to main thread')
71-
// console.log(1.5)
72-
compressedFile = await compress(file, options)
75+
// console.warn('Run compression in web worker failed:', e, ', fall back to main thread');
76+
compressedFile = await compress(file, opts);
7377
}
7478
} else {
75-
// console.log(2)
76-
compressedFile = await compress(file, options)
79+
compressedFile = await compress(file, opts);
7780
}
7881

7982
try {
80-
compressedFile.name = file.name
81-
compressedFile.lastModified = file.lastModified
83+
compressedFile.name = file.name;
84+
compressedFile.lastModified = file.lastModified;
85+
// eslint-disable-next-line no-empty
8286
} catch (e) {}
8387

84-
return compressedFile
88+
return compressedFile;
8589
}
8690

87-
imageCompression.getDataUrlFromFile = getDataUrlFromFile
88-
imageCompression.getFilefromDataUrl = getFilefromDataUrl
89-
imageCompression.loadImage = loadImage
90-
imageCompression.drawImageInCanvas = drawImageInCanvas
91-
imageCompression.drawFileInCanvas = drawFileInCanvas
92-
imageCompression.canvasToFile = canvasToFile
93-
imageCompression.getExifOrientation = getExifOrientation
91+
imageCompression.getDataUrlFromFile = getDataUrlFromFile;
92+
imageCompression.getFilefromDataUrl = getFilefromDataUrl;
93+
imageCompression.loadImage = loadImage;
94+
imageCompression.drawImageInCanvas = drawImageInCanvas;
95+
imageCompression.drawFileInCanvas = drawFileInCanvas;
96+
imageCompression.canvasToFile = canvasToFile;
97+
imageCompression.getExifOrientation = getExifOrientation;
9498

95-
imageCompression.handleMaxWidthOrHeight = handleMaxWidthOrHeight
96-
imageCompression.followExifOrientation = followExifOrientation
97-
imageCompression.cleanupCanvasMemory = cleanupCanvasMemory
98-
imageCompression.isAutoOrientationInBrowser = isAutoOrientationInBrowser
99-
imageCompression.version = '1.0.15'
99+
imageCompression.handleMaxWidthOrHeight = handleMaxWidthOrHeight;
100+
imageCompression.followExifOrientation = followExifOrientation;
101+
imageCompression.cleanupCanvasMemory = cleanupCanvasMemory;
102+
imageCompression.isAutoOrientationInBrowser = isAutoOrientationInBrowser;
103+
imageCompression.approximateBelowMaximumCanvasSizeOfBrowser = approximateBelowMaximumCanvasSizeOfBrowser;
104+
imageCompression.getBrowserName = getBrowserName;
105+
imageCompression.version = '1.0.15';
100106

101-
export default imageCompression
107+
export default imageCompression;

lib/web-worker.js

Lines changed: 61 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,50 @@
1-
import lib from './index'
2-
import compress from './image-compression'
3-
import { cleanupCanvasMemory, getNewCanvasAndCtx } from './utils'
4-
import UPNG from './UPNG'
5-
import * as UZIP from 'uzip'
1+
import * as UZIP from 'uzip';
2+
// eslint-disable-next-line import/no-cycle
3+
import lib from './index';
4+
import compress from './image-compression';
5+
import { getNewCanvasAndCtx } from './utils';
6+
import UPNG from './UPNG';
7+
import MaxCanvasSize from './config/max-canvas-size';
68

7-
let cnt = 0
8-
let imageCompressionLibUrl
9-
let worker
9+
let cnt = 0;
10+
let imageCompressionLibUrl;
11+
let worker;
1012

11-
function createWorker (script) {
13+
function createWorker(script) {
1214
if (typeof script === 'function') {
13-
script = `(${script})()`
15+
script = `(${script})()`;
1416
}
15-
return new Worker(URL.createObjectURL(new Blob([script])))
17+
return new Worker(URL.createObjectURL(new Blob([script])));
1618
}
1719

18-
function createSourceObject (str) {
20+
function createSourceObject(str) {
1921
// console.log('createSourceObject', str)
20-
return URL.createObjectURL(new Blob([str], { type: 'application/javascript' }))
22+
return URL.createObjectURL(new Blob([str], { type: 'application/javascript' }));
2123
}
2224

2325
function stringify(o) {
24-
return JSON.stringify(o, (key, value) => {
25-
return (typeof value === 'function' ) ? `BIC_FN:::(() => ${value.toString()})()` : value;
26-
})
26+
return JSON.stringify(o, (key, value) => ((typeof value === 'function') ? `BIC_FN:::(function () { return ${value.toString()} })()` : value));
2727
}
2828

2929
function parse(o) {
30-
if (typeof o === 'string') return o
31-
const result = {}
30+
if (typeof o === 'string') return o;
31+
const result = {};
3232
Object.entries(o).forEach(([key, value]) => {
3333
if (typeof value === 'string' && value.startsWith('BIC_FN:::')) {
3434
try {
35-
result[key] = eval(value.replace(/^BIC_FN:::/, ''))
35+
result[key] = eval(value.replace(/^BIC_FN:::/, ''));
3636
} catch (e) {
37-
console.log(key, e)
38-
throw e
37+
// console.log(key, e);
38+
throw e;
3939
}
4040
} else {
41-
result[key] = parse(value)
41+
result[key] = parse(value);
4242
}
43-
})
44-
return result
43+
});
44+
return result;
4545
}
4646

47-
function generateLib () {
47+
function generateLib() {
4848
// prepare the lib to be used inside WebWorker
4949
return createSourceObject(`
5050
// reconstruct library
@@ -61,6 +61,8 @@ function generateLib () {
6161
imageCompression.followExifOrientation = ${lib.followExifOrientation}
6262
imageCompression.cleanupCanvasMemory = ${lib.cleanupCanvasMemory}
6363
imageCompression.isAutoOrientationInBrowser = ${lib.isAutoOrientationInBrowser}
64+
imageCompression.approximateBelowMaximumCanvasSizeOfBrowser = ${lib.approximateBelowMaximumCanvasSizeOfBrowser}
65+
imageCompression.getBrowserName = ${lib.getBrowserName}
6466
6567
// functions / objects
6668
getDataUrlFromFile = imageCompression.getDataUrlFromFile
@@ -74,13 +76,27 @@ function generateLib () {
7476
followExifOrientation = imageCompression.followExifOrientation
7577
cleanupCanvasMemory = imageCompression.cleanupCanvasMemory
7678
isAutoOrientationInBrowser = imageCompression.isAutoOrientationInBrowser
79+
approximateBelowMaximumCanvasSizeOfBrowser = imageCompression.approximateBelowMaximumCanvasSizeOfBrowser
80+
getBrowserName = imageCompression.getBrowserName
7781
7882
getNewCanvasAndCtx = ${getNewCanvasAndCtx}
7983
CustomFileReader = FileReader
8084
CustomFile = File
85+
MaxCanvasSize = ${JSON.stringify(MaxCanvasSize)}
86+
function compress (){return (${compress}).apply(null, arguments)}
87+
88+
// core-js
8189
function _slicedToArray(arr, n) { return arr }
8290
function _typeof(a) { return typeof a }
83-
function compress (){return (${compress}).apply(null, arguments)}
91+
function _objectSpread2(target) {
92+
for (var i = 1; i < arguments.length; i++) {
93+
var source = arguments[i] != null ? arguments[i] : {};
94+
95+
Object.assign(target, source)
96+
}
97+
98+
return target;
99+
}
84100
85101
// Libraries
86102
const parse = ${parse}
@@ -164,7 +180,7 @@ function generateLib () {
164180
n(N.D,30,0);n(N.v,320,0)}());return H.H.N}()
165181
166182
const UZIP = {}
167-
UZIP["parse"] = ${UZIP["parse"]}
183+
UZIP["parse"] = ${UZIP.parse}
168184
UZIP._readLocal = ${UZIP._readLocal}
169185
UZIP.inflateRaw = ${UZIP.inflateRaw}
170186
UZIP.inflate = ${UZIP.inflate}
@@ -291,10 +307,10 @@ function generateLib () {
291307
for(var i=0; i<320; i++) U.ttree.push(0,0);
292308
*/
293309
})()
294-
`)
310+
`);
295311
}
296312

297-
function generateWorkerScript () {
313+
function generateWorkerScript() {
298314
// code to be run in the WebWorker
299315
return createWorker(`
300316
let scriptImported = false
@@ -315,43 +331,43 @@ function generateWorkerScript () {
315331
self.postMessage({ error: e.message + '\\n' + e.stack, id })
316332
}
317333
})
318-
`)
334+
`);
319335
}
320336

321-
export function compressOnWebWorker (file, options) {
337+
export function compressOnWebWorker(file, options) {
322338
return new Promise(async (resolve, reject) => {
323-
let id = cnt++
339+
const id = cnt++;
324340

325341
if (!imageCompressionLibUrl) {
326-
imageCompressionLibUrl = generateLib()
342+
imageCompressionLibUrl = generateLib();
327343
}
328344

329345
if (!worker) {
330-
worker = generateWorkerScript()
346+
worker = generateWorkerScript();
331347
}
332348

333-
function handler (e) {
349+
function handler(e) {
334350
if (e.data.id === id) {
335351
if (e.data.progress !== undefined) {
336-
options.onProgress(e.data.progress)
337-
return
352+
options.onProgress(e.data.progress);
353+
return;
338354
}
339-
worker.removeEventListener('message', handler)
355+
worker.removeEventListener('message', handler);
340356
if (e.data.error) {
341-
reject(new Error(e.data.error))
357+
reject(new Error(e.data.error));
342358
}
343-
resolve(e.data.file)
359+
resolve(e.data.file);
344360
}
345361
}
346362

347-
worker.addEventListener('message', handler)
348-
worker.addEventListener('error', reject)
363+
worker.addEventListener('message', handler);
364+
worker.addEventListener('error', reject);
349365

350366
worker.postMessage({
351367
file,
352368
id,
353369
imageCompressionLibUrl,
354-
options: { ...options, onProgress: undefined }
355-
})
356-
})
370+
options: { ...options, onProgress: undefined },
371+
});
372+
});
357373
}

0 commit comments

Comments
 (0)