第一步骤
执行命令
cnpm install exif-js --save
第二步骤
写公用 js 文件
// 此js为处理上传图片为手机拍照图片时,上传之后图片旋转展示的问题
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, orient) => {
let canvas = document.createElement('canvas')
let ctx = canvas.getContext('2d')
ctx.save()
canvas.width = height
canvas.height = width
console.log(orient);
if(orient == 8) { //顺时针90°
ctx.rotate(270 * Math.PI / 180)
ctx.drawImage(image, -width, 0);
}else if(orient == 6){ //逆时针90°
ctx.rotate(90 * Math.PI / 180)
ctx.drawImage(image, 0, -height)
}else if(orient == 3){ // 旋转180°
ctx.rotate(180 * Math.PI / 180)
ctx.drawImage(image, -width, -height)
}
// ctx.drawImage(image, 0, -height)
ctx.restore()
return canvas.toDataURL("image/jpeg")
}
}
第三步骤
业务组件引用(我用的是vue + elementui)
import imgUtil from '@/common/imgUtil.js';
<el-upload
class="avatar-uploader"
:action="uploadUrl"
:show-file-list="false"
:on-success="uploadSuccess"
:before-upload="beforeUpload"
:on-error="uploadError">
<img v-if="form.content" :src="form.content" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
beforeUpload(file) {
this.loading = Loading.service({
lock: true,
fullscreen: true,
background: "rgba(0, 0, 0, 0)",
text: "上传中,请稍等...",
customClass: "dan-loading",
spinner: "el-icon-loading"
});
return new Promise((resolve,reject) => {
imgUtil.getOrientation(file).then((orient) => {
if (orient && orient != 1) {
let reader = new FileReader()
let img = new Image()
reader.onload = (e) => {
img.src = e.target.result
img.onload = function () {
const data = imgUtil.rotateImage(img, img.width, img.height, orient)
const newFile = imgUtil.dataURLtoFile(data, file.name)
resolve(newFile)
}
}
reader.readAsDataURL(file)
} else {
resolve(file)
}
})
})
}
其实公用js文件部分不是原创,也是当时查了资料之后整合的,但是已经找不到原创链接了,如果有哪位大佬知道原创链接,欢迎指出,我再贴出来