Get pixels of a bitmap with javascript

10,267

You don't have (or aren't using) a <canvas> element. Your HTML should look something like this:

<img id="barcode" src="whatever.bmp">
<canvas id="mycanvas">
    <div id="fallback">
        You only see this message if your browser doesn't support canvas.
    </div>
<canvas>

And your function should be prefixed with:

var context = document.getElementById('mycanvas').getContext('2d');

That should make your code function properly. You need to get the drawing context of a <canvas> element first, then add the image to that context, and finally retrieve pixel data from the context.

To directly address your comment above, the line

var context = document.getElementById('barcode').getContext('2d');

tries to get the context of an image element, but that is not possible. You can only call getContext on a canvas element.

Share:
10,267
Umut Kaya İlkiz
Author by

Umut Kaya İlkiz

Updated on June 05, 2022

Comments

  • Umut Kaya İlkiz
    Umut Kaya İlkiz about 2 years

    I am trying to write a greasemonkey javascript code for specifically my own page. In the page, there is an img with id "barcode".

    I can use

    var imageattributes = document.getElementById('barcode');
    

    and get the image from the page. What I want is that I want to be able to get all the pixels in this image in an array.

    I have been going around in stackoverflow, and saw some ways to do this. I also saw pixastic. My problem with the solutions in stackoverflow is that

    var imgData = context.getImageData(0, 0, canvas.height, canvas.width);
    

    does not work. No matter what I do. And pixastic does not show how I can view the pixel information anywhere. Their documentation only covers the functions they already have for inversion, blur, etc.

    The code I currently have is this:

    var imageattributes = document.getElementById('barcode').attributes;
    var imageurl = imageattributes.getNamedItem("src").value;
    var imageurl2 = imageurl.replace("..","http://localhost");
    
    var img = new Image();
    img.src = imageurl2;
    context.drawImage(img, 0, 0);
    var imgData = context.getImageData(0, 0, canvas.height, canvas.width);
    var pixel = new Array();
    for(i=0;i<canvas.height;i++){
        pixel[i] = new Array();
        for(j=0;j<canvas.width;j++){
            pixel[i][j] = imgData.data[i*canvas.width+j*4];
        }
    }
    document.getElementById('derp').innerHTML = imageurl;
    

    Which is supposed to get the image, take it's src, load it as a new image, and put the pixels inside an array. And the last line is just to show on the screen if the code has worked or not, so if the url prints, it means it worked, if it doesn't, it doesn't.

    Can anyone please help me with this? Thank you.