read-png
Version:
Universal PNG File Reader. Uses read-pixels in the Browser and pngjs in NodeJS
1 lines • 1.65 kB
JavaScript
const getImage=e=>new Promise((t=>{const o=document.createElement("img");o.onload=()=>t(o),o.src=e})),readPixels=async({data:e,debug:t=!1})=>{let o,a,n;t&&console.log("[read-pixels] starting to read with",{data:e,debug:t}),e instanceof Promise&&(e=await e),"object"==typeof e&&"function"==typeof e.arrayBuffer?e=await e.arrayBuffer():"object"==typeof e&&e.buffer instanceof ArrayBuffer&&(e=e.buffer),e instanceof ArrayBuffer?"undefined"!=typeof Blob&&(o=new Blob([e],{type:"image/png"}),a=n=URL.createObjectURL(o)):"string"==typeof e&&e.startsWith("data:")&&(a=e);const d=await getImage(a);console.log("[read-pixels] img:",d);const{height:i,width:r}=d,s=document.createElement("canvas");s.height=i,s.width=r;const l=s.getContext("2d");l.drawImage(d,0,0,r,i);const f=l.getImageData(0,0,r,i);t&&console.log("[read-pixels] imageData:",f);const{data:g}=f;t&&console.log("[read-pixels] pixels:",g),n&&(t&&console.log("[read-pixels] revoking temporary url:",n),URL.revokeObjectURL(n));const c={height:i,pixels:g,width:r};return t&&console.log("[read-pixels] finishing with",c),c};async function readPNG({data:e,debug:t=!1}){t&&console.log("[read-png] starting with",{data:e,debug:t});const o=await readPixels({data:e,debug:t});return t&&console.log("[read-png] finishing with",{data:e,debug:t}),o}"undefined"!=typeof window&&(window.readPixels=readPixels),"undefined"!=typeof module&&(module.exports=readPixels),"undefined"!=typeof self&&(self.readPixels=readPixels),"object"==typeof module&&"object"==typeof module.exports&&(module.exports=readPNG),"undefined"!=typeof window&&(window.readPNG=readPNG),"undefined"!=typeof self&&(self.readPNG=readPNG);