手机端头像上传前端压缩

使用input文件标签上传标签,实现头像上传

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<script type="text/javascript" src="./jquery-1.8.3.min.js"></script>
	<script type="text/javascript" src="./exif.js"></script>
</head>
<body>
<form>
	<input id="file_header" name="file" type="file" accept="image/*" capture="camera">
</form>
</body>
</html>


压缩方法
$.fn.uploadHeader=function(fun){
		this.each(function(){
			var filechooser = this;
			//用于压缩图片的canvas
		    var canvas = document.createElement("canvas");
		    var ctx = canvas.getContext('2d');
		    //瓦片canvas
		    var tCanvas = document.createElement("canvas");
		    var tctx = tCanvas.getContext("2d");
		    //图片最大值 
		    var maxsize = 100 * 1024;
	    	//这个是处理图片旋转问题,在ios手机下,图片会发生旋转
			function getImgData(img,dir,next){
			    var image=new Image();
			    image.οnlοad=function(){
			        var degree=0,drawWidth,drawHeight,width,height;
			        //原始宽高
			        drawWidth=this.naturalWidth;
			        drawHeight=this.naturalHeight;
			        //以下改变一下图片大小
			        var maxSide = Math.max(drawWidth, drawHeight);
			        if (maxSide > 1024) {
			            var minSide = Math.min(drawWidth, drawHeight);
			            minSide = minSide / maxSide * 1024;
			            maxSide = 1024;
			            if (drawWidth > drawHeight) {
			                drawWidth = maxSide;
			                drawHeight = minSide;
			            } else {
			                drawWidth = minSide;
			                drawHeight = maxSide;
			            }
			        }
			        //使用canvas修正图片的方向
			        var canvas=document.createElement('canvas');
			        canvas.width=width=drawWidth;
			        canvas.height=height=drawHeight;
			        var context=canvas.getContext('2d');
			        //判断图片方向,重置canvas大小,确定旋转角度,iphone默认的是home键在右方的横屏拍摄方式
			        switch(dir){
			            //iphone横屏拍摄,此时home键在左侧
			            case 3:
			                degree=180;
			                drawWidth=-width;
			                drawHeight=-height;
			                break;
			            //iphone竖屏拍摄,此时home键在下方(正常拿手机的方向)
			            case 6:
			                canvas.width=height;
			                canvas.height=width;
			                degree=90;
			                drawWidth=width;
			                drawHeight=-height;
			                break;
			            //iphone竖屏拍摄,此时home键在上方
			            case 8:
			                canvas.width=height;
			                canvas.height=width;
			                degree=270;
			                drawWidth=-width;
			                drawHeight=height;
			                break;
			        }
			        //使用canvas旋转校正
	        		degree&&context.rotate(degree*Math.PI/180);//安卓没有获取旋转角度
			        context.drawImage(this,0,0,drawWidth,drawHeight);
			        //返回校正图片
			        next(canvas.toDataURL("image/png"));
			    }
			    image.src=img;
			}
		    filechooser.onchange = function() {
			    if (!this.files.length) return;
			    var files = Array.prototype.slice.call(this.files);
			    if (files.length > 9) {
			      alert("最多同时只可上传9张图片");
			      return;
			    }
			    files.forEach(function(file, i) {
			          //上传的格式
			        if (!/\/(?:jpeg|png|gif)/i.test(file.type)) return;

			          //创建一个filereader
			        var reader = new FileReader();
			          //获取图片大小
			        var size = file.size / 1024 > 1024 ? (~~(10 * file.size / 1024 / 1024)) / 10 + "MB" : ~~(file.size / 1024) + "KB";
			        var orientation;
		            EXIF.getData(file,function(){
		                orientation=EXIF.getTag(this,'Orientation');
		            });
			        reader.onload = function() {
						getImgData(this.result,orientation,function(data){
		                    loadimg(data);
		                });
			        };
			        reader.readAsDataURL(file);
			    })
			};
			function loadimg(data){
				var img = new Image();
	            img.src = data;
	            img.onload = function(){
	                //如果图片大小小于100kb,则直接上传
	                if (data.length <= maxsize) {
	                    img = null;
	                    fun(data);
	                    return;
	                }
	                //图片加载完毕之后进行压缩,然后上传
	                if (img.complete) {
	                    callback();
	                } else {
	                    img.onload = callback;
	                }
	                function callback() {
	                    var data = compress(img);
	                    fun(data);
	                    img = null;
	                }
	            }
			}
			function compress(img) {
		      var initSize = img.src.length;
		      var width = img.width;
		      var height = img.height;
		      //如果图片大于四百万像素,计算压缩比并将大小压至400万以下
		      var ratio;
		      if ((ratio = width * height / 4000000) > 1) {
		        ratio = Math.sqrt(ratio);
		        width /= ratio;
		        height /= ratio;
		      } else {
		        ratio = 1;
		      }
		      canvas.width = width;
		      canvas.height = height;
		  	  //铺底色
		      ctx.fillStyle = "#fff";
		      ctx.fillRect(0, 0, canvas.width, canvas.height);
		      //如果图片像素大于100万则使用瓦片绘制
		      var count;
		      if ((count = width * height / 1000000) > 1) {
		        count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片
		        //计算每块瓦片的宽和高
		        var nw = ~~(width / count);
		        var nh = ~~(height / count);
		        tCanvas.width = nw;
		        tCanvas.height = nh;
		        for (var i = 0; i < count; i++) {
		          for (var j = 0; j < count; j++) {
		            tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
		            ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
		          }
		        }
		      } else {
		        ctx.drawImage(img, 0, 0, width, height);
		      }
		      //进行最小压缩
		      var ndata = canvas.toDataURL('image/jpeg', 0.3);
		      tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
		      return ndata;
		    }
		})
	}



使用的是64位的图片上传,所以接口也得是64位的
$(function(){
		$("#file_header").uploadHeader(function(rst){
			var url = "http://textbooktest.e-edusky.com/textbook/common/upload1";
	        $.ajax({
	            url: url,
	            data: {"base64Data":rst},
	            dataType:'json',
	            type: 'POST',
	            beforeSend: function() {
	            },
	            success: function(oData, statusText) {
	                //提交成功后调用
	                if(oData.httpCode=="200"){
	                    $('<div><img src="'+oData.result.path+'"><span></span></div>').insertBefore($('.addimg'));
	                }else{
	                    tip("上传失败!文件不合格");
	                }
	            },error:function(data){
	            },complete:function(){
	                
	            }
	        });
		});
	})


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值