js-图片img转base64格式
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <img src="" class="img"/> <script> function getBase64Image(img){ var canvas=document.createElement("canvas"); canvas.width=img.width; canvas.height=img.height; var ctx=canvas.getContext("2d"); ctx.drawImage(img,0,0,img.width,img.height); var ext=img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase(); var dataUrl=canvas.toDataURL("images/"+ext); return dataUrl; }; var img="images/1.png"; var image=new Image(); image.src=img; image.onload=function(){ var base64=getBase64Image(image); document.getElementsByClassName("img")[0].setAttribute("src",base64) } </script> </body> </html>
最终的效果: