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>

  

最终的效果:

 

posted @ 2018-10-22 09:52  MiniDuck  阅读(5076)  评论(1编辑  收藏  举报