项目经常会用到图片上传的功能不管是PC端还是移动端,今天整理一下代码:
之前做移动端上传图片的时候,会发现,有些图片没有旋转过来,然后,我们只要引入这个插件,就能解决这个问题。
先安装插件exif-js:

npm install exif-js --save

在需要的页面引入

import Exif from 'exif-js'

上传图

uploadImgs (e) {
  let file = e.target.files || e.dataTransfer.files
  if (!file.length) {
    return
  }
  var picavalue = file[0]
  this.imgPreview(picavalue)
},
imgPreview (file, callback) {
  const that = this
  // 创建一个reader
  const reader = new FileReader()
  const img = new Image()

  if (!file || !window.FileReader) return
  if (/^image/.test(file.type)) {
    // eslint-disable-next-line
    let Orientation = null
    // 去获取拍照时的信息,解决拍出来的照片旋转问题
    Exif.getData(file, () => {
      Orientation = Exif.getTag(file, 'Orientation')
    })

    // 读取成功后的回调
    reader.onloadend = function () {
      console.log('==this.result===', this.result)
      const result = this.result
      img.src = result
      img.onload = function () {
        console.log('===Orientation===', Orientation)
        console.log('===img===', img)
        const data = that.compress(img, 0.1, Orientation)
        const blob = that.dataURItoBlob(data)
        const formData = new FormData()
        var nameImg = new Date().getTime() + '.jpg'
        formData.append('file', blob, nameImg)
        // 发送请求
        // 代码自己写把formData传给后台就可以了
      }
    }
    // 将图片转成base64格式
    reader.readAsDataURL(file)
  } else {
    this.$toast('请上传正确的图片格式')
  }
},
// 压缩图片
compress (img, compressNum, Orientation) {
  const canvas = document.createElement('canvas')
  const ctx = canvas.getContext('2d')
  const width = img.width
  const height = img.height
  canvas.width = width
  canvas.height = height
  // 铺底色
  ctx.fillStyle = '#fff'
  ctx.fillRect(0, 0, canvas.width, canvas.height)
  if (Orientation && Orientation !== 1) {
    switch (Orientation) {
      case 6:
        canvas.width = height
        canvas.height = width
        ctx.rotate(Math.PI / 2)
        ctx.drawImage(img, 0, -height, width, height)
        break
      case 3:
        ctx.rotate(Math.PI)
        ctx.drawImage(img, -width, -height, width, height)
        break
      case 8:
        canvas.width = height
        canvas.height = width
        ctx.rotate(3 * Math.PI / 2)
        ctx.drawImage(img, -width, 0, width, height)
        break
    }
  } else {
    ctx.drawImage(img, 0, 0, width, height)
  }

  // 进行压缩 compressNum - 图片质量:取值范围为0到1
  const ndata = canvas.toDataURL('image/jpeg', compressNum)
  return ndata
},
// base64转成bolb对象
dataURItoBlob (base64Data) {
  var byteString
  if (base64Data.split(',')[0].indexOf('base64') >= 0) {
    byteString = atob(base64Data.split(',')[1])
  } else {
    byteString = unescape(base64Data.split(',')[1])
  }
  var mimeString = base64Data
    .split(',')[0]
    .split(':')[1]
    .split(';')[0]
  var ia = new Uint8Array(byteString.length)
  for (var i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i)
  }
  return new Blob([ia], { type: mimeString })
}
Logo

前往低代码交流专区

更多推荐