問題:三星手機拍照時,正面拍照照片會旋轉,左橫拍才會正常。如下圖所示
image
image
image
上傳之后,就是這亞子,由于后臺需要讀取正臉照,去匹配,顯然這亞子不行。
解決后:
image
**解決問題:使用exif.js來獲取圖像數據,然后進行處理 **
1. 安裝依賴 npm install exif-js --save
- 引用依賴 import EXIF from 'exif-js';
3. 獲取圖像數據 EXIF.getData();
獲取某個數據方向參數 EXIF.getTag(this, 'Orientation');
代碼如下
// 處理圖片旋轉 方法
handleImgRotate(target, listName) {
let canvas = document.createElement('canvas');
let ctx = canvas.getContext('2d');
let orientation = null;
let imgObj = target;
let _this = this;
// 圖片壓縮
if (imgObj && imgObj.width > 1000 && imgObj.height > 1000) {
imgObj.width = imgObj.width / 6;
imgObj.height = imgObj.height / 6;
}
EXIF.getData(imgObj, function() {
// 獲取某個數據方向參數
orientation = EXIF.getTag(this, 'Orientation');
// 為6的時候,圖片需寬高反轉
if (orientation && orientation == 6 && imgObj.width > imgObj.height) {
canvas.width = imgObj.height;
canvas.height = imgObj.width;
} else {
canvas.width = imgObj.width;
canvas.height = imgObj.height;
}
ctx.drawImage(imgObj, 0, 0, imgObj.width, imgObj.height);
if (orientation) {
// 為1,正常
switch (Number(orientation)) {
case 3: // 需要180度旋轉
ctx.rotate(180 * Math.PI / 180);
ctx.drawImage(imgObj, -imgObj.width, -imgObj.height, imgObj.width, imgObj.height);
break;
case 6: // 需要順時針(向左)90度旋轉
ctx.rotate(90 * Math.PI / 180);
ctx.drawImage(imgObj, 0, 0, imgObj.width, -imgObj.height);
break;
case 8: // 需要逆時針(向右)90度旋轉
ctx.rotate(270 * Math.PI / 180);
ctx.drawImage(imgObj, -imgObj.height, 0, imgObj.height, imgObj.width);
break;
default:
ctx.drawImage(imgObj, 0, 0, imgObj.width, imgObj.height);
break;
}
}
_this[listName].push({ image: canvas.toDataURL('image/jpeg')});
});
return _this[listName];
遇到問題,使用的 element-ui 框架里的el-upload組件,上傳成功后,無法讀取上傳后image的圖片信息
解決問題:需要循環出所有圖片,并load加載方法,獲取信息
// 在el-upload中調用改變后的方法
<el-upload
class="avatar-uploader"
:action="uploadUrl"
:show-file-list="false"
:auto-upload="false"
multiple
:on-change="imageChange"
<img style="display: none;" v-for="(item, index) in avatarList" :key="index" :src="item.image" @load="avatarCallback($event)" />
</el-upload>
imageChange(file, fileList) {
this.avatarList = []; // 用于圖片需重新load加載
this.avatarListBase = []; // 改變一次時,需清空之前數據
fileList.forEach((item) => {
this.avatarList.push(
{image: URL.createObjectURL(item.raw)}); }
);
},
avatarCallback(e) {
let data = this.handleImgRotate(e.target); // 調用處理旋轉的方法
this.avatarListBase.push(data); // 添加到一個數組中,用于接口上傳參數時
}
// 上傳接口時:需將base64URL轉換為file
dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type: mime});
},
addWhiteUser() {
this.avatarListBase.forEach((item, index) => {
let formData = new FormData();
let raw = this.dataURLtoFile(this.avatarListBase[index].image, 'face' + index + '.jpg');
formData.append('imgs['+[index]+']', raw); });
});
}