How to get image matrix 2D using JavaScript / HTML5

后端 未结 2 436
天涯浪人
天涯浪人 2021-02-10 09:21

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
         


        
2条回答
  •  终归单人心
    2021-02-10 09:55

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

提交回复
热议问题