微信公众号里,需要上传照片,由于手机直接拍照上传,照片比较大,直接转BASE64上传会很慢
所以最好在JS中压缩后,再上传
网上找了个方法,照搬试了一下,可以用,但是,图片会被裁剪掉一大块
于是改了改,现在会根据图片是纵向还是横向等比例的进行压缩
哦!对了,这样转出来的BASE64字符串会有23位的文件头
如果后台用JDK的BASE64Decoder再转成图片的话,需要先把文件头去掉,不然无法转换的
HTML部分
<input type="file" name="businessLicence" id="businessLicence" onchange="start_upload(this);"/> <input type="hidden" name="businessLicenceBase64" id="businessLicenceBase64"/>
Js部分
function start_upload(obj){ if(!isCanvasSupported){ console.log("画布不存在,压缩失败"); }else{ compress(event, function(base64Img){ document.getElementById(obj.name+"Base64").value=base64Img; }); } } //判断是否存在画布 function isCanvasSupported() { var elem = document.createElement('canvas'); return !!(elem.getContext && elem.getContext('2d')); } //压缩方法 function compress(event, callback) { if ( typeof (FileReader) === 'undefined') { console.log("当前浏览器内核不支持base64图标压缩"); } else { try { var file = event.currentTarget.files[0]; if(!/image\/\w+/.test(file.type)){ alert("请确保文件为图像类型"); return false; } var reader = new FileReader(); reader.onload = function (e) { var image = $('<img/>'); image.load(function () { console.log("开始压缩"); //压缩的像素大小,square越大,像素越高 var square = 500; var canvas = document.createElement('canvas'); if (this.width > this.height) { canvas.width = Math.round(square * this.width / this.height); canvas.height = square; } else { canvas.width = square; canvas.height = Math.round(square * this.height / this.width); } var context = canvas.getContext('2d'); context.clearRect(0, 0, canvas.width, canvas.height); var imageWidth; var imageHeight; var offsetX = 0; var offsetY = 0; console.log(this.width); console.log(this.height); if (this.width > this.height) { imageWidth = Math.round(square * this.width / this.height); imageHeight = square; } else { imageWidth = square; imageHeight = Math.round(square * this.height / this.width); } console.log(imageWidth); console.log(imageHeight); context.drawImage(this, 0, 0, imageWidth, imageHeight); var data = canvas.toDataURL('image/jpeg'); //压缩完成执行回调 callback(data); }); image.attr('src', e.target.result); }; reader.readAsDataURL(file); } catch(e) { console.log("压缩失败!"); } } }