@taro-hooks/compressorjs
Version:
JavaScript image compressor.
10 lines • 7.95 kB
JavaScript
/*!
* Compressor.js v2.2.0
* https://fengyuanchen.github.io/compressorjs
*
* Copyright 2018-present Chen Fengyuan
* Released under the MIT license
*
* Date: 2025-04-06T12:41:00.917Z
*/
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).Compressor=e()}(this,function(){"use strict";function n(){return(n=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i,a=arguments[e];for(i in a)Object.prototype.hasOwnProperty.call(a,i)&&(t[i]=a[i])}return t}).apply(this,arguments)}var t,e,r,i,s,l,h,c,o,a={exports:{}},L=(t=a,"undefined"!=typeof window&&"undefined"!=typeof window&&(e=globalThis||window,r=e.HTMLCanvasElement&&e.HTMLCanvasElement.prototype,i=!!r,s=e.Blob&&function(){try{return Boolean(new Blob)}catch(t){return!1}}(),l=s&&e.Uint8Array&&function(){try{return 100===new Blob([new Uint8Array(100)]).size}catch(t){return!1}}(),h=e.BlobBuilder||e.WebKitBlobBuilder||e.MozBlobBuilder||e.MSBlobBuilder,c=/^data:((.*?)(;charset=.*?)?)(;base64)?,/,o=(s||h)&&e.atob&&e.ArrayBuffer&&e.Uint8Array&&function(t){var e,i,a,r,o,n=t.match(c);if(!n)throw new Error("invalid data URI");for(e=n[2]?n[1]:"text/plain"+(n[3]||";charset=US-ASCII"),o=!!n[4],t=t.slice(n[0].length),i=(o?atob:decodeURIComponent)(t),n=new ArrayBuffer(i.length),a=new Uint8Array(n),r=0;r<i.length;r+=1)a[r]=i.charCodeAt(r);return s?new Blob([l?a:n],{type:e}):((o=new h).append(n),o.getBlob(e))},i&&e.HTMLCanvasElement&&!r.toBlob&&(r.mozGetAsFile?r.toBlob=function(t,e,i){var a=this;setTimeout(function(){i&&r.toDataURL&&o?t(o(a.toDataURL(e,i))):t(a.mozGetAsFile("blob",e))})}:r.toDataURL&&o&&(r.msToBlob?r.toBlob=function(t,e,i){var a=this;setTimeout(function(){(e&&"image/png"!==e||i)&&r.toDataURL&&o?t(o(a.toDataURL(e,i))):t(a.msToBlob(e))})}:r.toBlob=function(t,e,i){var a=this;setTimeout(function(){t(o(a.toDataURL(e,i)))})})),t.exports?t.exports=o:e.dataURLtoBlob=o),a.exports),d={strict:!0,checkOrientation:!0,maxWidth:1/0,maxHeight:1/0,minWidth:0,minHeight:0,width:void 0,height:void 0,resize:"none",quality:.8,mimeType:"auto",convertTypes:["image/png"],convertSize:5e6,beforeDraw:null,drew:null,success:null,error:null};const u="undefined"!=typeof window&&void 0!==window.document?window:{},j=t=>0<t&&t<1/0,f=Array.prototype["slice"];const m=/^image\/.+$/;function k(t){return m.test(t)}const g=String["fromCharCode"];const p=u["btoa"];function b(t,e){var i,a=[];let r=new Uint8Array(t);for(;0<r.length;)a.push(g.apply(null,(i=r.subarray(0,8192),Array.from?Array.from(i):f.call(i)))),r=r.subarray(8192);return`data:${e};base64,`+p(a.join(""))}function w(t){var r,o,n,s,l=new DataView(t);let h;try{let e,i,a;if(255===l.getUint8(0)&&216===l.getUint8(1)){var c=l.byteLength;let t=2;for(;t+1<c;){if(255===l.getUint8(t)&&225===l.getUint8(t+1)){i=t;break}t+=1}}if(a=i&&(r=i+4,o=i+10,"Exif"===function(t,e,i){let a="",r;for(i+=e,r=e;r<i;r+=1)a+=g(t.getUint8(r));return a}(l,r,4))&&(n=l.getUint16(o),(e=18761===n)||19789===n)&&42===l.getUint16(o+2,e)&&8<=(s=l.getUint32(o+4,e))?o+s:a){var d,u=l.getUint16(a,e);let t;for(t=0;t<u;t+=1)if(d=a+12*t+2,274===l.getUint16(d,e)){d+=8,h=l.getUint16(d,e),l.setUint16(d,1,e);break}}}catch(t){h=1}return h}const y=/\.\d*(?:0|9){12}\d*$/;function D(t,e){e=1<arguments.length&&void 0!==e?e:1e11;return y.test(t)?Math.round(t*e)/e:t}function O(t,e){let{aspectRatio:i,height:a,width:r}=t;var o,t=1<arguments.length&&void 0!==e?e:"none",e=j(r),n=j(a);return e&&n?(o=a*i,("contain"===t||"none"===t)&&o>r||"cover"===t&&o<r?a=r/i:r=a*i):e?a=r/i:n&&(r=a*i),{width:r,height:a}}const{ArrayBuffer:v,FileReader:U}=u,B=u.URL||u.webkitURL,T=/\.\w+$/,R=u.Compressor;return class x{constructor(t,e){this.file=t,this.image=new Image,this.options={...d,...e},this.aborted=!1,this.result=null,this.init()}init(){const{file:a,options:t}=this;if(e=a,"undefined"!=typeof Blob&&(e instanceof Blob||"[object Blob]"===Object.prototype.toString.call(e))){const r=a.type;if(k(r))if(B&&U)if(v||(t.checkOrientation=!1),B&&!t.checkOrientation)this.load({url:B.createObjectURL(a)});else{var e=new U;const o=t.checkOrientation&&"image/jpeg"===r;(this.reader=e).onload=t=>{var e,t=(t=t.target).result,i={};o?1<(e=w(t))||!B?(i.url=b(t,r),1<e&&n(i,function(t){let e=0,i=1,a=1;switch(t){case 2:i=-1;break;case 3:e=-180;break;case 4:a=-1;break;case 5:e=90,a=-1;break;case 6:e=90;break;case 7:e=90,i=-1;break;case 8:e=-90}return{rotate:e,scaleX:i,scaleY:a}}(e))):i.url=B.createObjectURL(a):i.url=t,this.load(i)},e.onabort=()=>{this.fail(new Error("Aborted to read the image with FileReader."))},e.onerror=()=>{this.fail(new Error("Failed to read the image with FileReader."))},e.onloadend=()=>{this.reader=null},o?e.readAsArrayBuffer(a):e.readAsDataURL(a)}else this.fail(new Error("The current browser does not support image compression."));else this.fail(new Error("The first argument must be an image File or Blob object."))}else this.fail(new Error("The first argument must be a File or Blob object."))}load(t){const{file:e,image:i}=this;i.onload=()=>{this.draw({...t,naturalWidth:i.naturalWidth,naturalHeight:i.naturalHeight})},i.onabort=()=>{this.fail(new Error("Aborted to load the image."))},i.onerror=()=>{this.fail(new Error("Failed to load the image."))},u.navigator&&/(?:iPad|iPhone|iPod).*?AppleWebKit/i.test(u.navigator.userAgent)&&(i.crossOrigin="anonymous"),i.alt=e.name,i.src=t.url}draw(t){let{naturalWidth:e,naturalHeight:i,rotate:a=0,scaleX:r=1,scaleY:o=1}=t;var{file:t,image:n,options:s}=this,l=document.createElement("canvas"),h=l.getContext("2d"),c=Math.abs(a)%180==90,d=("contain"===s.resize||"cover"===s.resize)&&j(s.width)&&j(s.height);let u=Math.max(s.maxWidth,0)||1/0,f=Math.max(s.maxHeight,0)||1/0,m=Math.max(s.minWidth,0)||0,g=Math.max(s.minHeight,0)||0,p=e/i,{width:b,height:w}=s;c&&([u,f]=[f,u],[m,g]=[g,m],[b,w]=[w,b]),d&&(p=b/w),{width:u,height:f}=O({aspectRatio:p,width:u,height:f},"contain"),{width:m,height:g}=O({aspectRatio:p,width:m,height:g},"cover"),d?{width:b,height:w}=O({aspectRatio:p,width:b,height:w},s.resize):{width:b=e,height:w=i}=O({aspectRatio:p,width:b,height:w}),b=Math.floor(D(Math.min(Math.max(b,m),u))),w=Math.floor(D(Math.min(Math.max(w,g),f)));var y,v,U,B=-b/2,T=-w/2,R=b,x=w,A=[];d&&(y=d=0,v=e,U=i,{width:v,height:U}=O({aspectRatio:p,width:e,height:i},{contain:"cover",cover:"contain"}[s.resize]),d=(e-v)/2,y=(i-U)/2,A.push(d,y,v,U)),A.push(B,T,R,x),c&&([b,w]=[w,b]),l.width=b,l.height=w,k(s.mimeType)||(s.mimeType=t.type);let M="transparent";t.size>s.convertSize&&0<=s.convertTypes.indexOf(s.mimeType)&&(s.mimeType="image/jpeg"),"image/jpeg"===s.mimeType&&(M="#fff"),h.fillStyle=M,h.fillRect(0,0,b,w),s.beforeDraw&&s.beforeDraw.call(this,h,l),this.aborted||(h.save(),h.translate(b/2,w/2),h.rotate(a*Math.PI/180),h.scale(r,o),h.drawImage(n,...A),h.restore(),s.drew&&s.drew.call(this,h,l),this.aborted)||(d=t=>{this.aborted||this.done({naturalWidth:e,naturalHeight:i,result:t})},l.toBlob?l.toBlob(d,s.mimeType,s.quality):d(L(l.toDataURL(s.mimeType,s.quality))))}done(t){let{naturalWidth:e,naturalHeight:i,result:a}=t;var{file:t,image:r,options:o}=this;B&&!o.checkOrientation&&B.revokeObjectURL(r.src),!a||o.strict&&a.size>t.size&&o.mimeType===t.type&&!(o.width>e||o.height>i||o.minWidth>e||o.minHeight>i||o.maxWidth<e||o.maxHeight<i)?a=t:(r=new Date,a.lastModified=r.getTime(),a.lastModifiedDate=r,a.name=t.name,a.name&&a.type!==t.type&&(a.name=a.name.replace(T,function(t){let e=k(t)?t.substr(6):"";return"."+(e="jpeg"===e?"jpg":e)}(a.type)))),this.result=a,o.success&&o.success.call(this,a)}fail(t){var e=this.options;if(!e.error)throw t;e.error.call(this,t)}abort(){this.aborted||(this.aborted=!0,this.reader?this.reader.abort():this.image.complete?this.fail(new Error("The compression process has been aborted.")):(this.image.onload=null,this.image.onabort()))}static noConflict(){return window.Compressor=R,x}static setDefaults(t){n(d,t)}}});