React - 如何将图像复制到剪贴板?

4
我正在开发一个React Web应用程序,其中一项功能需要实现的是在单击图像时复制它,以便用户可以将其粘贴到paint、word等软件中。
我尝试了几种方法,首先遵循这篇文章中详细说明的指令:https://dev59.com/oVwX5IYBdhLWcg3w-DbJ#40547470
以下是我想出来的代码(containerId 是指包含一个图像元素作为其第一个子元素的 div 元素):
copyImg = (containerId) => {
const imgContainerElement = document.getElementById(containerId);
this.selectText(imgContainerElement.children[0]);
document.execCommand('copy');
window.getSelection().removeAllRanges();
alert('image copied!');
}

selectText = (element) => {
    var doc = document;
    if (doc.body.createTextRange) {
      var range = document.body.createTextRange();
      range.moveToElementText(element);
      range.select();
    } else if (window.getSelection) {
      var selection = window.getSelection();
      var range = document.createRange();
      range.selectNodeContents(element);
      selection.removeAllRanges();
      selection.addRange(range);
    }
  }

没有起作用。我尝试实现这里标记为2颗星的解决方案:https://www.tek-tips.com/viewthread.cfm?qid=833917

  function copyImg(imgId){
  var r = document.body.createControlRange();
  r.add(document.getElementById(imgId));
  r.select();
  r.execCommand("COPY");
}

但是createControlRange()未定义。

我尝试使用navigator.clipboard API,但它只适用于png,而该应用程序需要使用jpg。

我寻找了一个可以实现这一点的npm库,但我找到的都是用于复制文本的npm,例如:react-copy-to-clipboard

任何帮助将不胜感激。

编辑1:

按照dw_ https://dev59.com/N7fna4cB1Zd3GeqP0-fA#59183698的说明,这是我想出的解决方法: (注:我必须npm安装babel-polyfill并在App.js中导入它,以使异步函数工作并通过此错误:regeneratorRuntime未定义)

    copyImg = async (imgElementId) => {
    const imgElement = document.getElementById(imgElementId);
    const src = imgElement.src;
    const img = await fetch(src);
    const imgBlob = await img.blob();
    if (src.endsWith(".jpg") || src.endsWith(".jpeg")) {
      copyService.convertToPng(imgBlob);
    } else if (src.endsWith(".png")) {
      copyService.copyToClipboard(imgBlob);
    } else {
      console.error("Format unsupported");
    }
 }

convertToPng = (imgBlob) => {
    const imageUrl = window.URL.createObjectURL(imgBlob);
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");
    const imageEl = createImage({ src: imageUrl });
    imageEl.onload = (e) => {
        canvas.width = e.target.width;
        canvas.height = e.target.height;
        ctx.drawImage(e.target, 0, 0, e.target.width, e.target.height);
        canvas.toBlob(copyToClipboard, "image/png", 1);
    };
}

createImage = (options) => {
    options = options || {};
    const img = (Image) ? new Image() : document.createElement("img");
    if (options.src) {
        img.src = options.src;
    }
    return img;
  }

copyToClipboard = (pngBlob) => {
    try {
        navigator.clipboard.write([
            new ClipboardItem({
                [pngBlob.type]: pngBlob
            })
        ]);
        console.log("Image copied");
    } catch (error) {
        console.error(error);
    }
}

代码已经复制到了图片复制信息处,但是当将其粘贴到 Word 文档中时,它并没有显示出来。另外一个问题是我收到了控制台错误提示:
Uncaught (in promise) DOMException

copyToClipboard 更改为 copyService.copyToClipboard,并将 createImage({ src: imageUrl }); 更改为 copyService.createImage({ src: imageUrl }); - dw_
哪一行触发了 Uncaught in promise 错误? - dw_
navigator.clipboard.write - Itay Tur
这个jsfiddle链接是否对您有效? - dw_
代码相关内容的翻译:fiddle也无法工作。这行代码:navigator.clipboard.write会抛出DOMException: Document is not focused异常。此外,React示例也失败了。我认为这是因为照片来自fiddler API。 - Itay Tur
5个回答

5

根据 @Zohaib Ijaz 的答案和 将JPG图像转换为PNG使用HTML5 URL和画布文章。

如果图片是jpeg/jpg格式,它将首先使用HTML5 canvas将图像转换为png格式。

function createImage(options) {
  options = options || {};
  const img = (Image) ? new Image() : document.createElement("img");
  if (options.src) {
   img.src = options.src;
  }
  return img;
}
       
function convertToPng(imgBlob) {
  const imageUrl = window.URL.createObjectURL(imgBlob);
  const canvas = document.createElement("canvas");
  const ctx = canvas.getContext("2d");
  const imageEl = createImage({ src: imageUrl });
  imageEl.onload = (e) => {
    canvas.width = e.target.width;
    canvas.height = e.target.height;
    ctx.drawImage(e.target, 0, 0, e.target.width, e.target.height);
    canvas.toBlob(copyToClipboard, "image/png", 1);
  };      
}

async function copyImg(src) {
   const img = await fetch(src);
   const imgBlob = await img.blob();
   if (src.endsWith(".jpg") || src.endsWith(".jpeg")) {
     convertToPng(imgBlob);
   } else if (src.endsWith(".png")) {
     copyToClipboard(imgBlob);
   } else {
     console.error("Format unsupported");
   }
}

async function copyToClipboard(pngBlob) {
    try {
      await navigator.clipboard.write([
        new ClipboardItem({
            [pngBlob.type]: pngBlob
        })
      ]);
      console.log("Image copied");
    } catch (error) {
        console.error(error);
    }
}

