iOS设备上传照片时出现旋转的问题通常是由于照片的EXIF数据中的方向标签导致的。当使用某些iOS设备拍摄照片时,照片的方向信息会被存储在EXIF元数据中,而某些浏览器或服务器可能不会自动处理这些方向信息,导致照片显示时方向不正确。
可以使用JavaScript库如exif-js
来读取照片的EXIF数据,并根据方向标签旋转图片。以下是一个示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Fix Image Orientation</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/exif-js/2.3.0/exif.min.js"></script>
</head>
<body>
<input type="file" id="fileInput" accept="image/*">
<img id="preview" alt="Preview">
<script>
document.getElementById('fileInput').addEventListener('change', function(event) {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(e) {
const img = new Image();
img.onload = function() {
EXIF.getData(img, function() {
const orientation = EXIF.getTag(this, 'Orientation');
let width = img.width;
let height = img.height;
let x = 0;
let y = 0;
let rotation = 0;
switch (orientation) {
case 3:
rotation = 180;
break;
case 6:
rotation = 90;
[width, height] = [height, width];
x = -height;
break;
case 8:
rotation = 270;
[width, height] = [height, width];
y = -width;
break;
}
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx.translate(width / 2, height / 2);
ctx.rotate(rotation * Math.PI / 180);
ctx.drawImage(img, x, y, width, height, 0, 0, width, height);
document.getElementById('preview').src = canvas.toDataURL();
});
};
img.src = e.target.result;
};
reader.readAsDataURL(file);
}
});
</script>
</body>
</html>
FileReader
读取文件内容。exif-js
库获取照片的EXIF数据。canvas
元素绘制修正后的图片,并显示在页面上。通过这种方式,可以有效解决iOS设备上传照片时出现的旋转问题。
领取专属 10元无门槛券
手把手带您无忧上云