Sow nothing reap nothing

图片转Base64、转二进制流及Base64转File

已有2,622次关注

imgConversion = {
    /**
     * Base64字符串转file文件
     * @param {Object} dataurl  base
     * @param {Object} filename 文件名称
     */
    dataURLtoFile: function(dataurl, filename) {
        let arr = dataurl.split(',');
        let mime = arr[0].match(/:(.*?);/)[1];
        let bstr = atob(arr[1]);
        let n = bstr.length;
        let u8arr = new Uint8Array(n);
        while(n--){
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, {type:mime});
    },
    
    /**
     * Base64字符串转二进制流
     * @param {Object} dataurl
     */
    dataURLtoBlob: function(dataurl){
        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 Blob([u8arr], {
            type: mime
        });
    },
    
    /**
     * 图片转换为base64
     * @param {Object} img
     */
    getBase64Image: function(img){  
        let canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;
        let ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, img.width, img.height);
        let ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
        let dataURL = canvas.toDataURL("image/" + ext);
        return dataURL;
    },
}

已自动关闭评论