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) } }) }) }