创建一个能够获取摄像头并拍照上传到PHP服务器的HTML页面
以下是一个简单的HTML页面,使用JavaScript和Web API来访问用户的摄像头,并将拍摄的照片上传到一个PHP服务器。
HTML 页面 (index.html
):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Camera Photo Upload</title>
</head>
<body>
<video id="video" width="640" height="480" autoplay></video>
<button id="snap">Snap Photo</button>
<canvas id="canvas" width="640" height="480"></canvas>
<script>
const video = document.getElementById('video');
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
const snap = document.getElementById('snap');
// 启动摄像头
if (navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({ video: true })
.then(function (stream) {
video.srcObject = stream;
})
.catch(function (err) {
console.error("Error accessing the camera: " + err);
});
} else {
alert("Your browser does not support the navigator.mediaDevices.getUserMedia API");
}
// 拍照
snap.addEventListener('click', function () {
context.drawImage(video, 0, 0, 640, 480); // 绘制到canvas
// 将canvas转换为base64图片
const base64Image = canvas.toDataURL("image/png");
// 发送到PHP服务器
const xhr = new XMLHttpRequest();
xhr.open('POST', 'upload.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function () {
if (this.status == 200) {
console.log('Photo uploaded successfully');
} else {
console.error('Error uploading the photo');
}
};
xhr.send('photo=' + encodeURIComponent(base64Image));
});
</script>
</body>
</html>
PHP 服务器端代码 (upload.php
):
<?php
if (isset($_POST['photo'])) {
$base64Image = $_POST['photo'];
$image = base64_decode(explode(',', $base64Image)[1]);
$filename = 'photo.png';
if (file_put_contents($filename, $image)) {
// 文件保存成功
echo "Success";
} else {
// 文件保存失败
echo "Failed";
}
} else {
// 没有接收到图片数据
echo "No photo data received";
}
?>
确保你的服务器配置允许通过POST方法上传文件,并且\`u
评论已关闭