[英]How to upload an image file to AWS S3, after changing the orientation using Javascript?
我正在使用直接上傳到S3-簽名V4庫上傳照片。 但是,在將這些文件上傳到S3之前,我需要查找並糾正照片的方向。
我已經提到了關於stackoverflow incl的各種答案。 JS客戶端Exif方向:旋轉和鏡像JPEG圖像 。
在上傳到S3之前,我一直堅持將base64映像保存回文件。 這可能是一個愚蠢的小錯誤。 但是,無法進一步發展。 這里下面的腳本供參考。
if (filetype == 0) {
// getDataUrl(file, function (imgBase64) {
// });
window.loadImage(file, function (img) {
if (img.type === "error") {
console.log("couldn't load image:", img);
} else {
window.EXIF.getData(file, function () {
var orientation = window.EXIF.getTag(this, "Orientation");
console.log("orientation: ", orientation);
if (orientation != 1) {
resetOrientation(URL.createObjectURL(file), orientation, function (resetBase64Image) {
file = dataURLtoFile(resetBase64Image, file.name);
var orientation2 = window.EXIF.getTag(file, "Orientation");
console.log("orientation2: ", orientation2);
});
}
});
}
});
}
form.find('input[name="Content-Type"]').val(file.type);
form.find('input[name="key"]').val((folder1.length ? (folder1 + '/' + subfolder ) : subfolder) + filename);
// Now submit form to S3.
data.submit();
和
function resetOrientation(srcBase64, srcOrientation, callback) {
var img = new Image();
img.onload = function () {
var width = img.width,
height = img.height,
canvas = document.createElement('canvas'),
ctx = canvas.getContext("2d");
// set proper canvas dimensions before transform & export
if (4 < srcOrientation && srcOrientation < 9) {
canvas.width = height;
canvas.height = width;
} else {
canvas.width = width;
canvas.height = height;
}
// transform context before drawing image
switch (srcOrientation) {
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: break;
}
// draw image
ctx.drawImage(img, 0, 0);
// export base64
callback(canvas.toDataURL());
};
img.src = srcBase64;
}
function dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type:mime});
}
問題是方向校正的文件未上傳。 而是,上傳的文件繼續具有方向6或8。
僅jpeg文件將被上傳到該站點。
請幫忙。
我找不到可行的解決方案。
因此,我不得不選擇服務器端處理來處理圖像方向問題。
最初,我使用php函數從exif數據檢查方向
$exif = @exif_read_data($file['tmp_name']);
if (!empty($exif['Orientation'])) {
switch ($exif['Orientation']) {
case 3:
$degrees = 180;
break;
case 6:
$degrees = -90;
break;
case 8:
$degrees = 90;
break;
default:
$degrees = 0;
} // switch $exif
} //if (empty(exif))
然后使用PHP函數imagecreatefromjpeg
, imagerotate
和imagejpeg
將圖像保存到S3。 但是,這大大增加了圖像尺寸。 因此,現有的Lambda Java函數可處理縮略圖創建,應用水印,從而可以處理方向,圖像質量和文件大小。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.