话不多说直接上代码:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>面部信息采集页面</title>
<script type="text/javascript" th:src="@{/js/jquery.min.js}"></script>
<style>
.takePhoto {
margin-left: 620px;
margin-top: -300px;
heigth: 100px;
width: 50px;
border-radius: 50px;
}
.retakePhoto {
margin-left: 100px;
margin-top: -300px;
heigth: 100px;
width: 50px;
border-radius: 50px;
}
</style>
</head>
<body>
<form th:action="@{/uploadImage}" th:object="${imageForm}" method="post">
<input type="hidden" id="imageUrl" th:field="${imageForm.imageBase64}">
<div>
<video id="video" width="400" height="300"></video>
<canvas id="canvas" width="400" height="300" style="display: none;"></canvas>
<img id="img" src="" style="display: none;">
</div>
<button id="take" class="takePhoto">拍摄</button>
<button id="retake" class="retakePhoto">重拍</button>
<input type="submit" class="retakePhoto" value="提交">
</form>
<script>
// 将jQuery对象转为dom对象使用[]
var video = $('#video')[0];
var canvas = $('#canvas')[0];
var img = $('#img')[0];
//媒体对象
navigator.getMedia = navigator.getUserMedia
|| navagator.webkitGetUserMedia || navigator.mozGetUserMedia
|| navigator.msGetUserMedia;
navigator.getMedia({
video : true, // 使用摄像头
audio : false // 不使用收音设备
}, function(stream) {
// 部分浏览器video.src方法已经失效,使用下面方法实现兼容
try {
video.srcObject = stream;
} catch (error) {
video.src = window.URL.createObjectURL(stream);
}
video.play();
}, function(error) {
// 调用摄像头失败
alert("摄像头调用失败");
});
$("#take").on('click', function(e) {
// 阻止button的默认提交表单事件
e.preventDefault();
$("#img").css("display", "block");
// 绘制canvas图形
canvas.getContext('2d').drawImage(video, 0, 0, 400, 300);
// 把canvas图像转为img图片
img.src = canvas.toDataURL("image/png");
$("#imageUrl").val(img.src);
$("#video").css("display", "none");
});
$("#retake").on("click", function(e) {
e.preventDefault();
$("#img").css("display", "none");
$("#video").css("display", "block");
img.src = "";
});
</script>
</body>
</html>
后台代码:
@PostMapping(value = "/uploadImage")
public String uploadImage(ImageForm imageForm, Model model) {
// 这之间可以加入将base64数据写入数据库的操作
model.addAttribute("imageForm", imageForm);
// 跳转到图像确认画面
return "verifyPhoto";
}