RF: http://blog.csdn.net/lulu11231123/article/details/52181354
前台:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="../resource/js/jquery/jquery-2.2.3.js"></script>
</head>
<body>
<div id="contentHolder">
<video id="video" width="320" height="320" autoplay></video>
<button id="picture" style="display:block" >拍照</button>
<canvas style="display:block" id="canvas" width="320" height="320"></canvas>
<button id="sc" style="display:block" >上传</button>
</div>
<script>
navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia;
if (navigator.getUserMedia) {
navigator.getUserMedia({ audio: true, video: { width: 320, height: 320 } },
function(stream) {
var video = document.getElementById("video");
video.src = window.URL.createObjectURL(stream);
video.onloadedmetadata = function(e) {
console.log('nihao44eee4aaaaddda');
video.play();
};
},
function(err) {
console.log("The following error occurred: " + err.name);
}
);
} else {
console.log("getUserMedia not supported");
}
document.getElementById("picture").addEventListener("click", function () {
debugger;
var context = document.getElementById("canvas").getContext("2d");
context.drawImage(video, 0, 0, 320, 320);
});
document.getElementById("sc").addEventListener("click", function () {
var imgData=document.getElementById("canvas").toDataURL("image/png");
var data=imgData.substr(22);
debugger;
console.log(data);
$.post('../upload/sc',{'sj':data});
});
</script>
</body>
</html>
后台:
@RequestMapping(value = "/sc", method = RequestMethod.POST) @ResponseBody public String sc(HttpServletResponse response,HttpServletRequest request,String sj) throws Exception { GenerateImage(sj); return "sxt"; } // base64字符串转化成图片 public static boolean GenerateImage(String imgStr) { // 对字节数组字符串进行Base64解码并生成图片 if (imgStr == null) // 图像数据为空 return false; try { // Base64解码 BASE64Decoder decoder = new BASE64Decoder(); byte[] bytes = decoder.decodeBuffer(imgStr); // byte[] bytes = Base64.decodeBase64(imgStr); //或用Base64 解 org.apache.commons.codec.binary.Base64; for (int i = 0; i <bytes.length; ++i) { if (bytes[i] < 0) {// 调整异常数据 bytes[i] += 256; } }// 生成jpeg图片 String imgFilePath = "F:/test22.png";// 新生成的图片 OutputStream out = new FileOutputStream(imgFilePath); out.write(bytes); out.flush(); out.close(); return true; } catch (Exception e) { return false; } }