要将剪贴板中包含图片的 src 转换为 base64,可以使用以下步骤:

  1. 获取剪贴板内容:
const clipboardData = event.clipboardData || window.clipboardData;
const clipboardText = clipboardData.getData('text/html');
  1. 从剪贴板内容中提取图片的 src:
const imgSrcRegex = /<img[^>]+src='([^'>]+)'/;
const matches = clipboardText.match(imgSrcRegex);
const imgSrc = matches && matches[1];
  1. 将图片的 src 转换为 base64:
const toBase64 = url => new Promise((resolve, reject) => {
  const xhr = new XMLHttpRequest();
  xhr.onload = function() {
    const reader = new FileReader();
    reader.onloadend = function() {
      resolve(reader.result);
    }
    reader.readAsDataURL(xhr.response);
  };
  xhr.onerror = reject;
  xhr.open('GET', url);
  xhr.responseType = 'blob';
  xhr.send();
});

const imgBase64 = await toBase64(imgSrc);

完整的代码如下所示:

const toBase64 = url => new Promise((resolve, reject) => {
  const xhr = new XMLHttpRequest();
  xhr.onload = function() {
    const reader = new FileReader();
    reader.onloadend = function() {
      resolve(reader.result);
    }
    reader.readAsDataURL(xhr.response);
  };
  xhr.onerror = reject;
  xhr.open('GET', url);
  xhr.responseType = 'blob';
  xhr.send();
});

const clipboardData = event.clipboardData || window.clipboardData;
const clipboardText = clipboardData.getData('text/html');

const imgSrcRegex = /<img[^>]+src='([^'>]+)'/;
const matches = clipboardText.match(imgSrcRegex);
const imgSrc = matches && matches[1];

const imgBase64 = await toBase64(imgSrc);
console.log(imgBase64);

请注意,由于涉及到异步操作,上述代码应在异步函数中运行。

JavaScript 将剪贴板中图片的 src 转换为 base64 编码

原文地址: https://www.cveoy.top/t/topic/fSGK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录