I am trying to detect whether an image has transparency in it using HTML5 canvas. Here is my code, which is based on logic I have found on the internet for detecting transparent pixels using canvas (for example, this question):
//note: this happens during the onload of the element
var found = false;
if((element.src).indexOf('.png') || element.src.indexOf('.tif')) {
var c = document.createElement('canvas');
var ctx = c.getContext('2d');
ctx.drawImage(element,0,0);
var imageData = ctx.getImageData(0, 0, element.width, element.height),
data = imageData.data;
var i = data.length/4 - 1;
do {
if(data[(i*4) + 3] < 255) {
found = true;
}
} while (i-- && !found);
}
return found;
The problem is, even when I put in a PNG that does not have any transparency, it returns true. I used a counter to investigate:
console.log('total: '+i);
do {
if(data[(i*4) + 3] === 0) {
//found = true;
found++;
}
} while (i-- /*&& !found*/);
console.log('found: '+found);
//result for http://www.fnordware.com/superpng/pnggrad8rgb.png:
//total: 89999
//found: 45000
My question is, how can I reliably detect transparency in PNG and TIF files?