我正在製作一個簡單的網絡應用程序,允許訪問者通過使用html5 input [type = file]元素捕獲照片。然後,我將顯示它在網絡上進行預覽,然後訪問者可以選擇將照片上傳到我的服務器用於其他目的(即:上傳到FB)如何在移動網絡瀏覽器中使用輸入[type ='file']捕獲照片後在畫布中以正確的方向繪製照片?
我在拍照時發現照片的方向有問題使用我的iPhone和垂直舉行。照片是在一個正確的方向標籤。 但是,當我嘗試使用drawImage()方法將其繪製到畫布中時,它會繪製90度旋轉。
我試圖以4個方向拍照,只有其中一個可以在畫布上繪製正確的圖像,其他人可以旋轉甚至翻轉。
嗯,我很困惑,以獲得正確的方向來解決這個問題... 感謝您的幫助......
這裏是我的代碼,其中大部分來自MDN
複製<div class="container">
<h1>Camera API</h1>
<section class="main-content">
<p>A demo of the Camera API, currently implemented in Firefox and Google Chrome on Android. Choose to take a picture with your device's camera and a preview will be shown through createObjectURL or a FileReader object (choosing local files supported too).</p>
<p>
<form method="post" enctype="multipart/form-data" action="index.php">
<input type="file" id="take-picture" name="image" accept="image/*">
<input type="hidden" name="action" value="submit">
<input type="submit" >
</form>
</p>
<h2>Preview:</h2>
<div style="width:100%;max-width:320px;">
<img src="about:blank" alt="" id="show-picture" width="100%">
</div>
<p id="error"></p>
<canvas id="c" width="640" height="480"></canvas>
</section>
</div>
<script>
(function() {
var takePicture = document.querySelector("#take-picture"),
showPicture = document.querySelector("#show-picture");
if (takePicture && showPicture) {
// Set events
takePicture.onchange = function (event) {
showPicture.onload = function(){
var canvas = document.querySelector("#c");
var ctx = canvas.getContext("2d");
ctx.drawImage(showPicture,0,0,showPicture.width,showPicture.height);
}
// Get a reference to the taken picture or chosen file
var files = event.target.files,
file;
if (files && files.length > 0) {
file = files[0];
try {
// Get window.URL object
var URL = window.URL || window.webkitURL;
// Create ObjectURL
var imgURL = URL.createObjectURL(file);
// Set img src to ObjectURL
showPicture.src = imgURL;
// Revoke ObjectURL
URL.revokeObjectURL(imgURL);
}
catch (e) {
try {
// Fallback if createObjectURL is not supported
var fileReader = new FileReader();
fileReader.onload = function (event) {
showPicture.src = event.target.result;
};
fileReader.readAsDataURL(file);
}
catch (e) {
// Display error message
var error = document.querySelector("#error");
if (error) {
error.innerHTML = "Neither createObjectURL or FileReader are supported";
}
}
}
}
};
}
})();
</script>
它工作完美。非常感謝。 fileReader的讀取方法需要從readAsDataURL(文件)更改爲readAsBinaryString(文件) –
感謝您的偉大答案,本!但是,我不太確定輪換是否正確。請參閱下面的答案。 – gburning
@gburning我確實同意你的回答比較好,涵蓋了大多數場景!請使用下面的答案而不是我的答案。 –