js各种数据流之间的格式转换(blob、ArrayBuffer、DataURL、file,canvas)

总结一下常用的转换类型

一.将file转换成DataURL

方法1:利用URL.createObjectURL();

window.onload = function () {
            let img = document.getElementById('img');
            let file = document.getElementById('file');
            file.onchange = function(e) {
                let imgFile = e.target.files[0];
                let fileUrl = window.URL.createObjectURL(imgFile);
                img.src = fileUrl;
                img.onload = function() {
                    URL.revokeObjectURL(fileUrl);
                }
                console.log(fileUrl)
                // blob:http://127.0.0.1:5500/f8576dd2-6bae-4d74-a8a2-7d7c3a913d75
            }
        }

方法2:利用FileReader.readAsDataURL();

 window.onload = function () {
            let img = document.getElementById('img');
            let file = document.getElementById('file');
            file.onchange = function(e) {
                let imgFile = e.target.files[0];
                let fileReader = new FileReader();
                fileReader.readAsDataURL(imgFile);
                fileReader.onload = function () {
                    console.log(this.result);
                    // data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAACWEAAAOuCAMAAABbw7foAAABg...
                    img.src = this.result;
                }
            }
        }

二.将canvas转成DataURL

利用canvas.toDataURL();

 function canvasToDataURL(url) {
                let img = new Image();
                img.crossOrigin = "Anonymous";
                img.onload = function() {
                    let canvas = document.createElement("canvas");
                    let ctx = canvas.getContext("2d");
                    ctx.drawImage(img, 0, 0, img.width, img.height);
                    let dataURL = canvas.toDataURL('image/png', 1);
                    return dataURL;
                }
                img.src = url;
            }

三.将DataURL转成blob

 function dataURLToBlob(dataurl) {
                console.log('datarul', dataurl)
                let arr = dataurl.split(','),
                    mime = arr[0].match(/:(.*?);/)[1],
                    bstr = atob(arr[1]),
                    n = bstr.length,
                    u8arr = new Uint8Array(n)
                while (n--) {
                    console.log(bstr.charCodeAt(n));
                    u8arr[n] = bstr.charCodeAt(n)
                }
                return new Blob([u8arr], { type: mime })
            }
            console.log(dataURLToBlob('data:text/plain;base64,YWFhYWFhYQ=='));
            //Blob {size: 7, type: "text/plain"}

四.将DataURL转成file

 function dataURLToFile(dataurl, filename) {
                console.log('datarul', dataurl)
                let arr = dataurl.split(','),
                    mime = arr[0].match(/:(.*?);/)[1],
                    bstr = atob(arr[1]),
                    n = bstr.length,
                    u8arr = new Uint8Array(n)
                while (n--) {
                    console.log(bstr.charCodeAt(n));
                    u8arr[n] = bstr.charCodeAt(n)
                }
                return new File([u8arr], filename, { type: mime })
            }
            console.log(dataURLToFile('data:text/plain;base64,YWFhYWFhYQ==','测试文件'));
            //File {name: "测试文件", lastModified: 1618298078051, lastModifiedDate: Tue Apr 13 2021 15:14:38 GMT+0800 (中国标准时间), webkitRelativePath: "", size: 7, …}

五.将DataURL转成canvas

直接将DataURL指向img

六.将canvas/DataURL转成blob

利用canvas.toBlob()

  function canvasToBlob(dataurl) {
                let img = new Image();
                img.crossOrigin = 'Anonymous';
                img.src = bannerImg.src;
                img.onload = function () {
                    let canvas = document.createElement('canvas');
                    let ctx = canvas.getContext('2d');
                    ctx.drawImage(img, 0, 0, bannerImg.width, bannerImg.height);
                    canvas.toBlob((result) => {
                        console.log(result)
                        //Blob {size: 36004, type: "image/png"}
                    })
                }
                img.src = '';//url或dataURL
            }

七.将blob转成file

利用new File();

 function blobToFile(blob, filename) {
               return new File([blob], filename, { type: blob.type })
            }
            console.log(blobToFile(dataURLToBlob('data:text/plain;base64,YWFhYWFhYQ==','测试文件'), '测试文件'));
            //File {name: "测试文件", lastModified: 1618298840585, lastModifiedDate: Tue Apr 13 2021 15:27:20 GMT+0800 (中国标准时间), webkitRelativePath: "", size: 7, …}

八.将canvas转成file

先将canvas转成dataURL,然后将dataURL转成file即可,代码参考其他步骤。

九.arrayBuffer转blob

利用new Blob();

function arrayBufferToBlob(arrayBuffer, filename) {
                return new Blob([arrayBuffer], { type: filename });
            }
            blobToArrayBuffer(blob, (arrayBuffer) => {
                console.log(arrayBufferToBlob(arrayBuffer, '测试文件'));
                //Blob {size: 5, type: ""}
            });

十.blob转arrayBuffer

利用FileReader.readAsArrayBuffer();

 function blobToArrayBuffer(blob, callback) {
                let reader = new FileReader();
                reader.readAsArrayBuffer(blob);
                reader.onload = function () {
                    return callback(this.result);
                }
            }
            let blob = new Blob([1, 2, 3, 4, 5]);
            blobToArrayBuffer(blob, (arrayBuffer) => { console.log(arrayBuffer) })
            //ArrayBuffer(5) {}

 

  • 6
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值