富文本编辑器 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的部分。异步后拿到路径之后修改完善。

猜你喜欢

转载自blog.csdn.net/u013776700/article/details/125593397
今日推荐