我想允许用户使用他们的网络摄像头拍照,然后提供将该图片保存到服务器上。
我在aspx中创建了一个测试页面来拍摄照片并将其保存到本地文件夹中,但是我遇到了一些问题。
到目前为止:
- 网络摄像头正在获取视频并在页面的<video>
标签中显示该视频
- 用户从视频流中拍摄照片,并在页面的<canvas>
标签中显示。
但是,我无法将画布中的图片保存到本地文件夹中的文件中。当我单击保存按钮时,没有任何反应。我究竟做错了什么?
<head runat="server">
<title></title>
<script src="script.js"></script>
<link href="Style.css" rel="stylesheet" />
</head>
<body style="text-align:center">
<video id="video" width="320" height="240" autoplay></video>
<button id="btnStart">Film</button>
<button id="btnPhoto">Take a picture</button>
<canvas id="canvas" width="320" height="240"></canvas>
<br />
<br />
<br />
<br />
<button onclick="javascript:UploadPic();return false;">Save</button>
</body>
这是我的javascript代码:
window.onload = function () {
navigator.getUserMedia = (navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
//picture
var canvas = document.getElementById("canvas"),
context = canvas.getContext("2d"),
//film area
video = document.getElementById("video"),
//buttons
btnStart = document.getElementById("btnStart"),
btnPhoto = document.getElementById("btnPhoto"),
//video and audio
videoObj = {
video: true,
audio: false
};
//begin film
btnStart.addEventListener("click", function () {
var localMediaStream;
if (navigator.getUserMedia) {
navigator.getUserMedia(videoObj, function (stream) {
video.src = (navigator.webkitGetUserMedia) ? window.webkitURL.createObjectURL(stream) : stream;
localMediaStream = stream;
if (navigator.mozGetUserMedia) {
video.mozSrcObject = stream;
}
},
function (error) {
console.error("Video capture error: ", error.code);
});
//capture image button
btnPhoto.addEventListener("click", function () {
context.drawImage(video, 0, 0, 320, 240);
});
}
});
};
//Upload da imagem
function UploadPic() {
//Converte a imagem em base64
var Pic = document.getElementById("canvas2").toDataURL("image/jpg");
Pic = Pic.replace(/^data:image\/(png|jpg);base64,/, "")
//Envia a imagem em base64 para o server (pasta local)
$.ajax({
type: 'POST',
url: 'Save_Picture.aspx/UploadPic',
data: '{ "imageData" : "' + Pic + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
alert("Done, Picture Uploaded.");
}
});
}
答案 0 :(得分:0)
检查您的画布ID:
var Pic = document.getElementById("canvas2").toDataURL("image/jpg");
但写成
<canvas id="canvas" width="320" height="240"></canvas>
关于标记
将JS代码更改为:
var Pic = document.getElementById("canvas").toDataURL("image/jpg");