当来自 Mozilla Firefox 和 MS Edge 上的剪贴板时,Alpha 变为黑色

Le_*_*___ 5 javascript clipboard firefox cross-browser microsoft-edge

我正在使用此处的代码将剪贴板中的图像粘贴到页面上。它适用于所有浏览器(Chrome、Firefox、Edge 和 Opera)。

问题是:当图像是带有 alpha 通道(透明区域)的 PNG 或 GIF 时,alpha 在 Firefox 和 Edge 中变为黑色。

这是代码片段(如果您愿意,也可以使用 jsfiddle):

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);
  }
}
Run Code Online (Sandbox Code Playgroud)
body {
background-color: skyblue;
}
Run Code Online (Sandbox Code Playgroud)
<textarea id="pasteArea" placeholder="Paste Image Here"></textarea><br>
<img id="pastedImage">
Run Code Online (Sandbox Code Playgroud)

这是我在下一个演示中使用的源图像:

源图片

这是在 Chrome/Opera 中发生的事情(良好的输出):

转运箭转运

这是 Firefox/Edge 中发生的情况(错误输出):

转运箭在此处输入图片说明

我也在 Adob​​e Illustrator 和 Corel Draw 等其他软件中看到这种不良行为(粘贴时为黑色 alpha),您需要“打开”或“放置/导入”文件而不是“粘贴”以避免黑色 alpha。

系统信息:Windows 10(周年更新)32位;Chrome 58.0.3029.81、Opera 44.0、Firefox 53.0、Microsoft Edge 38.14393.0.0

我的问题是:如何避免在 Mozilla Firefox/MS Edge上粘贴到网页中的图像上出现黑色 alpha ?

Bol*_*ock 1

您将无法自行解决此问题。用户避免这种情况的唯一方法是上传或下载图像,而不是使用剪贴板导入或导出图像。