IOS中html5上傳圖片方向問題解決方案_IOS

來源:互聯網
上載者:User

用html5編寫圖片裁切上傳,在iphone手機上可能會遇到圖片方向錯誤問題,在此把解決方案和大家分享一下,
用到了html5的 FileReader和Canvas,如果還沒有接觸的同學,先瞭解一下其方法。

 //此方法為file input元素的change事件 function change(){  var file = this.files[0];  var orientation;  //EXIF js 可以讀取圖片的元資訊 https://github.com/exif-js/exif-js  EXIF.getData(file,function(){    orientation=EXIF.getTag(this,'Orientation');  });  var reader = new FileReader();  reader.onload = function(e) {      getImgData(this.result,orientation,function(data){      //這裡可以使用校正後的圖片data了     });   }  reader.readAsDataURL(file);}
// @param {string} img 圖片的base64// @param {int} dir exif擷取的方向資訊// @param {function} next 回調方法,返回校正方向後的base64function getImgData(img,dir,next){ var image=new Image(); image.onload=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;    }  }  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旋轉校正  context.rotate(degree*Math.PI/180);  context.drawImage(this,0,0,drawWidth,drawHeight);  //返回校正圖片  next(canvas.toDataURL("image/jpeg",.8)); } image.src=img;}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.