簡體   English   中英

如何使用JavaScript / HTML5獲取2D圖像矩陣

[英]How to get image matrix 2D using JavaScript / HTML5

是否有使用html5 / js示例將任何圖像轉換為2d矩陣的解決方案

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

正如其他人指出的那樣,您可以使用canvas元素執行此操作。 我將發布一個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標記

不幸的是,由於難以解釋的原因,除非圖像來自下載Java腳本的同一服務器,否則不允許Java代碼讀取圖像的像素。

即使圖像是公開的,整個互聯網都可以在不提供憑據的情況下下載它……整個世界都可以,但是出於安全原因,您的頁面無法(!)。 克服此限制的一個技巧是編寫一個服務器端部件,它將代表您獲取映像。

如果圖像是允許讀取的圖像,則可以創建畫布,在其上繪制圖像,然后讀取像素。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM