function getphoto(type){ $('.driveCode[title="'+type +'"]').trigger("click");}var myArray=[];function showPhoto(ele,type){ var files=ele.files, file=files[0]; var typeTemp=file.type; var reader = new FileReader(); reader.onerror=function(){ alert("文件过大,请清理内存后重新读取") } reader.onload=function(){ var result = this.result; var img = new Image(); img.src = result; if (img.complete){ getToken(); }else{ img.onload = getToken; } function getToken(){ var dataTemp = compress(img); $.post(BASE_URL,{ fname:type },function(data){ var result= JSON.parse(data); if(result && result.result == true){ var text = window.atob(dataTemp.split(",")[1]); var buffer = new Uint8Array(text.length); for (var i = 0; i < text.length; i++) { buffer[i] = text.charCodeAt(i); } var blob = getBlob(buffer, typeTemp); function getBlob(buffer, format){ var Builder = window.WebKitBlobBuilder || window.MozBlobBuilder; if(Builder){ var builder = new Builder; builder.append(buffer); return builder.getBlob(format); } else { return new window.Blob([ buffer ], {type: format}); } } var oMyForm = new FormData(); var key=result.key; var uptoken=result.uptoken; oMyForm.append("token",uptoken); oMyForm.append("key", key); oMyForm.append("file",blob); var oReq = new XMLHttpRequest(); oReq.open("POST", "http://upload.qiniu.com/"); oReq.send(oMyForm); oReq.onreadystatechange = function (){ if(oReq.readyState==4 && oReq.status==200){ var filename=JSON.parse(oReq.responseText); var key=filename.key; myArray.push({"key":key,"type":type}); console.log(myArray) } } }else if(result && result.msg){ alert(result.msg) } }) } function compress(img){ var initSize = img.src.length; var width = img.width; var height = img.height; //如果图片大于四百万像素,计算压缩比并将大小压至400万以下 var ratio; if ((ratio = width * height / 1000000)>1) { ratio = Math.sqrt(ratio); width /= ratio; height /= ratio; }else{ ratio = 1; } var canvas=$('.myCanvas[title'+'='+'"'+type+'"'+']')[0]; var ctx=canvas.getContext('2d'); var tCanvas = $(" ")[0]; var tctx = tCanvas.getContext("2d"); 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.1); console.log("压缩前:" + initSize); console.log("压缩后:" + ndata.length); console.log("压缩率:" + (100 * (initSize - ndata.length) / initSize) + "%"); return ndata; } } reader.readAsDataURL(file); }