/* COPYRIGHT Esri - https://js.arcgis.com/5.0.18/LICENSE.txt */
import t from"../../../core/Error.js";import{isAborted as e,createAbortError as a}from"../../../core/promiseUtils.js";import{Z as n}from"../../../chunks/Zlib.js";class i{constructor(t){this._canvas=null,this._ctx=null,t&&(this._canvas=t.canvas,this._ctx=t.ctx||t.canvas&&t.canvas.getContext("2d"))}decode(n,s,r){if(!n||n.byteLength<10)throw new t("imagecanvasdecoder: decode","required a valid encoded data as input.");let{width:c=0,height:h=0,format:o}=s;const{applyJpegMask:l}=s;if(l&&(!c||!h))throw new t("imagecanvasdecoder: decode","image width and height are needed to apply jpeg mask directly to canvas");return new Promise((t,d)=>{let g=null;"jpg"===o&&l&&(g=i._getMask(n,{width:c,height:h}));const w=new Blob([new Uint8Array(n)],{type:"image/"+o=="jpg"?"jpeg":o}),v=URL.createObjectURL(w),m=new Image;m.src=v,m.onload=()=>{if(URL.revokeObjectURL(v),e(r))return void d(a());c=m.width,h=m.height,this._canvas&&this._ctx?(this._canvas.width===c&&this._canvas.height===h||(this._canvas.width=c,this._canvas.height=h),this._ctx.clearRect(0,0,c,h)):(this._canvas=document.createElement("canvas"),this._canvas.width=c,this._canvas.height=h,this._ctx=this._canvas.getContext("2d")),this._ctx.drawImage(m,0,0);const n=this._ctx.getImageData(0,0,c,h),i=n.data;if(s.renderOnCanvas){if(g)for(let t=0;t<g.length;t++)g[t]?i[4*t+3]=255:i[4*t+3]=0;return this._ctx.putImageData(n,0,0),void t(null)}const o=c*h,l=new Uint8Array(o),w=new Uint8Array(o),_=new Uint8Array(o);if(g)for(let t=0;t<o;t++)l[t]=i[4*t],w[t]=i[4*t+1],_[t]=i[4*t+2];else{g=new Uint8Array(o);for(let t=0;t<o;t++)l[t]=i[4*t],w[t]=i[4*t+1],_[t]=i[4*t+2],g[t]=i[4*t+3]}t({width:c,height:h,pixels:[l,w,_],mask:g,pixelType:"u8"})},m.onerror=()=>{URL.revokeObjectURL(v),d("cannot load image")}})}static _getMask(t,e){let a=null;try{const i=new Uint8Array(t),s=Math.ceil(i.length/2);let r=0;const c=i.length-2;for(r=s;r<c&&(255!==i[r]||217!==i[r+1]);r++);if(r+=2,r<i.length-1){const t=new n(i.subarray(r)).getBytes();a=new Uint8Array(e.width*e.height);let s=0;for(let e=0;e<t.length;e++)for(let n=7;n>=0;n--)a[s++]=t[e]>>n&1}}catch(i){}return a}}export{i as default};
