Element-UI的upload组件手机拍照,图片发生旋转

当使用Element-UI的upload组件在手机端上传图片是,手机拍照拍出来的图片会发生旋转问题。

解决方法:
在el-upload组件标签中设置 on-change=“getFile”。
getFile方法

getFile(file, fileList){
      if (file.status == 'ready') {
          var _this = this;
          var event = event || window.event;
          var file = event.target.files[0];
          Exif.getData(file, function () {
              _this.orientation = Exif.getTag(this, 'Orientation');
          });

          var reader = new FileReader();
          _this.fileType = file.type;
          //转base64
          reader.onload = function (e) {
              _this.photoCompress(e.target.result, function (base64Codes) {
                  _this.faceMatchForm.faceImg = base64Codes; //将图片路径赋值给src
              });
          };
          reader.readAsDataURL(file);
      }
    },

解决图片旋转的主要方法photoCompress

photoCompress(path, callback) {
      var _this = this;
      //解决照片旋转问题
      let img = new Image();
      img.src = path;
      img.onload = function () {
          var that = this;
          //生成canvas
          var canvas = document.createElement('canvas'),
              ctx = canvas.getContext('2d');
          // 默认按比例压缩
          var degree = 0, drawWidth, drawHeight, width, height;
          //drawWidth = that.naturalWidth;
          //drawHeight = that.naturalHeight;
          drawWidth = that.width / 2;
          drawHeight = that.height / 2;
          canvas.width = width = drawWidth;
          canvas.height = height = drawHeight;
          //判断图片方向,重置canvas大小,确定旋转角度,iphone默认的是home键在右方的横屏拍摄方式
          if (_this.orientation != "" && _this.orientation != 1) {
              switch (_this.orientation) {
                  //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旋转校正
          ctx.rotate(degree * Math.PI / 180);
          ctx.drawImage(that, 0, 0, drawWidth, drawHeight);

          // 默认图片质量为0.4
          // 回调函数返回base64的值
          var base64 = canvas.toDataURL(_this.fileType, 0.4);
          callback(base64);
      }
  },

你可能感兴趣的:(Element-UI的upload组件手机拍照,图片发生旋转)