如何使用JavaScript/HTML5获取2D图像矩阵

How to get image matrix 2D using JavaScript / HTML5

本文关键字:2D 图像 获取 HTML5 何使用 JavaScript      更新时间:2023-09-26

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

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

正如其他人所指出的,您可以使用画布元素来实现这一点。我会发布一个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);

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

不幸的是,由于难以解释的原因,Javascript代码不允许读取图像的像素,除非图像来自下载Javascript的同一服务器。

即使图像是公开的,并且整个互联网都可以在不提供凭据的情况下下载。。。全世界都可以,但出于安全原因,您的页面不能(!)。绕过这个限制的一个技巧是编写一个服务器端部分,代表您获得图像。

如果图像是允许您读取的,那么您可以创建一个画布,在上面绘制图像,然后读取像素。

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
//