将图像转换为ImageData(Uint8ClampedArray)

时间:2017-07-28 05:35:53

标签: javascript html5-canvas

我有一个图像例如 " IMG / Myimage.jpg" 我想将其转换为Uint8ClampedArray格式(如图所示)。 enter image description here

为了什么?我正在使用一个库,经过漫长的过程将图像转换为这种格式,但我有其他图像,我需要将它们自己转换为相同的格式。我该怎么做?请原谅我的无知

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});
}

我需要在ImageData(Uint8ClampedArray)中转换我的图像以添加其他帧

2 个答案:

答案 0 :(得分:3)

您可以使用Image构造函数,CanvasRenderingContext2D.drawImage()CanvasRenderingContext2D.getImageData()从图片文件创建ImageData对象。

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
const width = 300;
const height = 311;

const image = new Image;
image.src = /* Blob URL, "/path/to/image/served/with/cors/headers" */;
image.onload = () => {
  ctx.drawImage(image, 0, 0);
  imageData = ctx.getImageData(0, 0, 300, 311);
  console.log(imageData);
}

答案 1 :(得分:0)

使用画布绘制提取方法的异步/等待解决方案,将一个参数作为源字符串(如果您已经有图像,可以传递 image.src):

/** @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);
}

示例:

// 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();