移动端h5 ios 拍照 图片上传后旋转问题的解决

1、使用exif.js获取图片信息 再用canvas旋转后 转base64 再转blog


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
            }
        }

}

你可能感兴趣的:(web移动端)