可以通过getImageData

可以通过getImageData

本文介绍了可以通过getImageData/putImageData使用HTML图片(例如canvas)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种方法可以动态修改/访问html图像中包含的数据,就像它们是html5 canvas元素一样.使用canvas,您可以在JavaScript中使用getImageData()和putImageData()访问原始像素数据,但是到目前为止,我仍然无法弄清楚如何对图像进行处理.

I'd like to know if there is a way to dynamically modify/access the data contained in html images just as if they were an html5 canvas element. With canvas, you can in javascript access the raw pixel data with getImageData() and putImageData(), but I have thus far been not able to figure out how to do this with images.

推荐答案

// 1) Create a canvas, either on the page or simply in code
var canvas = document.createElement('canvas');
var ctx    = canvas.getContext('2d');

// 2) Copy your image data into the canvas
var myImgElement = document.getElementById('foo');
ctx.drawImage( myImgElement, 0, 0 );

// 3) Read your image data
var w = myImgElement.width, h=myImgElement.height;
var imgdata = ctx.getImageData(0,0,w,h);
var rgba = imgdata.data;

// 4) Read or manipulate the rgba as you wish
for (var px=0,ct=w*h*4;px<ct;px+=4){
  var r = rgba[px  ];
  var g = rgba[px+1];
  var b = rgba[px+2];
  var a = rgba[px+3];
}

// 5) Update the context with newly-modified data
ctx.putImageData(imgdata,0,0);

// 6) Draw the image data elsewhere, if you wish
someOtherContext.drawImage( ctx.canvas, 0, 0 );

请注意,也可以从直接加载到脚本中而不是页面上的图像中引入第2步:

Note that step 2 can also be brought in from an image loaded directly into script, not on the page:

// 2b) Load an image from which to get data
var img = new Image;
img.onload = function(){
  ctx.drawImage( img, 0, 0 );
  // ...and then steps 3 and on
};
img.src = "/images/foo.png"; // set this *after* onload

这篇关于可以通过getImageData/putImageData使用HTML图片(例如canvas)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 21:30