How to determine if image is using transparency on Javascript?

Viewed 6131

I'd like to be able to detect if a logo type image has a transparent background or not, let's imagin that two similar images are .png files but one has a white background and another on has a transparent background, how would I be able to determine the one with transparency ?

I've tried using colorthief but it doesn't take transparency into account, so I thought doing it by myself on canvas. A first solution would be to convert the png file into jpg and if the background color of the jpg after being converted appear to be black then it's a transparent logo, but this might be a problem for users with black background and white logos. Is there a better solution than that ?

http://jsfiddle.net/9s5qf5cu/

from png to jpg :

var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);

var canvas = document.getElementById('imageCanvas');
var ctx = canvas.getContext('2d');


function handleImage(e){
    var reader = new FileReader();
    reader.onload = function(event){
        var img = new Image();
        img.onload = function(){
            canvas.width = 100;
            canvas.height = 100;
            ctx.drawImage(img,0,0, 100, 100);
            document.getElementById("image").src = canvas.toDataURL("image/jpeg");
        }
        img.src = event.target.result;

    }
    reader.readAsDataURL(e.target.files[0]);     
}
1 Answers
Related