Alpha turns black when coming from clipboard in Mozilla Firefox and MS Edge

I am using the code here to paste images from the clipboard into a page. It works fine in all browsers (Chrome, Firefox, Edge and Opera).

The problem is this: when the image is a PNG or GIF with an alpha channel (transparent areas), the alpha turns black in Firefox and Edge.

Here's a code snippet ( or a jsfiddle if you prefer ):

document.getElementById('pasteArea').onpaste = function (event) {
  // use event.originalEvent.clipboard for newer chrome versions
  var items = (event.clipboardData  || event.originalEvent.clipboardData).items;
  console.log(JSON.stringify(items)); // will give you the mime types
  // find pasted image among pasted items
  var blob = null;
  for (var i = 0; i < items.length; i++) {
    if (items[i].type.indexOf("image") === 0) {
      blob = items[i].getAsFile();
    }
  }
  // load image if there is a pasted image
  if (blob !== null) {
    var reader = new FileReader();
    reader.onload = function(event) {
      console.log(event.target.result); // data url!
      document.getElementById("pastedImage").src = event.target.result;
    };
    reader.readAsDataURL(blob);
  }
}
      

body {
background-color: skyblue;
}
      

<textarea id="pasteArea" placeholder="Paste Image Here"></textarea><br>
<img id="pastedImage">
      

Run code


Here's the original image that I'm using in the next demo:

source pic

This is what happens in Chrome / Opera (good takeaway):

transsource arrow transsource

This is what happens in Firefox / Edge (bad output):

transsource arrow enter image description here

I also see this bad behavior (black alpha on pasting) in other programs like Adobe Illustrator and Corel Draw where you need to "Open" or "Place / Import" the file instead of "Paste" to avoid black alpha.

System Information: Windows 10 (Anniversary Update) 32 bit; Chrome 58.0.3029.81, Opera 44.0, Firefox 53.0, Microsoft Edge 38.14393.0.0

My question is, how can I avoid black alpha on embed images on webpages in Mozilla Firefox / MS Edge?

+3


source to share


1 answer


You cannot get around this on your own. The only way your users can avoid this is to upload or download images, rather than using the clipboard to import or export.



0


source







All Articles