vue項目el-upload移動端ios手機拍照上傳相冊旋轉90度的問題修復


vue項目兼容移動端,上傳圖片用到的是element的el-upload組件,ios手機端使用的時候,拍照上傳照片會出現旋轉90度的問題,以下為解決方案

 

需要在el-upload組件的beforePicUpload的方法中對ios拍照上傳的圖片進行處理

 

①,需要用到exif-js插件進行照片的處理:

npm install exif-js --save

 

②新建一個fileUtils.js文件,使用import引入exif-js

import EXIF from ‘exif-js’

 

然后export default出來以下幾個方法:

import EXIF from 'exif-js'

export default {
    getOrientation: (file) => {
        return new Promise((resolve) => {
            EXIF.getData(file, function () {
                const orient = EXIF.getTag(this, 'Orientation')
                resolve(orient)
            })
        })
    },
 
    dataURLtoFile: (dataurl, filename) => {
        const arr = dataurl.split(',')
        const mime = arr[0].match(/:(.*?);/)[1]
        const bstr = atob(arr[1])
        let n = bstr.length
        let u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, {type: mime});
    },
 
    rotateImage: (image, width, height) => {
        let canvas = document.createElement('canvas')
        let ctx = canvas.getContext('2d')
        ctx.save()
        canvas.width = height
        canvas.height = width
        ctx.rotate(90 * Math.PI / 180)
        ctx.drawImage(image, 0, -height)
        ctx.restore()
        return canvas.toDataURL("image/jpeg")
    },
}

 <fileUtils.js>

 

③在beforePicUpload的方法中調用修改圖片的方法:

首先需要引入fileUtils.js

import fileUtils from '@/utils/fileUtils.js'

 beforePicUpload方法:

beforePicUpload(file) {
        return new Promise((resolve) => {
          fileUtils.getOrientation(file).then((orient) => {
            if (orient && orient === 6) {
                let reader = new FileReader()
                let img = new Image()
                reader.onload = (e) => {
                    img.src = e.target.result
                    img.onload = function () {
                      const data = fileUtils.rotateImage(img, img.width, img.height)
                      const newFile = fileUtils.dataURLtoFile(data, file.name)
                      resolve(newFile)
                    }
                }
                reader.readAsDataURL(file)
            } else {
                resolve(file)
            }
          })
        })
    }

 

再上傳圖片即可,如有疑問可以留言!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM