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
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.
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
//
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With