vue代码demo ,自行查看,注意得点是 img 的 css 样式需要重置orientation得值,image-orientation: none; 因为支持自动翻转得浏览器会出现翻转两次得情况
<template>
<div class="content">
<!-- <img src="../assets/952621f3-731d-48ce-ab2e-b95fe6a468ef.jpg" /> -->
<input type="file" accept="image/*" @change="change" />
<p>转换前</p>
<img class="preivew" style="height: 100px;" :src="img1" />
<p>转换后</p>
<img
class="preivew2"
:style="{ transform: 'rotate(' + route + ')' }"
:src="img1"
/>
</div>
</template>
<script>
import Exif from "exif-js";
const rotateImg = (file, fileUrl) => {
return new Promise((resolve, reject) => {
let img = new Image();
img.src = fileUrl;
img.onload = function() {
Exif.getData(file, function() {
const orientation = Exif.getTag(this, "Orientation");
if (!orientation || orientation == 1) {
return resolve(0);
}
let route = 0;
//根据orientation设置canvas的大小和旋转参数
switch (orientation) {
case 3: // 旋转180°
route = '180deg';
break;
case 6: // 旋转90°
route = '90deg';
break;
case 8: // 旋转-90°
route = '-90deg';
break;
default:
}
resolve(route);
});
};
});
};
export default {
data() {
return {
img1: "",
img2: "",
route: "0deg",
};
},
methods: {
change(e) {
const file = e.target.files[0];
this.img1 = URL.createObjectURL(file);
let that = this;
rotateImg(file, this.img1).then((res) => {
that.route = res;
});
},
},
};
</script>
<style scoped>
.content {
display: flex;
flex-direction: column;
align-items: center;
overflow-y: auto;
}
img {
width: 400px;
height: auto;
image-orientation: none;
}
</style>