uniapp上传图片旋转问题如何解决
在uniapp中使用uni.chooseImage选择图片后,上传到服务器时发现图片被自动旋转了方向,尤其是手机拍摄的竖版照片会变成横版。尝试过用exif-js读取Orientation信息但没解决,请问如何正确保持图片原始方向?需要在前端处理还是后端处理?有没有完整的解决方案或示例代码?
2 回复
使用uni.chooseImage选择图片后,通过canvas绘制并修正方向。获取图片的EXIF信息中的Orientation值,根据该值旋转canvas。最后将canvas导出为正确方向的图片。
在Uniapp中,上传图片时出现旋转问题通常是因为图片的EXIF方向信息未被正确处理。以下是解决方案:
1. 使用uni.chooseImage和uni.compressImage处理
uni.chooseImage({
count: 1,
success: (res) => {
const tempFile = res.tempFilePaths[0];
uni.compressImage({
src: tempFile,
quality: 80,
success: (compressedRes) => {
// 压缩后的图片路径,通常已自动修正方向
const correctedPath = compressedRes.tempFilePath;
// 上传 correctedPath
}
});
}
});
2. 使用第三方库手动修正
安装exif-js库:
npm install exif-js
代码示例:
import EXIF from 'exif-js';
function correctImageOrientation(filePath) {
return new Promise((resolve) => {
const img = new Image();
img.src = filePath;
img.onload = function() {
EXIF.getData(img, function() {
const orientation = EXIF.getTag(this, 'Orientation');
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// 根据orientation值旋转画布
switch(orientation) {
case 6: canvas.width = img.height; canvas.height = img.width; break;
case 8: canvas.width = img.height; canvas.height = img.width; break;
case 3: canvas.width = img.width; canvas.height = img.height; break;
default: canvas.width = img.width; canvas.height = img.height;
}
// 应用旋转
ctx.translate(canvas.width/2, canvas.height/2);
switch(orientation) {
case 6: ctx.rotate(90 * Math.PI / 180); break;
case 8: ctx.rotate(-90 * Math.PI / 180); break;
case 3: ctx.rotate(180 * Math.PI / 180); break;
}
ctx.drawImage(img, -img.width/2, -img.height/2, img.width, img.height);
resolve(canvas.toDataURL('image/jpeg'));
});
};
});
}
3. 服务端处理 如果前端处理不便,可在服务端根据EXIF信息旋转图片。
推荐方案:
优先使用uni.compressImage,它通常会自动处理方向问题。若问题依旧存在,再考虑使用EXIF库手动修正。
注意:在部分安卓设备上可能需要额外处理,建议在实际设备上进行充分测试。

