Alpha becomes black when coming from clipboard on

2019-03-31 12:26发布

问题:

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

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

Here's the code snippet (or 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">

Here's the source image I use in the next demonstration:

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

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

I also see this bad behavior (black alpha when pasted) in other softwares like Adobe Illustrator and Corel Draw, where you need to 'Open' or 'Place/Import' the file instead of 'Paste' to avoid the black alpha.

System info: Windows 10 (anniversary update) 32bits; Chrome 58.0.3029.81, Opera 44.0, Firefox 53.0, Microsoft Edge 38.14393.0.0

My question is: How can I avoid the black alpha on images pasted in webpages on Mozilla Firefox/MS Edge?

回答1:

You won't be able to work around this yourself. The only way your users can avoid this is to upload or download the images instead of using the clipboard to import or export them.