iphone手機html5上傳圖片方向問題解決

用html5編寫圖片裁切上傳,在iphone手機上可能會遇到圖片方向錯誤問題,在此把解決方法和你們分享一下,
用到了html5的 FileReader和Canvas,若是尚未接觸的同窗,先了解一下其方法。html

//此方法爲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;
}
相關文章
相關標籤/搜索