你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> IOS中html5上傳圖片方向問題解決方法

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

編輯:IOS開發綜合

用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 回調方法,返回校正方向後的base64
function 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;
}
  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved