采用lrz.mobile.min.js插件,实现图片压缩上传功能,兼容H5和移动端Android,IOS;压缩率能达到90%以上,图片清晰度高!(亲测可用,兼容性好!)
插件下载地址:http://download.csdn.net/download/weixin_39904091/10172527
代码示例:
1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8" /> 5 <title>base64</title> 6 <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> 7 8 <script type="text/javascript" src="lrz.mobile.min.js"></script> 9 10 <script type="text/javascript"> 11 $(function(){ 12 console.log("8"); 13 $('#photoAfter').change(function(){ 14 readPhotoAfter(this); 15 }); 16 $("#test").click(function(){ 17 console.log("66"); 18 }); 19 }); 20 21 //图片压缩后,base64编码上传 22 function readPhotoAfter(obj){ 23 console.log(obj.files[0].size/ 1024 +"kb"); 24 var reader = new FileReader(); 25 reader.readAsDataURL(obj.files[0]); 26 reader.onload = function(e){ 27 //console.log(this.result); //就是base64 28 var dd=this.result; 29 console.log("压缩前base64长度:"+dd.length); 30 31 } 32 lrz(obj.files[0], { 33 width: 800, 34 height: 600, 35 before: function () { 36 console.log('压缩开始'); 37 }, 38 fail: function (err) { 39 console.error(err); 40 }, 41 always: function () { 42 console.log('压缩结束'); 43 }, 44 done: function (results) { 45 // 你需要的数据都在这里,可以以字符串的形式传送base64给服务端转存为图片。 46 var data=results.base64; 47 document.getElementById("image").value=data; 48 console.log("编码后base64长度:"+data.length); 49 $("#image").attr("src",data); 50 } 51 }); 52 }; 53 // }); 54 55 56 </script> 57 58 </head> 59 <body> 60 <input type="file" id="photoAfter" /><img id="image" src="" width="200" height="200"/><br/> 61 <input type="button" value="提交" id="test"/> 62 </body> 63 </html>
参考链接:http://think2011.net/localResizeIMG/test/