var image={ /* 将图片(路径)转换为Base64 */ getBase64FromImageURL(url, callback) { let suffix = url.split('.').slice(-1)[0];//扩展名 var canvas = document.createElement('canvas'), ctx = canvas.getContext('2d'), img = new Image; img.crossOrigin = 'Anonymous'; img.src = url; img.onload = function () { canvas.height = img.height; canvas.width = img.width; ctx.drawImage(img, 0, 0); var base64URL = canvas.toDataURL(`image/${suffix || 'png'}`); callback(base64URL); canvas = null; }; }, /* 将base64转换为file类型 */ getFileFromBase64(base64, filename) { var arr = base64.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); });