@limetech/lime-elements
Version:
1 lines • 2.08 kB
JavaScript
async function n(n,o){const{width:e,height:r,fit:a="cover",type:i="image/jpeg",quality:c=.85,rename:s=n=>t(n,i)}=o,l=await async function(n){var t,o;if("function"==typeof globalThis.createImageBitmap)try{return await globalThis.createImageBitmap(n,{imageOrientation:"from-image"})}catch(n){"production"!==(null===(o=null===(t=globalThis.process)||void 0===t?void 0:t.env)||void 0===o?void 0:o.NODE_ENV)&&"undefined"!=typeof console&&"function"==typeof console.debug&&console.debug("createImageBitmap failed, falling back to HTMLImageElement:",n)}return await async function(n){var t;const o=URL.createObjectURL(n);try{const n=new Image;return n.decoding="sync",n.src=o,await(null===(t=n.decode)||void 0===t?void 0:t.call(n).catch((()=>{}))),n.complete||await new Promise(((t,o)=>{const e=()=>{n.removeEventListener("load",r),n.removeEventListener("error",a)},r=()=>{e(),t()},a=n=>{e(),o(n)};n.addEventListener("load",r),n.addEventListener("error",a)})),n}finally{URL.revokeObjectURL(o)}}(n)}(n),{sx:u,sy:d,sw:f,sh:y,dx:w,dy:g,dw:h,dh:m}=function(n,t,o,e,r){const a=n/t,i=o/e;if("cover"===r){let r,c;return a>i?(c=t,r=t*i):(r=n,c=n/i),{sx:(n-r)/2,sy:(t-c)/2,sw:r,sh:c,dx:0,dy:0,dw:o,dh:e}}let c,s;a>i?(c=o,s=o/a):(s=e,c=e*a);return{sx:0,sy:0,sw:n,sh:t,dx:(o-c)/2,dy:(e-s)/2,dw:c,dh:s}}(l.width,l.height,e,r,a),p=function(n,t){if(function(){try{return"function"==typeof globalThis.OffscreenCanvas}catch(n){return!1}}())return new globalThis.OffscreenCanvas(n,t);const o=document.createElement("canvas");return o.width=n,o.height=t,o}(e,r),v=function(n){const t=n.getContext("2d",{alpha:!0});if(!t)throw new Error("2D canvas context not available");return t}(p);v.clearRect(0,0,e,r),v.drawImage(l,u,d,f,y,w,g,h,m);const b=await function(n,t,o){return"convertToBlob"in n?n.convertToBlob({type:t,quality:o}):new Promise(((e,r)=>{n.toBlob((n=>{n?e(n):r(new Error("Failed to create blob from canvas"))}),t,o)}))}(p,i,c),x=s(n.name);return new File([b],x,{type:i})}function t(n,t){const o="image/png"===t?"png":"jpg",e=n.lastIndexOf(".");return`${e>0?n.slice(0,e):n}.${o}`}export{n as r}