Convert an image to ImageData (Uint8ClampedArray)

Viewed 11955

I have an image for example "img/Myimage.jpg" I would like to convert it to the Uint8ClampedArray format (as shown in the image). enter image description here

For what? I am using a library that after a long process converts the images to this format, but I have others images that I need to convert them on my own to this same format. how can I do it? Excuse my ignorance

var frames = animator.frames;
var res_c = document.getElementById("result");
var res_ctx = res_c.getContext('2d');
for (var x = 0; x < frames.length; x++) {
  //***frames are ImageData (Uint8ClampedArray)***
  res_ctx.putImageData(frames[x],0,0);
  console.log(frames[x])
  gif.addFrame(res_c,{copy:true,delay: 120});
}

I need convert my images in ImageData (Uint8ClampedArray) for add others frames

2 Answers

An async/await solution using the canvas draw-extract method, takes one paramter as a source string (can pass image.src if you already have an image):

/** @param {string} source */
async function imageDataFromSource (source) {
   const image = Object.assign(new Image(), { src: source });
   await new Promise(resolve => image.addEventListener('load', () => resolve()));
   const context = Object.assign(document.createElement('canvas'), {
      width: image.width,
      height: image.height
   }).getContext('2d');
   context.imageSmoothingEnabled = false;
   context.drawImage(image, 0, 0);
   return context.getImageData(0, 0, image.width, image.height);
}

Example:

// image source
const source = 'https://raw.githubusercontent.com/Rovoska/undertale/master/sprites/images/spr_maincharad_3.png';

// async wrapper
async epic () {
   // log data to console
   console.log(await imageDataFromSource(source));
}

// do the epic
epic();
Related