我制作了一个带有照片文件上传功能的网页表单。当我通过电脑上传照片时,它会成功上传到我们的服务器。该功能还可将照片调整为最大宽度或最大高度250px。当您使用iOS 7或Android设备的后置摄像头时,这就像魅力除了。像这个例子一样,图像会混乱:
使用电脑,iOS8:正确上传图像。 在Android上使用backcamera也会随机混淆图像(?)。
如何防止这种情况发生?
function readImage(uploader) {
showLoadingModal();
var reader = new FileReader();
var canvas = document.createElement("Canvas");
var image = new Image();
var file = uploader.files[0];
reader.readAsDataURL(file);
reader.onload = function(_file) {
image.src = _file.target.result;
image.onload = function() {
var w = this.width,
h = this.height,
t = file.type,
n = file.name,
s = ~~(file.size/1024) +'KB';
var orientation = 0;
EXIF.getData(this, function() {
orientation = EXIF.getAllTags(this);
});
//Resize
var MAX_WIDTH = 250;
var MAX_HEIGHT = 250;
var width = this.width;
var height = this.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
//Correct Orientation
var context = canvas.getContext("2d");
context.translate(canvas.width / 2, canvas.height / 2);
var xOffset = -0.5, yOffset = -0.5;
switch (orientation.Orientation) {
case 2:
context.scale(-1, 1);
xOffset = -0.5;
yOffset = -0.5;
break;
case 3:
context.rotate(180 * Math.PI/180);
xOffset = -0.5;
yOffset = -0.5;
break;
case 4:
context.scale(1, -1);
xOffset = -0.5;
yOffset = -0.5;
break;
case 5:
canvas.width = height;
canvas.height = width;
context.scale(-1, 1);
context.rotate(270 * Math.PI/180);
xOffset = -1;
yOffset = -1;
break;
case 6:
canvas.width = height;
canvas.height = width;
context.rotate(90 * Math.PI/180);
xOffset = 0;
yOffset = -1;
break;
case 7:
canvas.width = height;
canvas.height = width;
context.scale(-1, 1);
context.rotate(90 * Math.PI/180);
xOffset = 0;
yOffset = 0;
break;
case 8:
canvas.width = height;
canvas.height = width;
context.rotate(270 * Math.PI/180);
xOffset = -1;
yOffset = 0;
break;
}
context.drawImage(this, width * xOffset, height * yOffset, width, height);
var jsonData = {};
jsonData["userid"] = 1;
jsonData["filecontent"] = canvas.toDataURL();
jsonData["filename"] = file.name;
$.ajax({
type: "POST",
url: "",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(jsonData),
success: function () { location.reload(); },
error: function () {
hideLoadingModal();
}
});
};
image.onerror= function() {
alert('Invalid file type: '+ file.type);
};
};
}