UNPKG

compress-base64

Version:
93 lines (92 loc) 4.12 kB
/** * compress-base64 v7.0.10 by sunsilent * @license MIT **/ (function(root, factory) { if ('object' == typeof exports && 'object' == typeof module) module.exports = factory(); else if ('function' == typeof define && define.amd) define([], factory); else if ('object' == typeof exports) exports["CompressBase64"] = factory(); else root["CompressBase64"] = factory(); })(self, function() { return function() { "use strict"; var __webpack_require__ = {}; !function() { __webpack_require__.d = function(exports1, definition) { for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, { enumerable: true, get: definition[key] }); }; }(); !function() { __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }; }(); !function() { __webpack_require__.r = function(exports1) { if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, { value: 'Module' }); Object.defineProperty(exports1, '__esModule', { value: true }); }; }(); var __webpack_exports__ = {}; __webpack_require__.r(__webpack_exports__); __webpack_require__.d(__webpack_exports__, { default: function() { return compress; } }); var step = 0.001; function compress(base64, options) { var _options_type = options.type, type = void 0 === _options_type ? 'image/jpeg' : _options_type, width = options.width, height = options.height, _options_min = options.min, min = void 0 === _options_min ? 0 : _options_min, _options_max = options.max, max = void 0 === _options_max ? 200 : _options_max, crossOrigin = options.crossOrigin, quality = options.quality; return new Promise(function(resolve, reject) { var tq = quality || 0.8; var img = new Image(); img.src = base64; if ('string' == typeof crossOrigin) img.setAttribute('crossOrigin', crossOrigin); var tw = width; var th = height; img.onload = function() { if (isNaN(tw) && isNaN(th)) { tw = img.width; th = img.height; } else { if (!isNaN(tw) && isNaN(th)) th = tw * img.height / img.width; if (isNaN(tw) && !isNaN(th)) tw = th * img.width / img.height; } img.width = tw; img.height = th; var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); canvas.width = tw; canvas.height = th; ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.drawImage(img, 0, 0, canvas.width, canvas.height); var _$base64 = canvas.toDataURL(type, tq); while(_$base64.length / 1024 > max){ if (tq <= step) { _$base64 = canvas.toDataURL(type, step); break; } tq -= step; _$base64 = canvas.toDataURL(type, tq); } while(_$base64.length / 1024 < min){ tq += step; _$base64 = canvas.toDataURL(type, tq); } resolve(_$base64); }; img.onerror = function(error) { reject(error); }; }); } return __webpack_exports__; }(); });