上传图片,JS中等比压缩返回BASE64格式String

微信公众号里,需要上传照片,由于手机直接拍照上传,照片比较大,直接转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("压缩失败!"); } } }

 

posted on 2018-04-11 16:46 米德 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/mide0131/p/8796696.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值