I am currently working on a task that involves loading a PNG image and checking to see if it is fully opaque, meaning the alpha channel has near 100% coverage across the entire image. To achieve this, I am using a canvas and 2D Context to extract pixel data and iterate through it to inspect the alpha values.
However, I encountered a puzzling issue where certain areas of the image have pixel values of zeros (RGBA = [0000]), which is unexpected.
Browser in focus: chrome 50.0.2661.87
Below is my code snippet embedded within a ThreeJS environment:
var imageData = zipHandler.zip.file(src); // binary image data
var texture = new THREE.Texture();
var img = new Image();
img.addEventListener( 'load', function ( event ) {
texture.imageHasTransparency = false; // extending THREEJS Texture with a flag
if (img.src.substring(imgSrc.length-4).toLowerCase().indexOf("png") > -1
|| img.src.substring(0, 15).toLowerCase().indexOf("image/png") > -1) {
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
context.drawImage(img, 0, 0, img.width, img.height );
var pixDataContainer = context.getImageData(0, 0, img.width, img.height);
var pixData = pixDataContainer.data;
// scanning for pixels with alpha < 250
for (var pix = 0, pixDataLen = pixData.length; pix < pixDataLen; pix += 4) {
if (pixData[pix+3] < 250) {
texture.imageHasTransparency = true;
break;
}
}
}
texture.image = img;
texture.needsUpdate = true;
this.removeEventListener('load', arguments.callee, false);
}, false );
var fileExtension = src.substr(src.lastIndexOf(".") + 1);
img.src = "data:image/"+fileExtension+";base64,"+ btoa(imageData.asBinary());
The sequence of operations is crucial: initializing a new Image(), defining the onload function, and setting the source afterwards.