普通图片转base64
function getBase64(url, callback){ var canvas = document.createElement('canvas'),//创建canvas元素 dataURL= '', ctx = canvas.getContext('2d'), img = new Image; //通过构造函数来创建的 img 实例,在赋予 src 值后就会立刻下载图片,相比 createElement() 创建 省去了 append(),也就避免了文档冗余和污染 img.crossOrigin = 'Anonymous'; img.onload = function(){ canvas.height = img.height; canvas.width = img.width; ctx.drawImage(img,0,0,); dataURL = canvas.toDataURL('image/jpeg', 0.5); callback?callback(dataURL):null; //调用回调函数 canvas = null; }; img.src = url; // 图片预览}
获取file对象 ,获取base64URL
var file=document.querySelector("input[type='file']");var file1 = file.files[0]// 获取文件对象var reader = new FileReader();reader.onload=function(ev){ console.log(this.result)// console.log(ev.target.result)}reader.readAsDataURL(file1);