富文本编辑器 word整体粘贴实现图片自动展示(二)

富文本编辑器 word整体粘贴实现图片自动展示(二)

上回我们已经讲到实现整体粘贴图片展示的核心部分就是getData(‘text/tff’)去获取粘贴板clipboardData富文本内容,那么怎么实现展示图片呢,接下来我们我们就来实现。

从rtf中提取图片信息

// rtf中提取图片信息
function extractImageDataFromRtf(rtfData) {
  if (!rtfData) {
    return [];
  }
  const regexPictureHeader = /{\\pict[\s\S]+?({\\\*\\blipuid\s?[\da-fA-F]+)[\s}]*/
  const regexPicture = new RegExp('(?:(' + regexPictureHeader.source + '))([\\da-fA-F\\s]+)\\}', 'g');
  const images = rtfData.match(regexPicture);
  const result = [];

  if (images) {
    for (const image of images) {
      let imageType = false;

      if (image.includes('\\pngblip')) {
        imageType = 'image/png';
      } else if (image.includes('\\jpegblip')) {
        imageType = 'image/jpeg';
      }

      if (imageType) {
        result.push({
          hex: image.replace(regexPictureHeader, '').replace(/[^\da-fA-F]/g, ''),
          type: imageType
        });
      }
    }
  }
  return result;
}

利用正则从rtf内容中提取到图片的核心信息,得到数组。其中数组中保存的信息有
{
type: ‘’, //图片类型
hex: ‘’ // hex字符串
}

将hex字符串转化为base64图片信息

// 讲hex格式转化为base64
function convertHexToBase64(hexString) {
  return btoa(hexString.match(/\w{2}/g).map(char => {
    return String.fromCharCode(parseInt(char, 16));
  }).join(''));
}

到这里核心的方法提取rtf内容到图片信息就处理完了。
详细代码:

console.log('批量粘贴');
 // const pastDom = evt.clipboardData.getData('text/html');
 const rtf = evt.clipboardData.getData('text/rtf');
 const hexStrings = extractImageDataFromRtf(rtf);
 // 获取base64图片数据
 const base64Images = hexStrings.map((hexObj) => {
     return convertHexToBase64(hexObj.hex);
 })
 // 粘贴后处理粘贴内容
 setTimeout(() => {
   const editorDom = this.$refs.myQuillEditor.quill.root;
   const editorImgs = 		   editorDom.querySelectorAll('img[src*="0196fa582abab6a84a0d304f899eaf.gif"]');
   editorImgs.forEach((item, index) => {
     item.src = `data:${hexStrings[index].type};base64,${base64Images[index]}`;
   })
 }, 200)

利用查找quillEditor编辑器中loading图片,然后遍历替换为base64图片格式。
根据上述方法,大家可以自行根据实际情况在不同编辑器下修改代码,进一步完善上传到云存储也可调整替换图片的src的部分。异步后拿到路径之后修改完善。

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xiaolongyu3

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值