訪問者が html5 input[type=file] 要素を使用して写真をキャプチャできるようにする単純な Web アプリをモバイルで作成しています。次に、プレビュー用にウェブ上に表示し、訪問者は他の目的で写真をサーバーにアップロードすることを選択できます (例: FB にアップロード)。
iPhone で写真を縦に持って撮影すると、写真の向きに問題があることがわかりました。写真はタグで正しい向きになっています。しかし、drawImage()メソッドでキャンバスに描画しようとすると、90度回転して描画されてしまいます。
私は 4 つの向きで写真を撮ろうとしましたが、そのうちの 1 つだけがキャンバスに正しい画像を描くことができ、他の向きは回転したり、逆さまになったりします。
さて、私はこの問題を解決するための正しい向きを取得するのに混乱しています...助けてくれてありがとう...
これが私のコードです。主に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>