简体   繁体   中英

Summing all pixels on a Canvas screen?

Attempting to sum the value of all the pixels on canvas:

var imageData = ctx.getImageData(0, 0, 1280, 720);

var imgData = imageData.data;
    console.log(imgData);
    for(i=0; i<= imgData.length; i++){
        pixelSum = pixelSum + imgData[i];
    }
    alert(pixelSum);

Is this the correct approach?

The code shown will only give the sum of all components, not pixels per-SE.

You do need to change the loop criteria though, as well as declare the i :

for(var i = 0; i < imgData.length; i++){ ...

Also note that this will include the alpha-channel.

If this is for check-summing (comparing images/content against a "fingerprint") then it will be a poor choice as the chance of getting similar sum is much higher than other approaches. You could use 16-bit or 32-bit wide ranges instead of byte, or more established algorithms such as CRC-32, MD5 and SHA-1/256. It's not clear what you intend to use this for so I leave it with that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM