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]);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With