-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
50 lines (41 loc) · 1.25 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
"use strict";
var canvasImageCompressor = {
compress: function(options = {}) {
return new Promise(function(resolve, reject) {
var mime_type, cvs, ctx;
if(options['sourceImgObj'] == undefined) {
reject('sourceImgObj mist be present');
}
if (options['sourceImgObj'] instanceof jQuery) {
if (!options['sourceImgObj'].length) {
reject('sourceImgObj mist be present');
}
options['sourceImgObj'] = options['sourceImgObj'].get(0);
}
mime_type = options['outputFormat'] || 'image/jpeg';
if(mime_type == 'png') {
mime_type = 'image/png';
}
cvs = document.createElement('canvas');
cvs.width = options['sourceImgObj'].naturalWidth;
cvs.height = options['sourceImgObj'].naturalHeight;
ctx = cvs.getContext('2d');
ctx.drawImage(options['sourceImgObj'], 0, 0);
cvs.toBlob(
function(blob) {
resolve(blob);
ctx.clearRect(
0,
0,
options['sourceImgObj'].naturalWidth,
options['sourceImgObj'].naturalHeight
);
cvs.remove();
},
mime_type,
(options['quality'] || 100)/100
);
});
}
};
module.exports = canvasImageCompressor;