通过浏览器(例如chrome)复制图片有两种方式,复制图片和复制图片的地址。
当我复制图像地址并使用我的粘贴图像按钮粘贴它时,我可以从 base64 浏览器中复制图像。但是当我复制图像时,我无法获取图像。有没有办法使用图像 coipar 获取图像,如示例中所示?
Demo
代码
clickPaste() {
let self = this;
(navigator as any).clipboard.readText().then(clipboard => self.clip = clipboard);
console.log(self.clip) // copy image adress ---> base64
}
示例复制图像地址 - 工作
示例复制图像 - 不起作用
我知道复制图像和复制图像的地址是不同的事情,但是当我使用复制图像时,我不知道如何获取图像(blob 或 base64)。
最佳答案
您可以通过粘贴 ClipboardEvent 访问它的 .clipboardData
DataTransfer .
它将在 .files
文件列表(如果可用):
document.onpaste = (evt) => {
const dT = evt.clipboardData || window.clipboardData;
const file = dT.files[ 0 ];
console.log( file );
};
img{ height: 100vh; }
<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>
如果您需要在此类事件之外获取它,那么您将需要使用异步 Clipboard API .
不幸的是,这个 API 还没有得到很好的支持(目前只支持 Blink),但无论如何,这里是你如何使用这个 API 读取图像文件的方法。
您首先需要请求/检查
"clipboard-read"
Permission .然后如果请求没有被拒绝,你可以尝试通过调用
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 );
}
};
img{ height: 100vh; }
<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>
关于javascript - 从浏览器获取图像(使用粘贴),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60503912/