Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alpha becomes black when coming from clipboard on Mozilla Firefox and MS Edge

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:

source pic

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

transsourcearrowtranssource

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

transsourcearrowenter image description here

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?

like image 396
Le____ Avatar asked Nov 19 '22 22:11

Le____


1 Answers

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.

like image 92
BoltClock Avatar answered Dec 04 '22 13:12

BoltClock