【问题标题】:How to get image matrix 2D using JavaScript / HTML5如何使用 JavaScript / HTML5 获取图像矩阵 2D
【发布时间】:2013-02-16 12:54:25
【问题描述】:

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

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

【问题讨论】:

标签: javascript html matrix image


【解决方案1】:

正如其他人所指出的,您可以使用画布元素来执行此操作。我会发布一个 JSFiddle,但此技术仅适用于与页面托管在同一域中的图像(除非图像是 cross-origin enabled)......并且 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 pixel manipulation 了解详情。 您可能还想在您关心的浏览器上验证canvas tag is supported

【讨论】:

  • 我会得到一个矩阵图片,例如:T[0][0]=255,T[0][1]=283 这些是颜色的值
  • 您必须自己从 getImageData() 返回的平面数组中构建该数据结构。另外,请注意,您的问题暗示您认为每个像素只有一个字节,但事实并非如此 - 有 4 个字节(红色、绿色、蓝色和 alpha 通道)。
【解决方案2】:

不幸的是,由于难以解释的原因,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
//

【讨论】:

  • @AHmédNet: idata.data 包含所有颜色,但它是一维数组(Javascript 没有多维数组)。每个像素(r、g、b 和 alpha)有 4 个字节,因此要访问您需要计算为索引的数组(y*width+x)*4+c 其中c 是组件(红色=0,绿色=1,蓝色=2, alpha=3)。
  • 谢谢。我现在明白了:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-19
  • 1970-01-01
相关资源
最近更新 更多