'a'
mh-two-thousand-and-two
2024-04-12 44d2c92345cd156a59fc327b3060292a282d2893
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
var isFn = require('./isFn');
var loadImg = require('./loadImg');
var noop = require('./noop');
var defaults = require('./defaults');
var createUrl = require('./createUrl');
var isStr = require('./isStr');
exports = function(file, options, cb) {
    if (isFn(options)) {
        cb = options;
        options = {};
    }
    cb = cb || noop;
    options = options || {};
    defaults(options, defOptions);
    options.mimeType = options.mimeType || file.type;
    if (isStr(file)) {
        options.isUrl = true;
    } else {
        file = createUrl(file);
    }
    loadImg(file, function(err, img) {
        if (err) return cb(err);
        compress(img, options, cb);
    });
};
function compress(img, options, cb) {
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
    var width = img.width;
    var height = img.height;
    var ratio = width / height;
    var maxWidth = options.maxWidth;
    var maxHeight = options.maxHeight;
    if (options.width || options.height) {
        if (options.width) {
            width = options.width;
            height = width / ratio;
        } else if (options.height) {
            height = options.height;
            width = height * ratio;
        }
    } else {
        if (width > maxWidth) {
            width = maxWidth;
            height = width / ratio;
        }
        if (height > maxHeight) {
            height = maxHeight;
            width = height * ratio;
        }
    }
    width = floor(width);
    height = floor(height);
    canvas.width = width;
    canvas.height = height;
    ctx.drawImage(img, 0, 0, width, height);
    if (URL && options.isUrl) URL.revokeObjectURL(img.src);
    if (canvas.toBlob) {
        try {
            canvas.toBlob(
                function(file) {
                    cb(null, file);
                },
                options.mimeType,
                options.quality
            );
        } catch (e) {
            cb(e);
        }
    } else {
        cb(new Error('Canvas toBlob is not supported'));
    }
}
var defOptions = {
    maxWidth: Infinity,
    maxHeight: Infinity,
    quality: 0.8
};
var floor = Math.floor;
 
module.exports = exports;