1. 程式人生 > >jquery 前端實現圖片壓縮和上傳

jquery 前端實現圖片壓縮和上傳

        手機端上傳圖片時,有時候圖片會是一張比較大的圖片,上傳一張的大的圖片會消耗比較大的資源影響效率,這個時候就需要對上傳的圖片進行壓縮了。然而圖片的壓縮有很多種的實現方式,我這裡主要是通過畫布,拆分瓦片的形式來壓縮圖片。

  (這個主要為個人筆記記錄)

       jquery的程式碼實現:

	//用於壓縮圖片的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;
	//使用canvas對大圖片進行壓縮
	function compress(img) {
		var initSize = img.src.length;
		var width = img.width;
		var height = img.height;
		var bili = 1;
		if(width>480){
			bili = 480/width;
		}else{
			if(height>640){
				bili = 640/height;
			}else{
				bili=1;
			}
		}
		//如果圖片大於四百萬畫素,計算壓縮比並將大小壓至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', bili);
		tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
		return ndata;
	}

html的程式碼:

.inputfilestyle{
    width:96%;
    height:2.4rem;
    cursor: pointer;
    font-size: 30px;
    outline: medium none;
    position: absolute;
    filter:alpha(opacity=0);
    -moz-opacity:0;
    opacity:0;
    z-index:9999;
}

上傳多張圖片的示例

<div class="card">
   <div class="card-header">照片</div>
	<div class="card-content" style="display: none;" id="carddiv">
	    <div class="card-content-inner">
		<div id="imgresultdiv"></div>
	    </div>
	</div>
	<div class="card-footer">
	    <div class="content-block" style="width: 100%;">
		<div class="row" style="width: 100%;">
		   <div class="col-100">
			<input type="file" id="imgchoose" accept="image/*" multiple class="inputfilestyle" onclick="buttonclick();">
			<a href="#" class="button button-big button-fill button-blue">上傳照片</a>
		   </div>
		</div>
	    </div>
	 </div>
   </div>
</div>


其jquery程式碼
var filechooser = document.getElementById("imgchoose");
var imagebase64Array = new Array();
var chooseflag = false;
var filelength = 0;
var checklength = 0;
function buttonclick(){
    filelength = 0;
    checklength = 0;
}
//刪除照片
function deleteImg(num){
	var temp = new Array();
	for(var i=0;i<imagebase64Array.length;i++){
		if(i!=num){
			temp.push(imagebase64Array[i]);
		}
	}
	imagebase64Array = temp;
	showImg();
}
//顯示照片
function showImg(){
	if(imagebase64Array.length){
		$("#imgresultdiv").html("");
		for(var i=0;i<imagebase64Array.length;i++){
			var tempstr = imagebase64Array[i];
			var html = '<div style="border: 1px solid #cccccc;"><table style="width: 100%;"><tr><td align="center" style="background-image: url(\'\')">'
				+'<img src="'+tempstr+'" width="98%" id="htzpimg'+i+'" name="htzpimg"/></td></tr></table>';
			html =html+'<div class="menu-btn" style="margin: 15px;"><a href="#" onclick="deleteImg('+i+')">刪除該照片</a></div></div>';
			$("#imgresultdiv").append(html);
		}
		$("#carddiv").show();
	}else{
		$("#imgresultdiv").html("");
		$("#carddiv").hide();
	}
}
filechooser.onchange = function () {
	$.showIndicator();
	if (!this.files.length){
		$.hideIndicator();
		return;
	}
	var files = Array.prototype.slice.call(this.files);
   /*	if (files.length > 8) {
		$.hideIndicator();
		$.alert("最多同時只可上傳8張圖片");
		return null;
	}  */
	filelength = files.length;
	files.forEach(function(file, i) {
		if (!/\/(?:jpeg|png|gif|jpg)/i.test(file.type)) return;  //可以上傳的圖片格式為 .jpeg、.png、.gif、.jpg
		var reader = new FileReader();
		//獲取圖片大小
		var size = file.size / 1024 > 1024 ? (~~(10 * file.size / 1024 / 1024)) / 10 + "MB" : ~~(file.size / 1024) + "KB";
		reader.onload = function() {
		    var result = this.result;
		    var img = new Image();
		    img.src = result;
		    //如果圖片大小小於100kb,則直接上傳
		    if (result.length <= maxsize) {
				img = null;
                                $.hideIndicator();
                                imagebase64Array.push(result);
                                chooseflag = true;
                                checklength = checklength+1;
                               if(checklength==filelength){
                                  showImg();
                                  $("#imgchoose").val("");
                                  $.alert("選擇圖片成功!");
                               }
                               return ;
                    }
                   //圖片載入完畢之後進行壓縮,然後上傳
                    if (img.complete) {
                        callback();
                    } else {
                        img.onload = callback;
                    }
                    function callback() {
                        var data = compress(img);
                        $.hideIndicator();
                        imagebase64Array.push(data);
                        chooseflag = true;
                        checklength = htchecklength+1;
                        if(checklength==filelength){
                            showImg();
                            $("#imgchoose").val("");
                            $.alert("選擇圖片成功!");
                         }
                         img = null;
                    }
               };
               reader.readAsDataURL(file);
       })
};


