img图片旋转后保存上传

最近写运营后台要实现一个功能,H5端上传的照片在运营后台查看会旋转90°,要实现一个编辑旋转后保存上传的功能。

<img :src="currentImg" id="picrota"></img>
<el-button @click="editPic(url)">编辑图片</el-button>
editPic(url){
this.downloadIamge(url)
},
base64ToFile(urlData, fileName) {
      let arr = urlData.split(",");
      let mime = arr[0].match(/:(.*?);/)[1];
      let bytes = atob(arr[1]); // 解码base64
      let n = bytes.length;
      let ia = new Uint8Array(n);
      while (n--) {
        ia[n] = bytes.charCodeAt(n);
      }
      // console.log(urlData,fileName)
      return new File([ia], fileName, { type: mime });
    },
downloadIamge(imgSrc, name) {
      //下载图片地址和图片名
      var image = new Image();
      // 解决跨域 Canvas 污染问题
      image.setAttribute("crossOrigin", "anonymous");
      var that = this
      image.onload = function () {
        var canvas = document.createElement("canvas");
        console.log(document.getElementById("picrota").width,document.getElementById("picrota").height)
        let line = document.getElementById("picrota").width>document.getElementById("picrota").height?document.getElementById("picrota").width:document.getElementById("picrota").height
        console.log(line)
        var width = document.getElementById("picrota").width                                 
        var height = document.getElementById("picrota").height
        var w = that.deg % 180 == 0 ? width : height
        var h = that.deg % 180 == 0 ? height : width

        canvas.width = w;
        canvas.height = h;
        var context = canvas.getContext("2d");
        context.translate(w/2, h/2);
        context.rotate(that.deg * Math.PI / 180);
        context.translate(-w/2, -h/2);
        context.drawImage(image, w/2 - document.getElementById("picrota").width/ 2, h/2 - document.getElementById("picrota").height / 2, document.getElementById("picrota").width, document.getElementById("picrota").height); 
        var url = canvas.toDataURL("image/png"); //得到图片的base64编码数据
        that.cro = that.base64ToFile(url,`avatar${new Date().getTime()}.jpg`);
         that.picUpload(that.base64ToFile(url,`avatar${new Date().getTime()}.jpg`))
      };
      image.src = imgSrc;
     
    },
   picUpload(file) {
      let param = new FormData(); // 创建form对象
      param.append("file", file);
      let config = {
        headers: { "Content-Type": "multipart/form-data" },
      };
      this.$axios.post(this.uploadPath, param, config).then((res) => {
        console.log(res)
      }).catch(err => {
        this.$message.error(err.msg || err)
      });
    },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值