JavaScript:在使用EXIF进行移动上传之前调整图像方向
我正在尝试从移动设备将图像上传到Firestore,但图像方向仍然是横向的,而它应该是纵向的 基本流程:JavaScript:在使用EXIF进行移动上传之前调整图像方向,javascript,html,mobile,google-cloud-firestore,exif,Javascript,Html,Mobile,Google Cloud Firestore,Exif,我正在尝试从移动设备将图像上传到Firestore,但图像方向仍然是横向的,而它应该是纵向的 基本流程: 上载带有“输入”图像文件的图像 使用EXIF获取方向,并相应地调整到画布 将新画布上载到Firestore 问题: 预览画布时,方向和大小正确,但一旦上传到Firestore,图像仍处于原始(不正确)方向 问题: 代码有问题吗 我是否只是为了显示而定向,而不是更改实际的EXIF数据?如果是这样,我如何编辑它以正确的方向上传 function readURL(input) { if (
- 上载带有“输入”图像文件的图像
- 使用EXIF获取方向,并相应地调整到画布
- 将新画布上载到Firestore
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
var image = new Image();
reader.onload = function(e) {
$('#editImage').attr('src', e.target.result);
EXIF.getData(input.files[0], function() {
// Fetch image tag
// Create canvas
var canvas = document.createElement("canvas");
var img = document.createElement("IMG");
img.setAttribute('src', e.target.result);
// run orientation on img in canvas
orientation(img, canvas);
});
image.onload = function() {
// access image size here
};
};
reader.readAsDataURL(input.files[0]);
console.log(reader);
}
}
function orientation(img, canvas) {
// Set variables
var ctx = canvas.getContext("2d");
var exifOrientation = '';
// Set Width and Height
var width = img.width;
var height = img.height;
var MAX_WIDTH = 600;
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
console.log(width);
console.log(height);
// Check orientation in EXIF metadatas
EXIF.getData(img, function() {
var allMetaData = EXIF.getAllTags(this);
exifOrientation = allMetaData.Orientation;
console.log('Exif orientation: ' + exifOrientation);
});
// set proper canvas dimensions before transform & export
if (jQuery.inArray(exifOrientation, [5, 6, 7, 8]) > -1) {
canvas.width = height;
canvas.height = width;
} else {
canvas.width = width;
canvas.height = height;
}
// transform context before drawing image
switch (exifOrientation) {
case 2:
ctx.transform(-1, 0, 0, 1, width, 0);
break;
case 3:
ctx.transform(-1, 0, 0, -1, width, height);
break;
case 4:
ctx.transform(1, 0, 0, -1, 0, height);
break;
case 5:
ctx.transform(0, 1, 1, 0, 0, 0);
break;
case 6:
ctx.transform(0, 1, -1, 0, height, 0);
break;
case 7:
ctx.transform(0, -1, -1, 0, height, width);
break;
case 8:
ctx.transform(0, -1, 1, 0, 0, width);
break;
default:
ctx.transform(1, 0, 0, 1, 0, 0);
}
// Draw img into canvas
ctx.drawImage(img, 0, 0, width, height);
console.log(canvas.toDataURL());
var DataURL = canvas.toDataURL();
UploadFile(DataURL);
}
我也面临同样的问题,我真的很高兴与大家分享我是如何解决这个问题的 问题: 很少有智能手机,特别是三星和iPhone,以横向模式拍照。但是浏览器不够智能,无法正确渲染此图像 决议: 步骤1:您可以读取图像EXIF信息,并根据方向数据以您想要的方式渲染图像。“exif方向图像”npm包将在这方面派上用场 “exif方向图像”将读取图像文件并返回具有正确方向图像的画布。然后可以在屏幕上渲染画布 步骤2:如果要将正确定向的图像上载到服务器,则不要在步骤1中渲染画布,而是将画布转换为数据URL,然后将数据URL转换为文件。并使用此转换文件上载到s3存储桶或您正在使用的任何服务器