上傳一張圖片的示例
<div class="card">
	<div class="card-header">照片</div>
		<div class="card-content" style="display: none;" id="imgdiv">
			<div class="card-content-inner">
			<div id="resultdiv"></div>
		</div>
	</div>
	<div class="card-footer">
		<div class="content-block" style="width: 100%;">
			<div class="row" style="width: 100%;">
				<div class="col-100">
					<input type="file" id="imgchoose" accept="image/*" multiple  class="inputfilestyle">
					<a href="#" class="button button-big button-fill button-blue" onclick="" id="shangchuanimg">上傳照片</a>
				</div>
			</div>
		</div>
	</div>
</div>


對應的jquery
var filechooser = document.getElementById("imgchoose");
var imagebase64 = "";
var chooseflag = false;
//刪除照片
function deleteshowImg(num){
	if(num==0){
		imagebase64 = "";
		chooseflag = false;
		$("#resultdiv").html("");
		$("#imgdiv").hide();
		$("#shangchuanimg").attr("onclick","");
		$("#shangchuanimg").html("上傳照片");
		$("#imgchoose").val("");
		$("#imgchoose").show();
	}
}
//頁面顯示上傳的圖片
function showImg(num){
	if(num==0){ 
		var html = '<table style="width: 100%;"><tr><td align="center" style="background-image: url(\'\')" >'
			+'<img src="'+imagebase64+'" width="98%" id="htzpimg'+num+'" name="htzpimg"/></td></tr></table>';
		$("#imgdiv").html(html);
		$("#shangchuanimg").attr("onclick","deleteshowImg("+num+")");
		$("#shangchuanimg").html("刪除照片");
		$("#imgdiv").show();
		$("#imgchoose").hide();
	}
}
//圖片上傳
filechooser.onchange = function () {
        $.showIndicator();
        if (!this.files.length){ 
            $.hideIndicator();
            return;
       }
       var files = Array.prototype.slice.call(this.files);
      if (files.length > 1) {
            $.hideIndicator();
            $.alert("最多同時只可選擇1張圖片");
            return ;
      }
       files.forEach(function(file, i) {
            if (!/\/(?:jpeg|png|gif)/i.test(file.type)) return;
            var reader = new FileReader();
            //獲取圖片大小
            var size = file.size / 1024 > 1024 ? (~~(10 * file.size / 1024 / 1024)) / 10 + "MB" : ~~(file.size / 1024) + "KB";
            reader.onload = function() {
            var result = this.result;
            var img = new Image();
            img.src = result;
            //如果圖片大小小於100kb,則直接上傳
              if (result.length <= maxsize) {
                    $.hideIndicator();
                    img = null;
                    $.alert("選擇圖片成功!");
                    imagebase64 = result;
                    chooseflag = true;
                    showImg(0);
                    return ;
              }
              //圖片載入完畢之後進行壓縮,然後上傳
             if (img.complete) {
                callback();
             } else {
                 img.onload = callback;
             }
             function callback() {
                 var data = compress(img);
                 $.hideIndicator();
                 imagebase64 = data;
                 chooseflag = true;
                 showImg(0);
                 $.alert("選擇圖片成功!");
                 img = null;
              };
             reader.readAsDataURL(file);
        })
};