img-about
Version:
A module for image processing in browser, includes getting naturalSize, zooming, compressing... wrapped by Promise
10 lines (8 loc) • 2.8 kB
JavaScript
/**
* Bundle of img-about
* Generated: 2019-07-23
* Version: 2.2.0
* License: MIT
* Author: livelybone(2631541504@qq.com)
*/
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).imgCompress=t()}(this,function(){"use strict";"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;var e,d=(function(e){var t;t=function(){return function(e,t,n){t=t||"",n=n||512;for(var o=atob(e),r=[],i=0;i<o.length;i+=n){for(var a=o.slice(i,i+n),s=new Array(a.length),c=0;c<a.length;c++)s[c]=a.charCodeAt(c);var f=new Uint8Array(s);r.push(f)}return new Blob(r,{type:t})}},e.exports?(e.exports=t(),e.exports.default=e.exports):window.b64toBlob=t()}(e={exports:{}},e.exports),e.exports);function o(o){return new Promise(function(t,n){try{var e=new FileReader;e.onload=function(e){t(e.target.result)},e.readAsDataURL(o)}catch(e){n(e)}})}function r(r){return new Promise(function(e,t){var n=document.createElement("img"),o=function(){e({width:n.width,height:n.height})};n.onload=o,n.onerror=function(){t(new Error("Image<"+r+"> loaded error"))},n.src=r,n.complete&&o()})}var i=!!document.createElement("canvas").getContext;return function(e,t){if(!i)return Promise.reject(new Error("Canvas is not supported in your browser"));if(!(e instanceof File||e instanceof Blob))return Promise.reject(new Error("The type of param `imgFile` is not matched It should be an instance of one of the File and Blob"));var u=["scale","fixedWidth","fixedHeight","fixedSize"],n={compressType:u[0],scale:1,imageSize:0,imageType:e.type||"image/png",quality:.8,toBlob:!0},l=n;return t&&Object.keys(n).forEach(function(e){l[e]=void 0!==t[e]?t[e]:n[e]}),o(e).then(function(s){var c=document.createElement("canvas"),f=c.getContext("2d");return function(n){return new Promise(function(e,t){"string"==typeof n?e(r(n)):n instanceof Image?n.naturalWidth?e({width:n.naturalWidth,height:n.naturalHeight}):e(r(n.src)):n instanceof FileList||n instanceof File||n instanceof Blob?e(r(o(n[0]||n))):t(new Error("The type of param `img` is not matched. It should be an instance of one of the String, Image, File, FileList and Blob"))})}(s).then(function(e){var t,n,o=e.width,r=e.height;l.compressType===u[1]?n=(t=l.imageSize||o)*r/o:l.compressType===u[2]?t=(n=l.imageSize||r)*o/r:l.compressType===u[3]?r<o?t=(n=l.imageSize||r)*o/r:n=(t=l.imageSize||o)*r/o:(t=o*l.scale,n=r*l.scale);var i=document.createElement("img");i.src=s,c.width=t,c.height=n,f.drawImage(i,0,0,t,n);var a=c.toDataURL(l.imageType,l.quality);return l.toBlob?function(e){try{var t=e.split(","),n=t[0].match(/:(.*?);/)[1];return Promise.resolve(d(t[1],n))}catch(e){return Promise.reject(e)}}(a):a})})}});