<!Doctype html> <html> <head> <meta charset="utf-8" /> <title>H5 Js图片转base64编码</title> <style type="text/css"> .a{ border:1px solid #ccc; } .b{ border-color:#fff; } .c{ float:left; } .d{ clear:both; } </style> </head> <body> <div > <span>图片属性:</span> <span id="info"></span> </div> <div class="a c"> <p>base64编码:</p> <textarea id="base64_code" rows="20" cols="60" class="a b"></textarea> </div> <div class="a c" style="width:445px;height:365px;"> <p>图片展示:</p> <div id="img_area"></div> </div> <div class="d"> <input type="file" id="img_upload" /> </div> </body> </html> <script type="text/javascript"> window.onload = function() { var img_upload = document.getElementById("img_upload"); var base64_code = document.getElementById("base64_code"); var img_area = document.getElementById("img_area"); img_upload.addEventListener('change', readFile, false); } function readFile() { var file = this.files[0]; if (!/image\/\w+/.test(file.type)) { alert("请确保文件为图像类型"); return false; } var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function(e) { var data = e.target.result; var image = new Image(); image.onload = function() { var width = image.width; var height = image.height; var info = `width=${width},height=${height},size=${file.size}`; document.getElementById("info").innerHTML = info; } image.src = data; base64_code.innerHTML = this.result; img_area.innerHTML = '<img src="' + this.result + '" alt=""/>'; } } </script>