function copyImageViaSelector(selector) {
 copyImg(document.querySelector(selector).src);
}
  <img id="image" width="100" src="https://i.imgur.com/Oq3ie1b.jpg">
  <button onclick="copyImageViaSelector('#image')">Copy image</button>

React:

import React, { useRef } from "react";

const createImage = (options) => {
  options = options || {};
  const img = document.createElement("img");
  if (options.src) {
    img.src = options.src;
  }
  return img;
};

const copyToClipboard = async (pngBlob) => {
  try {
    await navigator.clipboard.write([
      // eslint-disable-next-line no-undef
      new ClipboardItem({
        [pngBlob.type]: pngBlob
      })
    ]);
    console.log("Image copied");
  } catch (error) {
    console.error(error);
  }
};

const convertToPng = (imgBlob) => {
  const canvas = document.createElement("canvas");
  const ctx = canvas.getContext("2d");
  const imageEl = createImage({ src: window.URL.createObjectURL(imgBlob) });
  imageEl.onload = (e) => {
    canvas.width = e.target.width;
    canvas.height = e.target.height;
    ctx.drawImage(e.target, 0, 0, e.target.width, e.target.height);
    canvas.toBlob(copyToClipboard, "image/png", 1);
  };
};

const copyImg = async (src) => {
  const img = await fetch(src);
  const imgBlob = await img.blob();
  const extension = src.split(".").pop();
  const supportedToBeConverted = ["jpeg", "jpg", "gif"];
  if (supportedToBeConverted.indexOf(extension.toLowerCase())) {
    return convertToPng(imgBlob);
  } else if (extension.toLowerCase() === "png") {
    return copyToClipboard(imgBlob);
  }
  console.error("Format unsupported");
  return;
};

const Image = () => {
  const ref = useRef(null);
  return (
    <div>
      <img id="image" ref={ref} width="100" src="https://i.imgur.com/Oq3ie1b.jpg" alt="" />
      <button onClick={() => copyImg(ref.current.src)}>copy img</button>
    </div>
  );
};

export default Image;

已知限制:

  • 不适用于IE / Safari / (Pre-chromium) Edge。
  • 仅适用于位于相同域或具有宽松CORS设置的服务器上的图像。

我编辑了问题,但仍然无法工作。可能是因为你提到的同一域名。虽然听起来很奇怪:图片已经在客户端浏览器中,CORS 与此有何关系? - Itay Tur
CORS可能会成为一个问题,因为我们通过ajax再次下载图像(如果它已经加载到页面上,它将从缓存中获取)。但是该错误与此无关。 - dw_
@UNlessofficialchannel更新了原始函数并添加了一个React示例。(在copyToClipboard函数中缺少了async/await) - dw_
@YTG,这个示例在这里或类似JSFiddle的网站上不会起作用,因为iframes需要设置“clipboard-write”权限。 - dw_

2
您可以使用 navigator.clipboard.write

async function copyImg(src) {
   const img = await fetch(src);
   const imgBlob = await img.blob();
   try {
      navigator.clipboard.write([
        new ClipboardItem({
            'image/png': imgBlob, // change image type accordingly
        })
      ]);
    } catch (error) {
        console.error(error);
    }
}


你打错字了,应该是 async function - dw_
只要图像在同一域上或在禁用CORS的域上,这应该可以工作。 - dw_
网站图片是JPG格式而不是PNG。 - Itay Tur
then use image/jpg - Zohaib Ijaz
1
很遗憾,不支持写入类型为image/jpeg的文件。 - dw_

0

使用Typescript

const copyImageToClipboard = async (imageURL?: string) => {
        if (imageURL === undefined || imageURL === null) return;

        try {
            const image = await fetch(imageURL!);
            const imageBlob = await image.blob();

            await navigator.clipboard
                .write([
                    new ClipboardItem({
                        'image/png': imageBlob,
                    })
                ]);
        } catch (error) {
            console.error(error);
        }
    }

0
以上所有的答案对我来说都太复杂了,尤其是涉及到画布的那些。我认为这是一个更直接的方法。这个方法只适用于PNG图像。
首先,你使用fetch API获取图像,然后从图像创建一个blob对象。之后,你只需要使用接受blob作为参数的clipboard API即可!
export const copyImage = (imagePath) => {
  fetch(imagePath)
    .then((response) => response.blob())
    .then((blob) => {
      // Now you have the image data as a blob object

      navigator.clipboard.write([
        new ClipboardItem({
          "image/png": blob,
        }),
      ]);
    })
    .catch((error) => console.error("Error fetching image:", error));
};

0
你可以尝试这个。你需要提供一个 HTMLDivElement 给它。
通常它是指向某个 div 的引用。
<div ref={node => (this._imageRef = node)}>
 <img src=""/>
</div>

你可以在构造函数中初始化这个红色

 constructor(props) {
    super(props);

    this._imageRef = null;
  }

你需要将这个_imageRef提供给函数。

现在所有的都应该可以工作了。

export function copyImageToClipboard(element) { // element is an ref to the div here
  const selection = window.getSelection();
  const range = document.createRange();
  const img = element.firstChild ;

  // Preserve alternate text
  const altText = img.alt;
  img.setAttribute('alt', img.src);

  range.selectNodeContents(element);
  selection.removeAllRanges();
  selection.addRange(range);

  try {
    // Security exception may be thrown by some browsers.
    return document.execCommand('copy');
  } catch (ex) {
    console.warn('Copy to clipboard failed.', ex);

    return false;
  } finally {
    img.setAttribute('alt', altText);
  }
}

注意:这也适用于IE浏览器


我在这里尝试了一下,但无法将其粘贴到Slack、StackOverflow等平台上。- http://jsfiddle.net/xz14jp3f/。有什么建议吗? - Govinda Totla

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接