vue h5 上传图片角度旋转问题

场景还原: 手机上传人脸照片,但是发现图片是旋转了90度,这个奇葩的问题。解决方法如下。

  • index.html 引入:

 <script src="https://cdn.jsdelivr.net/npm/exif-js"></script>
 
<template>
  <div class="file dc">
    <input ref="upload" accept="image/*" capture="camera" type="file"
      id="upload" class="realfilebt" @change="getFile($event)" />
  </div>
</template>

<script>
import { dataURLtoFile } from "src/assets/scripts/utils";
import axios from "axios";
const axiosInstance = axios.create({});
export default {
  name: "selfphoto",
  props: {
  },
  data() {
    return {
      file: "",
      cUserId: this.$route.query.cUserId,
      fileType: null,
      filename: null
    };
  },
  mounted() {},
  methods: {
    async getFile(e) {
      let that = this;
      // console.info(44, e);
      let file = event.target.files[0];
      console.log("file", file);
      if (!file) {
        return;
      }
      that.fileType = file.type;
      that.filename = file.name;

      var reader = new FileReader();
      var imgUrl = null;
      var Orientation = null;
      reader.readAsDataURL(file);
      EXIF.getData(file, function() {
        Orientation = EXIF.getTag(this, "Orientation");
      });

      // alert("Orientation", Orientation);

      reader.onloadend = function(e) {
        var image = new Image(),
          canvas = document.createElement("canvas"),
          ctx = canvas.getContext("2d");
        image.src = e.target.result;
        imgUrl = e.target.result;
        image.onload = function() {
          var w = image.naturalWidth,
            h = image.naturalHeight;

          if (w > 1000) {
            h = (h * 1000) / w;
            w = 1000;
          }

          // 6、顺时针90   8、逆时针90   3、180度
          if (Orientation == 6) {
            canvas.width = h;
            canvas.height = w;
            ctx.rotate(Math.PI / 2);
            ctx.drawImage(
              image,
              0,
              0,
              image.naturalWidth,
              image.naturalHeight,
              0,
              -h,
              w,
              h
            );
          } else if (Orientation == 3) {
            canvas.width = w;
            canvas.height = h;
            ctx.rotate(Math.PI);
            ctx.drawImage(
              image,
              0,
              0,
              image.naturalWidth,
              image.naturalHeight,
              -w,
              -h,
              w,
              h
            );
          } else if (Orientation == 8) {
            canvas.width = h;
            canvas.height = w;
            ctx.rotate((3 * Math.PI) / 2);
            ctx.drawImage(
              image,
              0,
              0,
              image.naturalWidth,
              image.naturalHeight,
              -w,
              0,
              w,
              h
            );
          } else {
            canvas.width = w;
            canvas.height = h;
            ctx.drawImage(
              image,
              0,
              0,
              image.naturalWidth,
              image.naturalHeight,
              0,
              0,
              w,
              h
            );
          }

          var data = canvas.toDataURL(that.fileType, 1);
          let file = dataURLtoFile(data, that.filename);
          // console.info(333333, data, file);
          that.upload(file);
        };
      };
    },

    upload(file) {
      Indicator.open({
        text: "请稍等...",
        spinnerType: "snake"
      });
      var that = this;

      var data = new FormData();
      data.append("file", file);
      data.append("ossPathName", "QRImg"); // 文件后缀名

      axiosInstance({
        method: "POST",
        url: ` 修改成你的URL`,
        data: data
        // onUploadProgress: function(progressEvent) {
        //   var percentCompleted = Math.round(
        //     (progressEvent.loaded * 100) / progressEvent.total
        //   );
        //   //console.log(percentCompleted)
        //   //对应上传进度条
        //   self.progress = percentCompleted;
        // }
      })
        .then(async res => {
          console.log("res", res.data.Data.ossUrl);
        })
        .catch(function(err) {
          console.log("err", err);
        });
    }
  }
};
</script>

<style lang="scss" scoped>
.file {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 1;
  overflow: hidden;
}
.realfilebt {
  width: 100%;
  height: 100%;
  // background: red;
  opacity: 0;
}
</style>



/**
 * @desc 将base64的图片转为文件流
 * @param {String} dataUrl base64数据
 * @return {Object} 文件流
 */
export const dataURLtoFile = (dataUrl, filename) => {
    // const filename = `img${Date.now()}`;
    const arr = dataUrl.split(',');
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, { type: mime });
};
使用规范:  var file = $("#file_input")[0].files[0]; if(file.size / 1024 > 1024 * 5){ mui.toast('图片不能超过5M'); return; } //图片压缩 compress.rotatePhotoCompress(file,function(imageObj){ var formData = new FormData(); formData.append("uploadFile", imageObj, file.name); // 文件对象 //图片上传 uploadAdd(formData); }); /** * 图片上传 * @param formData */ function uploadAdd(formData){ var URL = apiUrl.addMultImageURL+"?plateTag=order&fileOwnerId=order&fileType=image&token;="+app.getToken(); $.ajax({ url: URL, //请求地址 type: "post", async: true, //默认为异步 data: formData, //参数 contentType: false, //数据请求格式 processData:false, xhr:function(){ myXhr = $.ajaxSettings.xhr(); if(myXhr.upload){ // check if upload property exists myXhr.upload.addEventListener('progress',function(e){ //显示进条 $("#progress1").show(); var loaded = e.loaded;//已经上传大小情况 var tot = e.total;//附件总大小 var per = Math.floor(100*loaded/tot); //已经上传的百分比 mui("#progress1").progressbar({progress:per}).show(); }, false); // for handling the progress of the upload } return myXhr; },// 成功 success: function (data) { //隐藏进条 $("#progress1").hide(); if (data.error == 0 && null != data.url) { mui.toast('上传图片成功'); $('.show_img').append("<div class='imgList'><span class='oClose'>X</span><img src="+app.fileUrl+data.url+"><input type='hidden' name='imgUrls["+count+"]' value="+data.url.replace(app.fileUrl,"")+"></div>"); count++; } else { mui.toast('上传图片失败'); $('#uploadPicButton').html('请你选择图片重新上传'); } }, error:function(rep) { $("#progress1").hide(); console.log(JSON.stringify(rep)); mui.toast('上传异常'); } }) }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值