欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > js将图片复制到粘贴板上

js将图片复制到粘贴板上

2024/10/28 8:26:57 来源:https://blog.csdn.net/m0_72678953/article/details/143256190  浏览:    关键词:js将图片复制到粘贴板上

这个方法目前受限与js的API的限制,只能针对jpg/jpeg/png进行粘贴,gif目前没有比较好的方法可以去粘贴,现将代码粘贴如下:

// 通过 Canvas,我们可以将图像绘制到画布上,然后将其转换为支持的格式(如 PNG),这样就能顺利地复制到剪贴板。
async function copyImageToClipboard(imageUrl) {  const response = await fetch(imageUrl);  const contentType = response.headers.get('Content-Type') || 'image/png';  const isSupportedImageType = contentType.startsWith('image/');  if (!isSupportedImageType) {  throw new Error('Unsupported image type');  }  const blob = await response.blob(); // 获取图像的 Blob 对象const imgElement = new Image(); // 创建 Image 对象imgElement.src = URL.createObjectURL(blob); // 将 Blob 转为 URLreturn new Promise((resolve, reject) => {imgElement.onload = async () => {const canvas = document.createElement('canvas'); // 创建 Canvasconst ctx = canvas.getContext('2d'); // 获取 Canvas 上下文if (contentType === 'image/gif') {// 处理 GIF,直接使用 GIF Blobconst item = new ClipboardItem({ 'image/gif': blob });  // 使用 GIF 格式await navigator.clipboard.write([item]); // 写入剪贴板resolve();} else {// 处理 JPG/JPEG/PNG,转换为 PNGcanvas.width = imgElement.width; // 设置宽度canvas.height = imgElement.height; // 设置高度ctx.drawImage(imgElement, 0, 0); // 将图像绘制到 Canvas// 转换为 Blob,使用 'image/png' 作为 MIME 类型canvas.toBlob(async (newBlob) => {const item = new ClipboardItem({ 'image/png': newBlob });  // 使用 PNG 格式await navigator.clipboard.write([item]); // 写入剪贴板resolve(); // Promise 成功}, 'image/png');}};imgElement.onerror = reject; // 处理错误});
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com