从浏览器获取图像(使用粘贴)

Joh*_* w. 11 javascript clipboard clipboarddata typescript angular

通过浏览器(例如chrome)复制图片有两种方式,复制图片和复制图片地址。

当我复制图像地址并使用“粘贴图像”按钮粘贴它时,我可以获取从 Base64 浏览器复制的图像。但是当我复制图像时,我无法获取图像。有没有办法使用图像 coipar 来获取图像,如示例所示?

演示

代码

  clickPaste() {
    let self = this;
    (navigator as any).clipboard.readText().then(clipboard => self.clip = clipboard);
console.log(self.clip) // copy image adress ---> base64
  }
Run Code Online (Sandbox Code Playgroud)

复制图像地址示例 - 工作 图像

图像

示例复制图像 - 不起作用

图3

图像4

我知道复制图像和复制图像的地址是不同的事情,但是当我使用复制图像时,我无法找到如何获取图像(blob 或 base64)。

Kai*_*ido 10

您可以从粘贴 ClipboardEvent.clipboardDataDataTransfer访问它。

如果可用,它将位于.filesFileList 中:

document.onpaste = (evt) => {
  const dT = evt.clipboardData || window.clipboardData;
  const file = dT.files[ 0 ];
  console.log( file );
};
Run Code Online (Sandbox Code Playgroud)
img{ height: 100vh; }
Run Code Online (Sandbox Code Playgroud)
<div contenteditable>You can paste the image here</div>
<figure>
  <figcaption>Copy this image</figcaption>
  <img src="https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png">
</figure>
Run Code Online (Sandbox Code Playgroud)

如果您需要在此类事件之外获取它,那么您将需要使用异步Clipboard API
不幸的是,这个 API 还没有得到很好的支持(目前仅 Blink),但无论如何,这里是您如何使用这个 API 读取图像文件。

您首先需要请求/检查"clipboard-read" 权限
然后,如果请求没有被拒绝,您可以尝试通过调用 来读取剪贴板的全部内容navigator.clipboard.read()。这将返回一个DataTransferItemsList.type (从技术上讲是一个数组),您仍然需要从中选择包含您想要访问的数据的列表。
在您的情况下,您只知道它是一张图像,但图像有多种类型,因此您需要在执行此检查时确定它是哪一种。

document.getElementById('btn').onclick = async (evt) => {
  const auth = await navigator.permissions.query( { name: "clipboard-read" } );
  if( auth.state !== 'denied' ) {
    const item_list = await navigator.clipboard.read();
    let image_type; // we will feed this later
    const item = item_list.find( item => // choose the one item holding our image
      item.types.some( type => { // does this item have our type
        if( type.startsWith( 'image/' ) ) {
          image_type = type; // store which kind of image type it is
          return true;
        }
      } )
    );
    const file = item && await item.getType( image_type );
    console.log( file );
  }
};
Run Code Online (Sandbox Code Playgroud)
img{ height: 100vh; }
Run Code Online (Sandbox Code Playgroud)
<button id="btn">read clipboard content</button>
<figure>
  <figcaption>Copy this image</figcaption>
  <img src="https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png">
</figure>
Run Code Online (Sandbox Code Playgroud)