当前位置: 首页 > 工具软件 > b64img > 使用案例 >

img 格式相互转换 url, base64,blob, file

邴子实
2023-12-01

正常向后端传的文件就是file格式,存储到文件服务器

url -> base64  -> file

url -> blob -> file

url -> base64 -> blob -> file

 

  • url -> base64  canvas.toDataURL('image/type')
   urlToBase64 () {
      let me = this
      // 获取图片的type
      let type = src.slice(src.lastIndexOf('.') + 1, src.length)
      var canvas = document.createElement('canvas');
      var img = document.createElement('img');
      // 设置可以跨域
      img.setAttribute('crossOrigin', 'anonymous')
      img.onload = function(e) {
          canvas.width = img.width;
          canvas.height = img.height;
          var context = canvas.getContext('2d');
          context.drawImage(img, 0, 0, img.width, img.height);
          document.body.append(canvas)
          let base64 = canvas.toDataURL('image/' + type)
          return base64
      }
      img.src = src;
   }

 

  •  base64 -> blob  new Blob(blobArr, {type: contentType})
    base64ToBlob (b64Data, contentType, sliceSize) {
      contentType = contentType || '';
      sliceSize = sliceSize || 512;
      var byteCharacters = window.atob(b64Data);
      // var byteCharacters  = b64Data;
      //该atob函数将base64编码的字符串解码为一个新字符串,其中包含二进制数据每个字节的字符。
      var byteArrays = [];
      for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
          var slice = byteCharacters.slice(offset, offset + sliceSize);
          var byteNumbers = new Array(slice.length);
          //通过使用.charCodeAt字符串中每个字符的方法应用它来创建一个字节值数组。
          for (var i = 0; i < slice.length; i++) {
              byteNumbers[i] = slice.charCodeAt(i);
          }
          //将此字节值数组转换为实际类型的字节数组,方法是将其传递给Uint8Array构造函数。
          var byteArray = new Uint8Array(byteNumbers);
          byteArrays.push(byteArray);
      }
      //创建一个blob:包含此数据的URL,并将其显示给用户。
      var blob = new Blob(byteArrays, { type: contentType });
      return blob;
    }
  •  base64 -> file  new File(fileArr, filename, { type: contentType})
    //  base64 => file
    dataURLtoFile (dataurl, filename, src) {
      var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
      while(n--){
          u8arr[n] = bstr.charCodeAt(n);
      }
      let file = new File([u8arr], filename, {type:mime});
      return file 
    },
  •  url -> blob  xhr.responseType = blob
   downFile (src) {
      let me = this
      var xhr = new XMLHttpRequest();
      xhr.open('GET', src);
      xhr.responseType = 'blob';   //二进制文件
      xhr.onload = function(){
        console.log(this.response, 'response')
        var filename = src.slice(src.lastIndexOf('.') + 1, src.length)
        // var arr = src.split(','), mime = arr[0].match(/:(.*?);/)[1];
        var blob = this.response;
        return blob;
        //blob转file
        me.postImg(file, src)
        console.log('file', file)
        if(this.status === 200){
            var img = document.createElement('img');
            img.src = window.URL.createObjectURL(this.response);
            img.onload = function(){
                //图片加载完,释放一个URL资源.
              window.URL.revokeObjectURL(this.src);
            }
            document.body.appendChild(img);
        }
      }
      xhr.send();
    }

 

  • blob -> file  
  blobToFile (blob, filename, contentType) {
    let file = new File([blob], filename, {type: contentType, lastModified: Date.now()});
    return file
  }
  •  blob | file -> base64 // input接收文件的格式就是blob|file  (new FileReader()).readAsDataURL
  fileToBase64 (file) {
    let a = new FileReader()
        a.readAsDataURL(file)
        a.onload = function (e){        
          let base64 = e.target.result
          return base64 
        }
        
  }

 

 类似资料: