2 lines
2.2 KiB
JavaScript
2 lines
2.2 KiB
JavaScript
(function(){"use strict";const u=new Set(["image/jpeg","image/webp"]),l=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function g(e){if(e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71&&e[4]===13&&e[5]===10&&e[6]===26&&e[7]===10)return"image/png";if(e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255)return"image/jpeg";if(e.length>=6&&e[0]===71&&e[1]===73&&e[2]===70&&e[3]===56&&e[5]===97&&(e[4]===55||e[4]===57))return"image/gif";if(e.length>=12){const a=e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70,n=e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80;if(a&&n)return"image/webp"}return null}function m(e){const a=new Uint8Array(e);let n="";const r=32768;for(let t=0;t<a.length;t+=r)n+=String.fromCharCode.apply(null,a.subarray(t,t+r));return self.btoa(n)}function d(e,a,n){const r=Math.max(e,a);if(r<=n)return{w:e,h:a};const t=n/r;return{w:Math.max(1,Math.round(e*t)),h:Math.max(1,Math.round(a*t))}}async function h(e,a){const n=u.has(a)?"image/webp":"image/png";let r;try{r=await createImageBitmap(e)}catch{return{error:"decode_failed"}}const{w:t,h:f}=d(r.width,r.height,2048);try{const i=new OffscreenCanvas(t,f),o=i.getContext("2d",{alpha:!0});if(!o)return r.close(),{error:"decode_failed"};o.imageSmoothingQuality="high",o.drawImage(r,0,0,t,f),r.close();const c={type:n};n==="image/webp"&&(c.quality=.85);const s=await i.convertToBlob(c);if(s.size>6291456)return{error:"too_large_after_normalize"};const _=await s.arrayBuffer();return{dataUrl:`data:${n};base64,${m(_)}`,mime:n,bytes:s.size}}catch{try{r.close()}catch{}return{error:"decode_failed"}}}async function p(e){const{id:a,file:n}=e,r=n.size;let t;try{t=await n.arrayBuffer()}catch{return{id:a,ok:!1,reason:"io"}}const f=new Uint8Array(t.slice(0,12)),i=g(f);if(!i)return{id:a,ok:!1,reason:"magic_mismatch"};if(!l.has(i))return{id:a,ok:!1,reason:"invalid_mime"};if(n.type&&l.has(n.type)&&n.type,r<=6291456){const c=`data:${i};base64,${m(t)}`;return{id:a,ok:!0,dataUrl:c,mime:i,bytes:r,origBytes:r,normalized:!1}}const o=await h(n,i);return"error"in o?{id:a,ok:!1,reason:o.error}:{id:a,ok:!0,dataUrl:o.dataUrl,mime:o.mime,bytes:o.bytes,origBytes:r,normalized:!0}}typeof self<"u"&&typeof self.importScripts=="function"&&self.addEventListener("message",async e=>{const a=await p(e.data);self.postMessage(a)})})();
|