vue图片上传、支持旋转(上传旋转后的图片方案)

 思路:采用element的图片上传图片组件el-upload,上传图片后,canvas绘制旋转后的图片,将canvas绘制出来的base64文件转化成file文件上传

关键代码:

 <el-form :model="formLabelAlign">
        <el-form-item class="is-required">
          <el-upload
            v-model="formLabelAlign.result_pic_path"
            class="upload-demo"
            drag
            action="#"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
          >
            <div v-if="imageUrl" ref="imgWrap" class="rectify-img">
              <img ref="rectifyImg" :src="imageUrl">
              <div class="delete icon" @click.stop="handleDelete" />
              <div class="rotate icon" @click.stop="handleRotate" />
            </div>
            <div v-else>
              <div class="img-dragger-wrap">
                <i class="el-icon-plus" />
                <div class="el-upload__text">拖动图片到此处</div>
              </div>
              <el-button type="primary" size="medium">选择文件</el-button>
            </div>
          </el-upload>
          <span class="upload-tip">(大小:20M以内   格式:jpg、png、bmp、tif   分辨率:不小于112*112)</span>
        </el-form-item>
      </el-form>

校验图片大小、图片格式、分辨率等

   beforeAvatarUpload(file) {
      this.imageUrl = URL.createObjectURL(file)
      this.file = file
      const _this = this
      const imgAccept = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/bmp' || file.type === 'image/tif'
      if (!imgAccept) {
        this.imageUrl = ''
        this.$message.error('不支持此图片格式,请更换图片')
        return false
      }
      const isLt20M = file.size / 1024 / 1024 < 20
      if (!isLt20M) {
        this.$message.error('上传头像图片大小不能超过 20MB!')
      }
      const isSize = new Promise(function(resolve, reject) {
        const _URL = window.URL || window.webkitURL
        const img = new Image()
        img.onload = function() {
          const valid = img.width >= 112 && img.height >= 112
          valid ? resolve() : reject()
        }
        img.src = _URL.createObjectURL(file)
      }).then(() => {
        return file
      }, () => {
        this.imageUrl = ''
        _this.$message.error('不支持此分辨率图片,请更换图片')
        return false
      }).catch(e => {
        console.log(e)
      })
      return imgAccept && isSize && isLt20M
    }

旋转上传功能

 handleRotate() {
      this.rotate += 90
      if (this.rotate >= 360) {
        this.rotate = 0
      }
      const that = this
      this.$refs.rectifyImg.style.transform = `rotate(${this.rotate}deg)`
      const img = new Image()
      img.src = this.imageUrl
      console.log('this.imageUrl', this.imageUrl)
      img.onload = function() {
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')
        canvas.width = img.width
        canvas.height = img.height
        if (that.rotate === 0) {
          ctx.drawImage(img, 0, 0)
        } else if (that.rotate === 90) {
          canvas.width = img.height
          canvas.height = img.width
          ctx.translate(canvas.width / 2, canvas.height / 2)
          ctx.rotate((that.rotate * Math.PI) / 180)
          ctx.drawImage(img, -canvas.height / 2, -canvas.width / 2)
        } else if (that.rotate === 180) {
          ctx.rotate((that.rotate * Math.PI) / 180)
          ctx.drawImage(img, -img.width, -img.height)
        } else {
          canvas.width = img.height
          canvas.height = img.width
          ctx.translate(canvas.width / 2, canvas.height / 2)
          ctx.rotate((that.rotate * Math.PI) / 180)
          ctx.drawImage(img, -canvas.height / 2, -canvas.width / 2)
        }
        const ndata = canvas.toDataURL('image/jpeg', 1.0)
        that.file = that.dataURLtoFile(ndata)
      }
    },

将base64转换为文件

  dataURLtoFile(dataurl) {
      var arr = dataurl.split(',')
      var bstr = atob(arr[1])
      var n = bstr.length
      var u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], 'image', {
        type: 'image'
      })
    },

将this.file上传即是旋转后的图片

上一篇:画点:canvas画折线图的小js


下一篇:js图片添加文字水印并设置水印居中的方法