-4

In plain javascript I need to check if the majority of an image is transparent.

e.g if more than 50% of the image is less than 10% visible then consider it transparent.

I need a way to filter out all these images as they're usually completely blank or just have a little logo on them.

Mattijs
  • 25
  • 5
  • 2
    That's good to know what you want/need but what have you tried so far and which part are you having issues with? What research have you done... No source code = nothing to debug/fix and this isn't a free writing service. – NewToJS Oct 22 '17 at 06:03
  • Did you check this https://stackoverflow.com/questions/41287823/check-image-transparency first result after searching "check image transparency javascripit" – Bassie Oct 22 '17 at 06:04
  • 1
    Possible duplicate of [Check image transparency](https://stackoverflow.com/questions/41287823/check-image-transparency) – Tigger Oct 22 '17 at 06:07
  • It is a bit different than the mentioned as possible duplicate, as there will be in this case a threshold to consider an image transparent. –  Oct 22 '17 at 06:36

1 Answers1

2
function opacityRatio(image) {
    const canvas = document.createElement("canvas");
    const context = canvas.getContext("2d");
    canvas.width = image.width;
    canvas.height = image.height;
    context.drawImage(image, 0, 0);
    const data = context.getImageData(0, 0, canvas.width, canvas.height).data;
    let opacity = 0;
    for (let i = 0; i < data.length; i += 4) {
        opacity += data[i + 3];
    }
    return (opacity / 255) / (data.length / 4);
}

This function will return a number from 0 to 1, being 0 a fully transparent image, 1 a fully opaque one. Note that it is using getImageData, and to work, the image needs to be hosted in the same origin/domain or to have cross-origin permissions.