標籤:
/* 將頁面選擇的圖片等比壓縮成指定大小(長邊固定)
file:圖片檔案
callBack:回呼函數
maxLen:長邊的長度
*/
function makePic(file,callBack,maxLen){
var url = webkitURL.createObjectURL(file); /* 產生圖片 */ var $img = new Image(); $img.src = url; // $(‘body‘).append($img); $img.onload = function() { //產生比例 var width = $img.width,height = $img.height; //計算縮放比例 var rate=1; if(width>=height){ if(width>maxLen){ rate=maxLen/width; } }else{ if(height>maxLen){ rate=maxLen/height; } } $img.width=width*rate; $img.height=height*rate; //產生canvas var $canvas =$(‘#thecanvas‘); var ctx = $canvas[0].getContext(‘2d‘); $canvas.attr({width : $img.width, height : $img.height}); ctx.drawImage($img, 0, 0, $img.width, $img.height); var base64 = $canvas[0].toDataURL(‘image/jpeg‘,0.9); callBack(base64);// }}$(‘.unPic_list input[type=file]‘).bind(‘change‘,function(e){ var that=this; for(var j=0;j<e.target.files.length;j++){ makePic(e.target.files[j],function(imgStr){ var img = new Image(); img.src=imgStr; img.onload=function(){ $(‘body‘).append(img);
/*此處將 imgStr.substr(22)操作即的圖片二進位流,可發送到伺服器*/ } },750); } })
利用html5壓縮圖片,產出位元據流