原理:调出摄像头,拍照保存到画布,将图片URi传送到后台
前端代码(Index.cshtml):
<style>
#video,#canvas {display: block;margin:1em auto;width:180px;height:180px;}
#snap { display: block;margin:0 auto;width:80%;height:2em; }
</style>
<div class="container">
<video id="video" autoplay></video>
<button id="snap">点击拍照</button>
<canvas id="canvas"></canvas>
</div>
<script>
window.addEventListener("DOMContentLoaded", function () {
try { document.createElement("canvas").getContext("2d"); } catch (e) { alert("not support canvas!") }
var video = document.getElementById("video"),
canvas = document.getElementById("canvas"),
context = canvas.getContext("2d");
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
if (navigator.getUserMedia)
navigator.getUserMedia(
{ "video": true },
function (stream) {
if (video.mozSrcObject !== undefined)video.mozSrcObject = stream;
else video.src = ((window.URL || window.webkitURL || window.mozURL || window.msURL) && window.URL.createObjectURL(stream)) || stream;
video.play();
},
function (error) {
//if(error.PERMISSION_DENIED)console.log("用户拒绝了浏览器请求媒体的权限",error.code);
//if(error.NOT_SUPPORTED_ERROR)console.log("当前浏览器不支持拍照功能",error.code);
//if(error.MANDATORY_UNSATISFIED_ERROR)console.log("指定的媒体类型未接收到媒体流",error.code);
alert("Video capture error: " + error.code);
}
);
else alert("Native device media streaming (getUserMedia) not supported in this browser");
$('#snap').on('click', function () {
context.drawImage(video, 0, 0, canvas.width = video.videoWidth, canvas.height = video.videoHeight);
$.post('/home/index', { "img": canvas.toDataURL().substr(22) }, function (data, status) {
alert(status!="success"?"图片处理出错!":data== "yes"?"图片上传完成!":data);
}, "text");
});
}, false);
</script>
后台代码(HomeController.cs):
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web.Mvc;
namespace WebFrame.Controllers
{
public class HomeController : Controller
{
public ActionResult Index() { return View(); }
[HttpPost]
public ActionResult Index(FormCollection form)
{
try
{
byte[] imgBytes = Convert.FromBase64String(form["img"]);
Stream stream = new MemoryStream(imgBytes);
Image imgae = Image.FromStream(stream);
imgae.Save(HttpContext.Server.MapPath("~/") + Guid.NewGuid().ToString() + ".jpg", ImageFormat.Jpeg);
return Content("yes");
}
catch (Exception e) { return Content(e.Message); }
}
}
}
效果如下图:
附上Demo下载地址: 基于html5、JS实现的拍照上传图片(免积分)