我有一个使用 multer 的 Express 应用程序将图像上传到 S3 存储桶。我没有做任何特别的事情,只是直接上传,但是当它们在浏览器中显示时,一些 iPhone 图像是横向的。
我知道这在技术上是一个浏览器错误,Firefox 现在支持 image-orientation
规则,但 Chrome 仍会在其一侧显示图像。
有没有办法让 Express 读取 EXIF 数据并在上传之前旋转它们?
最佳答案
好吧,我明白了。我使用了 JavaScript Load Image 的组合和 FormData API。
首先,我使用“加载图像”从 exif 数据获取图像的方向并旋转它。然后,我将转换 Load Image 提供的 Canvas 输出并将其转换为 Blob(对于 iOS,您可能还需要 .toBlob()
polyfill,因为它尚不支持此功能。
然后将该 blob 附加到 FormData
对象,并且我还将它放回 DOM 中以进行文件预览。
// We need a new FormData object for submission.
var formData = new FormData();
// Load the image.
loadImage.parseMetaData(event.target.files[0], function (data) {
var options = {};
// Get the orientation of the image.
if (data.exif) {
options.orientation = data.exif.get('Orientation');
}
// Load the image.
loadImage(event.target.files[0], function(canvas) {
canvas.toBlob(function(blob) {
// Set the blob to the image form data.
formData.append('image', blob, 'thanksapple.jpg');
// Read it out and stop loading.
reader.readAsDataURL(blob);
event.target.labels[0].innerHTML = labelContent;
}, 'image/jpeg');
}, options);
reader.onload = function(loadEvent) {
// Show a little image preview.
$(IMAGE_PREVIEW).attr('src', loadEvent.target.result).fadeIn();
// Now deal with the form submission.
$(event.target.form).submit(function(event) {
// Do it over ajax.
uploadImage(event, formData);
return false;
});
};
});
现在介绍我使用 jQuery 的 AJAX 方法的 uploadImage
函数。请注意 processData
和 contentType
标志,它们很重要。
function uploadImage(event, formData) {
var form = event.target;
$.ajax({
url: form.action,
method: form.method,
processData: false,
contentType: false,
data: formData
}).done(function(response) {
// And we're done!
});
// Remove the event listener.
$(event.target).off('submit');
}
所有信息都在那里,但它分布在多个资源中,希望这会节省人们大量的时间和猜测。
关于node.js - 如何让我的 Express 应用程序在上传时尊重方向 EXIF 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37317718/