Convert base64 png data to javascript file objects

后端 未结 3 1193
既然无缘
既然无缘 2020-11-28 06:22

I have two base64 encoded in PNG, and I need to compare them using Resemble.JS

I think that the best way to do it is to convert the PNG\'s

3条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-28 07:17

    Way 1: only works for dataURL, not for other types of url.

    function dataURLtoFile(dataurl, filename) {
        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);
        }
        return new File([u8arr], filename, {type:mime});
    }
    
    //Usage example:
    var file = dataURLtoFile('data:image/png;base64,......', 'a.png');
    console.log(file);
    

    Way 2: works for any type of url, (http url, dataURL, blobURL, etc...)

    //return a promise that resolves with a File instance
    function urltoFile(url, filename, mimeType){
        mimeType = mimeType || (url.match(/^data:([^;]+);/)||'')[1];
        return (fetch(url)
            .then(function(res){return res.arrayBuffer();})
            .then(function(buf){return new File([buf], filename, {type:mimeType});})
        );
    }
    
    //Usage example:
    urltoFile('data:image/png;base64,......', 'a.png')
    .then(function(file){
        console.log(file);
    })
    

    Both works in Chrome and Firefox.

提交回复
热议问题