一个js就能做到的手机端图片压缩后上传base64
这个是我在做微信投票的时候的一个需求:
现在的手机照片一般都在3-5M,通过程序后台压缩是一个方式,但是顾客太耗费流量了,网上找了下方法用H5canvas来处理图片,经过测试一张图片压缩后不会超过100KB
下面这个js方法就是完整的js,保存到脚本文件中即可使用。
/** * 从网上下载来的一个招数,网上是传多图,我这个是单个上传返回图片路径,要自定义一个callbackCanvsUpload(res)res={'code':1,'data':'','msg':} * * * <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script> <script src="/static/js/canvsupload.js"></script> <input id="canvsUpload" type="file" name="canvsUpload" accept="image/*" multiple="multiple" /> <div id="canvasDiv"></div> <script> function callbackCanvsUpload(res) { alert(res.code); } </script> */ var imgTypeArr = new Array(); var imgArr = new Array(); var isHand = 0;// 1正在处理图片 var base64Img = ''; var nowImgType = "image/jpeg"; var uploadApiUrl="http://www.5atl.com"; var jic = { compress : function(source_img_obj, imgType) { source_img_obj.onload = function() { var cvs = document.createElement('canvas'); var scale = this.height / this.width; cvs.width = 640; cvs.height = 640 * scale; var ctx = cvs.getContext("2d"); ctx.drawImage(this, 0, 0, cvs.width, cvs.height); var newImageData = cvs.toDataURL(imgType, 0.8); base64Img = newImageData; //预览图 //var img = new Image(); //img.src = newImageData; //$(img).css('width', 100 + 'px'); //$(img).css('height', 100 + 'px'); //$("#canvasDiv").append(img); isHand = 0; catUpload(); } } } function handleFileSelect(evt) { isHand = 1; imgArr = []; imgTypeArr = []; $("#canvasDiv").html(""); var files = evt.target.files; for (var i = 0, f; f = files[i]; i++) { // Only process image files. if (!f.type.match('image.*')) { continue; } imgTypeArr.push(f.type); nowImgType = f.type; var reader = new FileReader(); // Read in the image file as a data URL. reader.readAsDataURL(f); // Closure to capture the file information. reader.onload = (function(theFile) { return function(e) { var i = new Image(); i.src = e.target.result; jic.compress(i, nowImgType); }; })(f); } } $(function() { document.getElementById('canvsUpload').addEventListener('change',handleFileSelect, false); }); function catUpload() { if (base64Img == "") { callbackCanvsUpload({'code':-1,'data':'','msc':'您还没有选择图片'}); return false; } if (isHand == 1) { callbackCanvsUpload({'code':-1,'data':'','msc':'请等待图片处理完毕!'}); return; } canvsalert('图片正在处理上传中···'); $.ajax({ type : "POST", url : uploadApiUrl, // data : {'img' : imgArr,'type' : imgTypeArr},// 如果是上传多图就用这个方式 data : {'img' : base64Img,'type' : nowImgType}, success : function(res){ callbackCanvsUpload(res); } }); } function canvsalert(msg) { var style = "display: block; width: 92%;padding:4%; height: 100%; z-index: 10; position: fixed; text-align: center; top: 0px; background: rgba(1,1,1,0.8); color: #fff; padding-top: 200px; font-size: 1em;line-height:1.5em;left:0;"; var str = '<div id="canvsalertc" style="' + style + '">' + msg + '</div>'; $("body").append(str); setTimeout('$("#canvsalertc").remove()', 3000); }