How to get image matrix 2D using JavaScript / HTML5

后端 未结 2 442
天涯浪人
天涯浪人 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:52

    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.

提交回复
热议问题