记录一下:前端压缩图片
作者:互联网
//这里处理点击上传事件 $('#clipbg-btn').click(function () { var cas = $('#cropper-img').cropper('getCroppedCanvas'); var base64 = cas.toDataURL('image/jpeg'); $("#finalImg").prop("src", base64); // 显示图片 $(".header-img").addClass('no-bg'); // var data = encodeURIComponent(base64); //如果需要URI编码,则使用这个 closecropper() $(".header-img img").attr('src', base64) $(".header-img img").removeClass('default'); $(".btn upload").text('上传中···') $(".upload").attr('disabled', 'disabled'); mui.showLoading("正在上传.....","div"); var bili = 1.5; // 压缩比例 console.log("压缩前base64-length:" + base64.length); suofang(base64, bili, addPicture); }) var suofang = function(base64, bili, callback) { console.log("执行缩放程序,bili=" + bili); //处理缩放,转格式 var _img = new Image(); _img.src = base64; _img.onload = function() { var _canvas = document.createElement("canvas"); var w = this.width / bili; var h = this.height / bili; _canvas.setAttribute("width", w); _canvas.setAttribute("height", h); _canvas.getContext("2d").drawImage(this, 0, 0, w, h); var base64 = _canvas.toDataURL("image/jpeg"); _canvas.toBlob(function(blob) { console.log(blob.size); if(blob.size > 1024*1024){ suofang(base64, bili, callback); }else{ callback(blob, base64); } }, "image/jpeg"); } } function addPicture(blob,base64) { // console.log("base64: " + base64) if (base64.indexOf("image/png") > -1){ base64 = base64.replace('png', 'jpeg'); }; $.ajax({ type: "post", url: "/app/face/updateUserFaceInfo", data: { "base64": base64 }, success: function(r) { console.log(JSON.stringify(r)) $(".upload").removeAttr('disabled'); mui.hideLoading(); /* 上传后操作的动作放这里 */ } }); }
标签:function,canvas,img,记录,前端,base64,bili,var,压缩 来源: https://www.cnblogs.com/dayu33/p/16525019.html