通过浏览器(例如chrome)复制图片有两种方式,复制图片和复制图片地址。
当我复制图像地址并使用“粘贴图像”按钮粘贴它时,我可以获取从 Base64 浏览器复制的图像。但是当我复制图像时,我无法获取图像。有没有办法使用图像 coipar 来获取图像,如示例所示?
Demo
code
clickPaste() {
let self = this;
(navigator as any).clipboard.readText().then(clipboard => self.clip = clipboard);
console.log(self.clip) // copy image adress ---> base64
}
Example copy image address - working
示例复制图像 - 不起作用
我知道复制图像和复制图像的地址是不同的事情,但是当我使用复制图像时,我无法找到如何获取图像(blob 或 base64)。
您可以从paste 剪贴板事件's .clipboardData数据传输.
它将在.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>
如果您需要在此类事件之外获取它,那么您将需要使用异步剪贴板API.
不幸的是,这个 API 还没有得到很好的支持(目前仅 Blink),但无论如何,这里是您如何使用这个 API 读取图像文件。
您首先需要请求/检查"clipboard-read"
允许.
然后,如果请求没有被拒绝,您可以尝试通过调用读取剪贴板的全部内容navigator.clipboard.read()
。这将返回一个数据传输项列表(从技术上讲是一个数组),您仍然需要从中选择保存.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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)