html5+canvas实现图片的压缩上传

来源:互联网 发布:ipad pro 记笔记 知乎 编辑:程序博客网 时间:2024/05/18 02:22

     在任何项目中,图片的上传都是很常用的功能,在html5未普及之前,人们用插件来实现这个功能,比如jquery.fileupload.js,这些插件虽然功能强大,但是总觉得挺麻烦。如果你的功能的浏览器要求是在IE10以上,那么不妨用html5的FileReader对象来实现。

      FileReader对象主要用来把文件读入内存,并且读取文件中的数据。对图片上传这里用到的是该对象的readAsDataURL方法,该方法用于将文件中的数据读取为dataURL,如图为图片转化的部分:


但是在很多时候,选择的图片太大导致上传的过程卡滞,甚至浏览器崩溃而导致上传失败,特别是在移动设备中,这个时候可以通过在文件选取的时候通过获取file对象的size属性来判断文件是否超过限制范围,从而限制上传。当然,还有一种方式,利用canvas来对图片进行压缩。

    利用canvas的drawImage方法来绘制图片,并且设置绘制的图片的width跟height,最后再通过canvas的toDataURL方法来生成压缩后的dataUR

   下面直接上代码:

html:

<div class="head_img pr">                        <em class="pa"></em>                        <img src='../images/icon_touxiang.png' alt="" class="modify_img" />                        <input id="photo" type="file" accept="image/*" />                    </div>
jquery:

$('#photo').change(function(){var _this = $(this)[0],    _file = _this.files[0],fileType = _file.type;console.log(_file.size);if(/image\/\w+/.test(fileType)){$.notify.show('图片上传中...', function(){});var fileReader = new FileReader();fileReader.readAsDataURL(_file);fileReader.onload = function(event){var result = event.target.result;   //返回的dataURLvar image = new Image();image.src = result;image.onload = function(){  //创建一个image对象,给canvas绘制使用var cvs = document.createElement('canvas');var scale = 1;  if(this.width > 1000 || this.height > 1000){  //1000只是示例,可以根据具体的要求去设定  if(this.width > this.height){  scale = 1000 / this.width;}else{  scale = 1000 / this.height;  }  }cvs.width = this.width*scale;                                  cvs.height = this.height*scale;     //计算等比缩小后图片宽高var ctx = cvs.getContext('2d');  ctx.drawImage(this, 0, 0, cvs.width, cvs.height);                                 var newImageData = cvs.toDataURL(fileType, 0.8);   //重新生成图片,<span style="font-family: Arial, Helvetica, sans-serif;">fileType为用户选择的图片类型</span>var sendData = newImageData.replace("data:"+fileType+";base64,",'');$.post('/user/personalchange',{type:'photo',value:sendData},function(data){if(data.code == '200'){$('.modify_img').attr('src',newImageData);$.notify.close();}else{$.notify.show(data.message, {placement: 'center'});}});}}}else{$.notify.show('请选择图片格式文件', {placement: 'center'});}});

这只是一个简单的例子,可以把处理压缩的那部分代码独立出来,然后实现选择多个图片是的循环处理。

上传前


上传中


上传后





1 0
原创粉丝点击