移動端手機拍照上傳的方向問題

iphone正確的手機拍照方式是橫屏的,用戶每每是豎屏拍照等於照相機反轉了90度,出來的照片固然是反轉90度,當你橫屏拍照上傳,圖片就是正確的,一張生成的圖片是沒法辨別選擇方向的,只有在上傳前反轉角度才行,由於上傳到服務器之後,程序怎麼可能知道這張照片要反轉90度,那張要反轉180度,另外一張要反轉270度呢,其餘的不用反轉呢,正確的拍照姿式很重要呀!前端

移動端上傳後顯示在img標籤的src中,有遇到圖片旋轉這種狀況,你不能要求用戶如何拍照,解決辦法:canvas

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
相關文章
相關標籤/搜索