UNPKG

compress-base64

Version:
88 lines (87 loc) 3.06 kB
/** * compress-base64 v7.0.10 by sunsilent * @license MIT **/ "use strict"; var __webpack_require__ = {}; (()=>{ __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] }); }; })(); (()=>{ __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }; })(); (()=>{ __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; } }); const step = 0.001; function compress(base64, options) { const { type = 'image/jpeg', width, height, min = 0, max = 200, crossOrigin, quality } = options; return new Promise((resolve, reject)=>{ let tq = quality || 0.8; const img = new Image(); img.src = base64; if ('string' == typeof crossOrigin) img.setAttribute('crossOrigin', crossOrigin); let tw = width; let th = height; img.onload = ()=>{ 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; const canvas = document.createElement('canvas'); const 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); let 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 = (error)=>{ reject(error); }; }); } var __webpack_export_target__ = exports; for(var __webpack_i__ in __webpack_exports__)__webpack_export_target__[__webpack_i__] = __webpack_exports__[__webpack_i__]; if (__webpack_exports__.__esModule) Object.defineProperty(__webpack_export_target__, '__esModule', { value: true });