4

有没有使用 html5/js 示例将任何图像转换为二维矩阵的解决方案

picture.jpg -------be Converted to -----> matrice[W][H] of pixels
4

2 回答 2

7

正如其他人所指出的,您可以使用画布元素来执行此操作。我会发布一个 JSFiddle,但此技术仅适用于与页面托管在同一域上的图像(除非该图像启用了跨域功能)......并且 JSFiddle 似乎没有托管任何合适的图像以在示例中使用. 所以这是我用来测试的代码:

// Get a reference to the image you want the pixels of and its dimensions
var myImage = document.getElementById('theImageToWorkWith');
var w = myImage.width, h = myImage.height;

// Create a Canvas element
var canvas = document.createElement('canvas');

// Size the canvas to the element
canvas.width = w;
canvas.height = h;

// Draw image onto the canvas
var ctx = canvas.getContext('2d');
ctx.drawImage(myImage, 0, 0);

// Finally, get the image data
// ('data' is an array of RGBA pixel values for each pixel)
var data = ctx.getImageData(0, 0, w, h);

阅读画布像素操作以获取详细信息。您可能还想验证您关心的浏览器是否支持 canvas 标签。

于 2013-02-16T14:11:55.607 回答
2

Unfortunately for reasons that are difficult to explain Javascript code is not allowed to read the pixels of an image unless the image comes from the same server where the Javascript has been downloaded from.

This even if the image is public and the whole internet can download it without providing credentials... the whole world can but your page cannot for security reasons (!). One trick to circumvent this limitation is to write a server side part that will get the image on your behalf.

If the image is one that you are allowed to read then you can create a canvas, draw the image on it and then read the pixels.

var c = document.createElement("canvas");
c.width = img.width;
c.height = img.height;
var ctx = c.getContext("2d");
ctx.drawImage(img, 0, 0);
var idata = c.getImageData(0, 0, img.width, img.height);
//
// here idata.data[(y*img.width + x)*4] is the red value
// of pixel (x, y), followed by green, blue and alpha
//
于 2013-02-16T13:47:30.413 回答