美文网首页
图片转换 (File、Blob、base64)

图片转换 (File、Blob、base64)

作者: 码农界四爷__King | 来源:发表于2024-08-26 11:27 被阅读0次
    https://blog.csdn.net/weixin_53791978/article/details/131152857
    

    BLOB 与 File

    【1】BLOB 转 File
    const file = new File([blob], fileName, { type: fileType, lastModified: Date.now() });
    
    【2】File 转 BLOB
    const blob = URL.createObjectURL(file);
    

    BLOB 与 base64

    【1】BLOB(url) 转 base64
    const image = new Image();
    image.src = imgBlob;
    image.onload = () => {
      // 构建canvas节点
      const canvas = document.createElement('canvas');
      canvas.width = image.width;
      canvas.height = image.height;
      const context = canvas.getContext('2d');
      context.drawImage(image, 0, 0, image.width, image.height);
      // 转换
      const imgBase64 = canvas.toDataURL();
      console.log(imgBase64);
    };
    
    
    【2】base64 转 BLOB
    // 分割base64
    const temp = base64Data.split(','); 
    // 获取类型
    const mime = arr[0].match(/:(.*?);/)[1];
    // 解码使用 base-64 编码的字符串
    const raw = window.atob(temp[1]);
    const rawLength = raw.length;
    // base64文件数据读取
    const uInt8Array = new Uint8Array(rawLength);
    for (let i = 0; i < rawLength; i += 1) {
      uInt8Array[i] = raw.charCodeAt(i);
    }
    const blob = new Blob([uInt8Array], { type: mime });
    

    File 与 base64:

    【1】File 转 base64
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function (e) {
      // e.target.result 即为base64结果
      console.log(e.target.result);
    };
    
    【2】base64 转 File
    // 分割base64
    const arr = base64Data.split(','); 
    // 获取类型
    const mime = arr[0].match(/:(.*?);/)[1];
    // 解析base字符串
    const bstr = atob(arr[1]); 
    const n = bstr.length; 
    // base64文件数据读取
    const u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    const file =  new File([u8arr], filename, { type: mime });
    

    相关文章

      网友评论

          本文标题:图片转换 (File、Blob、base64)

          本文链接:https://www.haomeiwen.com/subject/ipzokjtx.html