iphone手机html5上传图片方向问题解决

用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;
}
    原文作者:lihualong
    原文地址: https://segmentfault.com/a/1190000004346191
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