Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get image matrix 2D using JavaScript / HTML5

are there any solution of converting any image to the 2d matrix using html5/js example

picture.jpg -------be Converted to -----> matrice[W][H] of pixels
like image 493
AHméd Net Avatar asked Jan 15 '23 05:01

AHméd Net


2 Answers

As others have noted, you can do this using a canvas element. I'd post a JSFiddle except this technique only works for images hosted on the same domain as the page (unless the image is cross-origin enabled)... and JSFiddle doesn't seem to host any suitable images to use in an example. So here's the code I used to test this:

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

Read up on canvas pixel manipulation for details. You might also want to verify the canvas tag is supported on browsers you care about.

like image 154
broofa Avatar answered Jan 16 '23 20:01

broofa


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
//
like image 31
6502 Avatar answered Jan 16 '23 20:01

6502