Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if image is using transparency on Javascript?

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]);     
}
like image 979
Hiroyuki Nuri Avatar asked Dec 14 '22 22:12

Hiroyuki Nuri


1 Answers

Use this function by passing your context and your canvas. Then it will loop over the alpha channel until it finds an entry that is not completely opaque.

function hasAlpha (context, canvas) {
    var data = context.getImageData(0, 0, canvas.width, canvas.height).data,
        hasAlphaPixels = false;
    for (var i = 3, n = data.length; i < n; i+=4) {
        if (data[i] < 255) {
            hasAlphaPixels = true;
            break;
        }
   }
   return hasAlphaPixels;
}

Note: this will not work if your canvas is tainted.

like image 98
Zomry Avatar answered Dec 21 '22 09:12

Zomry