js img转换base64
方法一:canvas
1 <script type="text/javascript"> 2 function getBase64Image(img) { 3 var canvas = document.createElement("canvas"); 4 canvas.width = img.width; 5 canvas.height = img.height; 6 var ctx = canvas.getContext("2d"); 7 ctx.drawImage(img, 0, 0, img.width, img.height); 8 var dataURL = canvas.toDataURL("image/png"); 9 return dataURL 10 // return dataURL.replace("data:image/png;base64,", ""); 11 } 12 13 14 function main() { 15 var img = document.createElement('img'); 16 img.src = './images/Game of Thrones.jpg'; //此处自己替换本地图片的地址 17 img.onload =function() { 18 var data = getBase64Image(img); 19 var img1 = document.createElement('img'); 20 img1.src = data; 21 document.body.appendChild(img1); 22 console.log(data); 23 } 24 } 25 main() 26 27 </script>
方法二:FileReader
1 <html> 2 <head> 3 <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> 4 <title>通过filereader接口读取文件</title> 5 <script type="text/javascript"> 6 function readAsDataURL() 7 { 8 if(typeof FileReader=='undifined') //判断浏览器是否支持filereader 9 { 10 result.innerHTML="<p>抱歉,你的浏览器不支持 FileReader</p>"; 11 return false; 12 } 13 var file=document.getElementById("imagefile").files[0]; 14 if(!/image\/\w+/.test(file.type)) //判断获取的是否为图片文件 15 { 16 alert("请确保文件为图像文件"); 17 return false; 18 } 19 var reader=new FileReader(); 20 reader.readAsDataURL(file); 21 reader.onload=function(e) 22 { 23 var result=document.getElementById("result"); 24 result.innerHTML='<img src="'+this.result+'" alt=""/>' 25 } 26 27 } 28 </script> 29 </head> 30 31 <body> 32 <p> 33 <label>请选择一个文件:</label> 34 <input type="file" id="imagefile" /> 35 <input type="button" value="读取图像" onClick="readAsDataURL();" /> 36 </p> 37 <div name="result" id="result"> 38 <!-- 这里用来显示图片结果--> 39 </div> 40 </body> 41 </html>