catdad-experiments / heic-decode

🤳 decode heic images to extracts the raw pixel data
35 stars 13 forks source link

load the decoded result in a browser canvas element #11

Closed jantimon closed 1 year ago

jantimon commented 1 year ago

is it possible to render the decoded result in a browser canvas element?

jantimon commented 1 year ago

Got it to work :)

I had to convert the raw image from an ArrayBuffer to a Uint8ClampedArray. The Uint8ClampedArray can be passed to the ImageData constructor.

That result can be rendered on any cancas:

const heic = require("heic-decode");
const { Buffer } = require("buffer");

const input = document.createElement("input");
input.type = "file";
document.body.appendChild(input);
input.addEventListener("change", function () {
  const file = input.files[0];
  const reader = new FileReader();
  reader.readAsArrayBuffer(file);
  reader.onload = async function (result) {
    const decodedImage = await heic.decode({ buffer: Buffer.from(reader.result) });
    const canvas = document.createElement("canvas");
    document.body.appendChild(canvas);
    const ctx = canvas.getContext("2d");
    const imageData = new ImageData(
      new Uint8ClampedArray(decodedImage.data),
      decodedImage.width,
      decodedImage.height
    );
    ctx.putImageData(imageData, 0, 0);
  };
});

Here is a live example:
https://codesandbox.io/s/heic-decoding-example-r4ltlb?file=/src/index.js