将图片(路径)转为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);
});

转载于:https://blog.csdn.net/qq_37860634/article/details/104110803?utm_medium=distribute.pc_relevant.none-task-blog-baidujs_title-0&spm=1001.2101.3001.4242

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页