Image base64, file, blob format mutual conversion, and gif to base64

Image base64, file, blob format mutual conversion, and gif to base64 (sixth point)

1. new Image() image link to base64

  • It can only be converted into ordinary jpg/png images. Can't convert gif
  • type can be converted to base64 and blob
  • quality Image quality (image/jpeg or image/webp takes effect)
const imgToBase64 = ({
    
    
  url='',type='base64',quality=1,success=null,imgType='image/jpeg'
}) => {
    
    
     const resultFn=(myCanvas,cb)=>{
    
    
       if(type=='base64'){
    
    
          const dataURL = myCanvas.toDataURL(imgType,quality);
        	success && success(dataURL);
          cb && cb(true)
      }else{
    
    
          myCanvas.toBlob((blobData)=>{
    
    
          success && success(blobData)
        },imgType,quality);
         cb && cb(true)
      }
     }
     let canvas = document.createElement('canvas'),canvas2=null,canvas3=null
     ctx = canvas.getContext('2d'),
     img = new Image();
     img.crossOrigin = 'Anonymous';//设置跨域
     img.onload = function () {
    
    
      if(imgType=='image/jpeg' || imgType=='image/webp'){
    
    
        canvas.height = img.height;
     	  canvas.width = img.width;
        ctx.drawImage(img, 0, 0);
        resultFn(canvas,()=>{
    
    
          canvas=null
        })
      }else{
    
    
        canvas.height = img.height*quality;
     	  canvas.width = img.width*quality;
        ctx.drawImage(img, 0, 0,canvas.width,canvas.height);
        resultFn(canvas,()=>{
    
    
          canvas=null
        })
      }
     };
     img.src = url;
}

//使用:
imgToBase64({
    
    
    url:'https://n.sinaimg.cn/tech/transform/774/w320h454/20190312/Jw5G-hufnxfm3452998.gif',
    type:'bolb',
    quality:1,
    success:(res)=>{
    
    
        console.log(res)
    }
})

2. Convert blob data to files

  • blob object
const blobToFolder = (blob,cb)=>{
    
    
  const newImg = new Image();
  const url = URL.createObjectURL(blob);
  newImg.onload = function() {
    
    
    cb && cb(url)
    URL.revokeObjectURL(url);
  };
  newImg.src = url;
}

3. Convert blob data to file

  • blob object
  • name file name
const blobToFile = (blob,name,cb)=>{
    
    
  cb && cb(new File([blob],name,{
    
    type:blob.type}));
}

4. Convert base64 converted data into blob

  • urlData: base64 data
const base64UrlToBlob=(urlData) => {
    
    
      var arr = urlData.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
    
    
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], {
    
     type: mime });
}

5. Convert blob and file data to base64

  • urlData: base64 or file format data
const blobFileToBase64Url=(blobFileData,cb)=>{
    
    
  const fileReader = new FileReader();
    fileReader.onload = (e) => {
    
    
      cb && cb(e.target.result)
    };
    // readAsDataURL
    fileReader.readAsDataURL(blobFileData);
    fileReader.onerror = () => {
    
    
      new Error('blobFileToBase64Url error');
    };
}

6. Use fetch to convert the image link to blob or base64

  • Advantages: asynchronous interactive processing, can realize git to base64
  • Restrictions: images may have cross-domain request issues
const fetchToBlodBase64=(url,cb,type='base64')=>{
    
    
  fetch(url)
    .then(respone => respone.blob())    // 将响应体转换成blob格式数据
    .then(blob => {
    
    
        if(type=='base64'){
    
    
          let reader = new FileReader(); 
          reader.onloadend = function(e){
    
    
            cb && cb(e.target.result)
          };
          reader.readAsDataURL(blob);
        }else{
    
    
          cb && cb(blob)
        }
    })
    .catch(console.error);
}

summary method

//file图片压缩并返回file文件
const compressionImg=(file,quality,cb)=>{
    
    
  blobFileToBase64Url(file,base64=>{
    
    //转base64
    imgToBase64({
    
    //转bolb,并压缩
        url:base64,
        type:'bolb',
        quality:quality,
        success:(bolb)=>{
    
    
            blobToFile(bolb,'img',(changeFile)=>{
    
    //转file
              console.log(changeFile)
            })
        }
    })
  })
}
// 普通url链接图片压缩并下载
//  下载图片
const downloadFile=(content,fileName='')=>{
    
    
      let aLink = document.createElement('a')
      aLink.download = fileName;
      aLink.setAttribute('href',content)
      aLink.click() 
}
// 压缩并下载
const compressionDownloadImg=(url,quality)=>{
    
    
  imgToBase64({
    
    
    url:url,
    type:'bolb',
    quality:quality,
    success:(bolbData)=>{
    
    
        blobToFolder(bolbData,folderData=>{
    
    
            downloadFile(folderData,'img.png')
        })
    }
  })
}

Others (file stream converted to excel file)


  const fileStreamToExcel = (res, name = '数据统计') => {
    
    
        if (!res) {
    
    
          alert('暂无数据')
          return false
        }
        if (res && res.status) {
    
    
          return false
        }
        const blob = new Blob([res])
        if (window.navigator.msSaveBlob) {
    
    
          // 兼容ie 鬼使用ie
          window.navigator.msSaveBlob(blob, `${
      
      name}.xls`)
        } else {
    
    
          // 主流浏览器
          const elink = document.createElement('a')
          elink.download = `${
      
      name}.xls`
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        }
      }

Guess you like

Origin blog.csdn.net/qq_40591925/article/details/127869995