将图片(路径)转换为Base64 和 将base64转换为file类型

var image={
    /* 将图片(路径)转换为Base64 */
    getBase64FromImageURL(url, callback) {
        var canvas = document.createElement('canvas'),
            ctx = canvas.getContext('2d'),
            img = new Image;
        img.crossOrigin = 'Anonymous';
        img.onload = function() {
            canvas.height = img.height;
            canvas.width = img.width;
            ctx.drawImage(img, 0, 0);
            var base64URL = canvas.toDataURL('image/png');
            callback(base64URL);
            canvas = null;
        };
        img.src = url;
    },
    /* 将base64转换为file类型 */
    getFileFromBase64(base64URL, filename) {
        var arr = base64URL.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 });
    }
}
/* 测试用例 */
image.getBase64FromImageURL('1.png', (base64URL)=> {
    console.log(base64URL);
    var imgURL = image.getFileFromBase64(base64URL, 'imgName');
    console.log(imgURL);
});

 

你可能感兴趣的:(Sg.js,PLUS,Sg.js框架)