在微信里ios手機上傳豎拍照片會自動旋轉90度,與拍攝時的角度不同,所以需要處理:
1、使用EXIF.js可以獲取到照片的拍攝屬性:
API 方法
名稱 | 說明 |
---|---|
EXIF.getData(img, callback) | 獲取圖像的數據 能兼容尚未支持提供 EXIF 數據的瀏覽器獲取到元數據。 |
EXIF.getTag(img, tag) | 獲取圖像的某個數據 |
EXIF.getAllTags(img) | 獲取圖像的全部數據,值以對象的方式返回 |
EXIF.pretty(img) | 獲取圖像的全部數據,值以字符串的方式返回 |
//獲取照片方向角屬性,用戶旋轉控制 EXIF.getData(files, function() { //alert(EXIF.getTag(this, 'Orientation')); Orientation = EXIF.getTag(this, 'Orientation'); // return; });
其中Orientation就是拍攝的角度信息;其他參數信息可以查看:http://code.ciaoca.com/javascript/exif-js/
注意:這里我的files是獲取的文件格式的圖片,files[0]獲取的。
Orientation屬性說明如下:
旋轉角度 | 參數 |
0° | 1 |
順時針90° | 6 |
逆時針90° | 8 |
180° | 3 |
2、判斷照片需要旋轉多少角度並使用canvas對其旋轉處理:
//修復ios if (navigator.userAgent.match(/iphone/i)) { var img = new Image(); img.src = resImg.src; img.onload = function(){ var canvas=document.createElement("canvas"); var ctx=canvas.getContext("2d"); var imgWidth = canvas.width = this.width; var imgHeight = canvas.height = this.height; //如果方向角不為1,都需要進行旋轉 added by lzk if(Orientation && Orientation != 1){ switch(Orientation){ case 6: // 旋轉90度 canvas.width = this.height; canvas.height = this.width; ctx.rotate(Math.PI / 2); // (0,-imgHeight) 從旋轉原理圖那里獲得的起始點 ctx.drawImage(this, 0, -imgHeight, imgWidth, imgHeight); break; case 3: // 旋轉180度 ctx.rotate(Math.PI); ctx.drawImage(this, -imgWidth, -imgHeight, imgWidth, imgHeight); break; case 8: // 旋轉-90度 canvas.width = imgHeight; canvas.height = imgWidth; ctx.rotate(3 * Math.PI / 2); ctx.drawImage(this, -imgWidth, 0, imgWidth, imgHeight); break; } }else{ ctx.drawImage(this, 0, 0, imgWidth, imgHeight); } var base64code=canvas.toDataURL("image/png",1); $(resImg).attr("src",base64code); var $blob = baseToBlobImg(base64code); if($(_self).attr('id') == 'hiddenServerId'){ chooseImgList[0].serverImg = $blob //接收blob }else{ chooseImgList[1].serverImg = $blob //接收blob } } }else{ //非蘋果手機壓縮后上傳 var base64code = resImg.src; var $blob = baseToBlobImg(base64code); if($(_self).attr('id') == 'hiddenServerId'){ chooseImgList[0].serverImg = $blob //接收blob }else{ chooseImgList[1].serverImg = $blob //接收blob } }
3、將處理后的圖片最后轉換成bold類型文件上傳:
/*將base64的圖片轉換為blod格式上傳*/ function baseToBlobImg(base64code){ var arr = base64code.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while(n--) { u8arr[n] = bstr.charCodeAt(n); } return obj = new Blob([u8arr], {type:mime}); }
可借鑒CSDN里林志Ke的帖子:利用exif.js解決ios手機上傳豎拍照片旋轉90度問題