imagehtmlcanvasgetimagedata

possible to use html images like canvas with getImageData / putImageData?


I'd like to know if there is a way to dynamically modify/access the data contained in html images just as if they were an html5 canvas element. With canvas, you can in javascript access the raw pixel data with getImageData() and putImageData(), but I have thus far been not able to figure out how to do this with images.


Solution

  •     // 1) Create a canvas, either on the page or simply in code
        var canvas = document.createElement('canvas');
        var ctx    = canvas.getContext('2d');
    
        // 2) Copy your image data into the canvas
        var myImgElement = document.getElementById('foo');
        ctx.drawImage( myImgElement, 0, 0 );
    
        // 3) Read your image data
        var w = myImgElement.width, h=myImgElement.height;
        var imgdata = ctx.getImageData(0,0,w,h);
        var rgba = imgdata.data;
        
        // 4) Read or manipulate the rgba as you wish
        for (var px=0,ct=w*h*4;px<ct;px+=4){
          var r = rgba[px  ];
          var g = rgba[px+1];
          var b = rgba[px+2];
          var a = rgba[px+3];
        }
    
        // 5) Update the context with newly-modified data
        ctx.putImageData(imgdata,0,0);
    
        // 6) Draw the image data elsewhere, if you wish
        someOtherContext.drawImage( ctx.canvas, 0, 0 );
    

    Note that step 2 can also be brought in from an image loaded directly into script, not on the page:

        // 2b) Load an image from which to get data
        var img = new Image;
        img.onload = function(){
          ctx.drawImage( img, 0, 0 );
          // ...and then steps 3 and on
        };
        img.src = "/images/foo.png"; // set this *after* onload