移动端手机拍照上传的方向问题

iphone正确的手机拍照方式是横屏的,用户往往是竖屏拍照等于照相机反转了90度,出来的照片当然是反转90度,当你横屏拍照上传,图片就是正确的,一张生成的图片是无法辨别选择方向的,只有在上传前反转角度才行,因为上传到服务器以后,程序怎么可能知道这张照片要反转90度,那张要反转180度,另一张要反转270度呢,其他的不用反转呢,正确的拍照姿势很重要呀!

移动端上传后显示在img标签的src中,有遇到图片旋转这种情况,你不能要求用户如何拍照,解决办法:

1. 如果你的后端上传使用阿里OSS管理的图片,那么,工具会提供相应的api进行图片旋转到正确的方向

2. 前端或者后端进行图片参数处理,改变图片方向

如果上传后的图片,点击放大显示在浏览器中,这时浏览器会默认将图片显示成正确的方向

<script src="js/exif.js"></script>
var file = document.querySelector('input[type=file]').files[0];//IE10以下不支持
EXIF.getData(file, function() {
       var Orientation = EXIF.getTag(this, 'Orientation');
       if(Orientation && Orientation != 1){//图片角度不正确
              fileFun(Orientation,file);
       }else{
            //不需处理直接上传
       }
   });
   
//base64格式图片 转为Blob  
function dataURLtoBlob(dataurl) {
    var arr = dataurl.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 new Blob([u8arr], {type:mime});
}
//图片处理函数
function fileFun(Orientation,file){
    var reader = new FileReader();
    var image = new Image();
    reader.readAsDataURL(file);
    
    reader.onload = function (ev) {
            image.src = ev.target.result;
            image.onload = function () {
                var imgWidth = this.width,
                    imgHeight = this.height; //获取图片宽高
                var canvas=document.getElementById("myCanvas");
                var ctx = canvas.getContext('2d');
                canvas.width = imgWidth;
                canvas.height = imgHeight;
                if(Orientation && Orientation != 1){
                    switch(Orientation){
                        case 6:     // 旋转90度
                            canvas.width = imgHeight;
                            canvas.height = imgWidth;
                            ctx.rotate(Math.PI / 2);
                            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 dataurl=canvas.toDataURL("image/jpeg", 0.8);//canvase 转为base64
                var blob = dataURLtoBlob(dataurl);//base64转为blog
            }
        }

}

作者:只会切图的前端 
原文:https://blog.csdn.net/qq_41786458/article/details/83621865 

原文地址:https://www.cnblogs.com/lisaShare/p/10871317.html