码迷,mamicode.com
首页 > 移动开发 > 详细

移动端图片处理

时间:2021-04-01 13:15:06      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:get   create   wim   this   bst   name   androi   str   src   


  import EXIF from ‘exif-js‘ // 处理移动端拍摄照片旋转的问题
dataURLtoFile (dataurl, filename) {
      /* eslint-disable */
      var arr = dataurl.split(,), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n)
      /* eslint-disable */
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], filename, { type: mime })
    },
    checkOrientation (file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        let orientation = null
        reader.onload = (e) => {
          let img = new Image()
          let canvas = document.createElement(canvas)
          let ctx = canvas.getContext(2d)

          img.src = e.target.result
          img.onload = () => {
            EXIF.getData(img, () => {
              orientation = EXIF.getTag(img, Orientation)
            })
            // 如果没有Orientation 则为Android
            if (!orientation) {
              canvas.width = img.width
              canvas.height = img.height
              ctx.drawImage(img, 0, 0, img.width, img.height)
              resolve(false)
            } else {
              // 如果有Orientation 则为IOS
              switch (orientation) {
                case 1:
                  canvas.width = img.width
                  canvas.height = img.height
                  ctx.drawImage(img, 0, 0, img.width, img.height)
                  break
                case 3:
                  canvas.width = img.width
                  canvas.height = img.height
                  ctx.rotate(Math.PI)
                  ctx.drawImage(img, -img.width, -img.height, img.width, img.height)
                  break
                case 6:
                  canvas.width = img.height
                  canvas.height = img.width
                  ctx.rotate(Math.PI / 2)
                  ctx.drawImage(img, 0, -img.height, img.width, img.height)
                  break
                case 8:
                  canvas.width = img.height
                  canvas.height = img.width
                  ctx.rotate(3 * Math.PI / 2)
                  ctx.drawImage(img, -img.width, 0, img.width, img.height)
                  break
              }
            }
            let dataURL = canvas.toDataURL()
            resolve(this.dataURLtoFile(dataURL, file.name))
          }
        }
        reader.readAsDataURL(file)
      })
    },

 

移动端图片处理

标签:get   create   wim   this   bst   name   androi   str   src   

原文地址:https://www.cnblogs.com/CoderZX/p/14603283.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!