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

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 15:51   6102   0

总结一下常用的转换类型

一.将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) {}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP