3

Is it possible to use ImageData array object to get an Image() object. My eventual goal is to use drawImage instead of putImageData since putImageData is too slow (from stackoverflow similar qs and my own tests). All I have is ImageData array that I want to draw on top of an existing image on a canvas .

Yves M.
  • 29,855
  • 23
  • 108
  • 144
Captain Jack sparrow
  • 959
  • 1
  • 13
  • 28

1 Answers1

7

You can create an ImageBitmap from an ImageData and pass that to drawImage(). https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/createImageBitmap

Something like:

const imgdata = ...;
const ctx = ...;

createImageBitmap(imgdata).then(function(imgBitmap) {
    ctx.drawImage(imgBitmap, ...remaining args);
});

I was able to do this to scale some ImageData I had, since putImageData does not have arguments for scaling. Unfortunately, it looks like IE, Edge, and Safari do not support createImageBitmap().

It's worth mentioning that for my case (resizing the ImageData), createImageBitmap() does have extra options for resizing the resulting ImageBitmap on its own.

wolf1oo
  • 177
  • 1
  • 5
  • You can use one of: `function createImageBitmap(image: ImageBitmapSource): Promise;`, `function createImageBitmap(image: ImageBitmapSource, sx: number, sy: number, sw: number, sh: number): Promise;` – kinjelom Jun 05 '19 at 11:26
  • does createImageBitmap() copy pixel data or just make a reference? – Jiang YD Oct 23 '19 at 04:33
  • I think generally anything that's an ImageBitmapSource is immutable, so it's probably taking a reference? – wolf1oo Oct 23 '19 at 14:11
  • 1
    but is it faster than putImageData? @wolf1oo – Pants Jun 22 '20 at 13:56
  • This is not supported in neither the latest Safari nor older Edge, so you will need to polyfill it to support those browsers. Google "safari createImageBitmap polyfill" – kozan Apr 22 '21 at 15:48