图片转base64
两种方法
第一种
function getBase64(imgUrl) { var canvas = document.createElement('CANVAS'), ctx = canvas.getContext('2d'), img = new Image; img.src = imgUrl; img.crossOrigin = 'Anonymous'; img.onload = function(){ canvas.height = img.height; canvas.width = img.width; ctx.drawImage(img,0,0); var dataURL = canvas.toDataURL('image/png'); console.log('dataURL: ', dataURL); return dataURL; }; }
第二种
function getBase64(imgUrl) { return new Promise(((resolve, reject) => { window.URL = window.URL || window.webkitURL; var xhr = new XMLHttpRequest(); xhr.open("get", imgUrl, true); xhr.responseType = "blob"; xhr.onload = function () { if (this.status == 200) { var blob = this.response; let oFileReader = new FileReader(); oFileReader.onloadend = function (e) { let base64 = e.target.result; resolve(base64) }; oFileReader.readAsDataURL(blob); } } xhr.send(); }))
青云直上三千码