js获取图片的base64编码并压缩

获取图片的base64编码

<!DOCTYPE html> <html> <head> <meta charset="gbk"> <title></title> </head> <body> <input accept="image/*" type="file" onchange="gen_base64()">      <br/> <textarea></textarea>      <br/>      <img src="" /> <script type="text/javascript"> function $_(id) { return document.getElementById(id); } function gen_base64() { var file = $_('upload_file').files[0]; r = new FileReader(); //本地预览 r.onload = function(){ $_('base64_output').value = r.result;              $_('myImg').src= r.result; } r.readAsDataURL(file); //Base64 } </script> </body> </html>

案例2:js压缩图片

<html> <body> <script> function getUrl(fil) { var Cnv = document.getElementById('myCanvas'); var Cntx = Cnv.getContext('2d');//获取2d编辑容器 var imgss = new Image();//创建一个图片 var agoimg=document.getElementById("ago"); for (var intI = 0; intI < fil.length; intI++) {//图片回显 var tmpFile = fil[intI]; var reader = new FileReader(); reader.readAsDataURL(tmpFile); reader.onload = function (e) { url = e.target.result; imgss.src = url; agoimg.src=url; agoimg.onload = function () { //等比缩放 var m = imgss.height / imgss.width; Cnv.width = 300 ;//该值影响缩放后图片的大小 Cnv.height =300*m; //img放入画布中 Cntx.drawImage(agoimg, 0, 0,300,300*m);     //把画布中的数据,写出到某img的src里 var Pic = document.getElementById("myCanvas").toDataURL("image/png"); var imgs =document.getElementById("press"); imgs.src =Pic ; } } } } </script> <input type="file" value="上传图片" hidefocus="true" onchange="getUrl(this.files);"/> <br/> <canvas ></canvas> old img::<img src="" alt=""/> new img::<img src="" alt=""/> </body> </html>

效果图

js获取图片的base64编码并压缩

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/6e49d214186f4f156bf6d2e81c4c6c63.html