2

I am trying to read RGB from an image In canvas.

  1. I create a canvas and its context
  2. I ll read img.width and img.height & set the same dimensions to the canvas
  3. Draw the image in canvas
  4. Read the imagedata using getImageData()
  5. when I see the RGB values as Red = 0, Green = 0, Blue = 0 for all the pixels of image.

         <html>
         <head>
         <title></title>
         <script type="text/javascript">
         function myfun() {
        var img = document.getElementById('myImg');
    
        var width = img.clientWidth;
        var height = img.clientHeight;
    
    
        var _grayCanvas = document.getElementById('grayCanvas');
        var grayctx = _grayCanvas.getContext("2d");
    
        grayctx.canvas.width = width;
        grayctx.canvas.height = height;
    
    
        var grayimg = new Image();
        grayimg.src = "img.bmp";
    
    
    
        grayimg.onload = function () {
            grayctx.drawImage(grayimg, 0, 0);
        }
    
    
    
        var x = 0;
        var y = 0;
        var canvasColor = grayctx.getImageData(x, y, width, hieght);
    
        var red = canvasColor.data[0];
        var green = canvasColor.data[1];
        var blue = canvasColor.data[2];
        var alpha = canvasColor.data[3];
    
        alert(red + " : " + green + " : " + blue + " : " + alpha);
    
    
        for (var i = 0; i < canvasColor.data.length ; i += 4) {
            var red = canvasColor[i];
            var green = canvasColor[i + 1];
            var blue = canvasColor[i + 2];
            var alpha = canvasColor[i + 3];
            if(red > 0)
            alert(red + " : " + green + " : " + blue + " : " + alpha);
        }
    
    }
    

What might be the issue with respect to the above code ? Thanks in advance.

Karthik Dheeraj
  • 1,039
  • 1
  • 13
  • 25
  • see http://stackoverflow.com/questions/7373851/help-to-read-the-rgb-value-of-an-image-using-html5 – Rachel Gallen Jun 13 '14 at 11:15
  • `canvasColor.length` should be `canvasColor.data.length`. It will only be 4, since you've just asked for 1 pixel. Therefore, your for loop is nonsense too! I.e You can only index from [0..3], yet you try to index from [0..6] (i=0 + 3) up to (i=3 + 3). – enhzflep Jun 13 '14 at 11:20
  • But do you see the image on the canvas? – Jonas Grumann Jun 13 '14 at 11:44
  • Here's a code example that reads all the pixels on an image: http://www.html5canvastutorials.com/advanced/html5-canvas-get-image-data-tutorial/ – markE Jun 13 '14 at 14:04

0 Answers0