FaceRecognition.vue 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. <template>
  2. <div>
  3. <video
  4. id="video"
  5. ref="video"
  6. :width="width"
  7. :height="height"
  8. autoplay
  9. >
  10. </video>
  11. <div
  12. v-if="showRecognizeButton"
  13. style="position: absolute; width: 400px; text-align: center; margin-top: -50px; color: #232323;"
  14. >
  15. <button
  16. class="verify-button"
  17. @click="snap"
  18. :disabled="disableSnap"
  19. >{{msg}}</button>
  20. </div>
  21. </div>
  22. </template>
  23. <script>
  24. import { mapState as globalMapState } from "vuex";
  25. import { createNamespacedHelpers } from "vuex";
  26. const { mapState, mapMutations } = createNamespacedHelpers("examingHomeModule");
  27. export default {
  28. name: "FaceRecognition",
  29. data() {
  30. return { disableSnap: false, msg: "开始识别" };
  31. },
  32. props: {
  33. width: String,
  34. height: String,
  35. showRecognizeButton: Boolean,
  36. closeCamera: Boolean // optional
  37. },
  38. async mounted() {
  39. this.openCamera();
  40. },
  41. watch: {
  42. snapNow(val) {
  43. if (val) {
  44. if (!this.lastSnapTime || Date.now() - this.lastSnapTime > 60 * 1000) {
  45. this.lastSnapTime = Date.now();
  46. this.snapTimer();
  47. } else {
  48. this.serverLog(
  49. "debug/S-002001",
  50. "上次的抓拍未超过1分钟,本次抓拍指令取消"
  51. );
  52. this.decreaseSnapCount();
  53. }
  54. this.toggleSnapNow();
  55. }
  56. },
  57. closeCamera: function(newValue) {
  58. if (newValue) {
  59. console.log("关闭摄像头");
  60. this.$refs.video.srcObject.getTracks().forEach(function(track) {
  61. track.stop();
  62. });
  63. } else {
  64. this.openCamera();
  65. }
  66. }
  67. },
  68. beforeDestroy() {
  69. this.$refs.video.srcObject.getTracks().forEach(function(track) {
  70. track.stop();
  71. });
  72. },
  73. methods: {
  74. ...mapMutations(["toggleSnapNow", "decreaseSnapCount"]),
  75. async openCamera() {
  76. const video = this.$refs.video;
  77. if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
  78. try {
  79. console.log("启动摄像头");
  80. const stream = await navigator.mediaDevices.getUserMedia({
  81. video: {
  82. facingMode: "user"
  83. // width: 400,
  84. // height: this.showRecognizeButton ? 300 : 250
  85. }
  86. });
  87. if (stream) {
  88. video.srcObject = stream;
  89. try {
  90. await video.play();
  91. } catch (error) {
  92. this.$Message.error({
  93. content: "摄像头没有正常启用",
  94. duration: 5
  95. });
  96. }
  97. } else {
  98. this.$Message.error("没有可用的视频流");
  99. }
  100. } catch (error) {
  101. console.log(error);
  102. this.$Message.error("无法启用摄像头");
  103. }
  104. } else {
  105. this.$Message.error("没有找到可用的摄像头");
  106. }
  107. },
  108. async snapTimer() {
  109. try {
  110. const examRecordDataId = this.$route.params.examRecordDataId;
  111. const captureBlob = await this.getSnapShot();
  112. // console.log(captureBlob.size);
  113. this.serverLog("debug/S-004001", "抓拍照片的大小:" + captureBlob.size);
  114. const captureFilePath = await this.uploadToServer(captureBlob);
  115. await this.faceCompare(captureFilePath, examRecordDataId);
  116. } catch (error) {
  117. // FIXME: more processing
  118. console.log("定时抓拍流程失败");
  119. } finally {
  120. const video = this.$refs.video;
  121. video && video.play();
  122. this.decreaseSnapCount();
  123. }
  124. },
  125. async snap() {
  126. // TODO: chrome 70. FaceDetector检测人脸
  127. // var canvas = document.createElement("canvas");
  128. // canvas.width = 220;
  129. // canvas.height = 165;
  130. // var context = canvas.getContext("2d");
  131. // context.drawImage(this.$refs.video, 0, 0, 220, 165);
  132. // var f = new FaceDetector();
  133. // const v = await f.detect(canvas);
  134. // console.log(v);
  135. // return;
  136. this.$Message.destroy();
  137. try {
  138. this.disableSnap = true;
  139. // console.log("disableSnap: " + this.disableSnap);
  140. // await new Promise(resolve =>
  141. // setTimeout(() => {
  142. // console.log(new Date());
  143. // resolve();
  144. // }, 3000)
  145. // );
  146. // return;
  147. // if(this.disableSnap) return; // 避免界面没有更新。
  148. this.msg = "拍照中...";
  149. const captureBlob = await this.getSnapShot();
  150. this.msg = "上传照片中...";
  151. const captureFilePath = await this.uploadToServer(captureBlob);
  152. this.msg = "人脸比对中...";
  153. await this.faceCompareSync(captureFilePath);
  154. } catch (error) {
  155. // FIXME: more processing
  156. console.log("同步照片比对流程失败");
  157. throw error;
  158. } finally {
  159. const video = this.$refs.video;
  160. video && video.play();
  161. this.msg = "开始识别";
  162. this.disableSnap = false;
  163. }
  164. },
  165. async getSnapShot() {
  166. return new Promise((resolve, reject) => {
  167. const video = this.$refs.video;
  168. if (video.readyState !== 4 || !video.srcObject.active) {
  169. this.$Message.error({ content: "摄像头没有正常启用", duration: 5 });
  170. reject("摄像头没有正常启用");
  171. this.logout();
  172. return;
  173. }
  174. video.pause();
  175. var canvas = document.createElement("canvas");
  176. canvas.width = 220;
  177. canvas.height = 165;
  178. var context = canvas.getContext("2d");
  179. context.drawImage(video, 0, 0, 220, 165);
  180. canvas.toBlob(resolve, "image/jpeg", 0.95);
  181. });
  182. },
  183. async uploadToServer(captureBlob) {
  184. //保存抓拍照片到服务器
  185. // var fileName = new Date().getTime() + ".png";
  186. // var fileUrl = "/api/exchange/inner/upyun/put/capturePhoto/" + fileName;
  187. var fileUrl = "/api/exchange/inner/upyun/put/capturePhoto/jpg";
  188. let resultUrl;
  189. try {
  190. const res = await this.$http.put(fileUrl, captureBlob, {
  191. headers: {
  192. "Content-Type": "image/jpg"
  193. }
  194. });
  195. resultUrl = res.data;
  196. } catch (e) {
  197. console.log(e);
  198. this.$Message.error("保存抓拍照片到服务器失败!");
  199. throw "保存抓拍照片到服务器失败!";
  200. }
  201. // let UPYUN_URL;
  202. // try {
  203. // UPYUN_URL = (await this.$http.get("/api/ecs_oe_student_face/upyun"))
  204. // .data.downloadPrefix;
  205. // } catch (error) {
  206. // this.$Message.error("获取照片下载前缀失败!");
  207. // throw "获取照片下载前缀失败!";
  208. // }
  209. return resultUrl;
  210. },
  211. async faceCompareSync(captureFilePath) {
  212. try {
  213. const res = await this.$http.post(
  214. "/api/ecs_oe_student_face/examCaptureQueue/compareFaceSync?fileUrl=" +
  215. captureFilePath
  216. );
  217. // TODO: 识别成功、失败的通知或跳转
  218. this.$emit("on-recognize-result", {
  219. error: null,
  220. pass: res.data.isPass,
  221. stranger: res.data.isStranger
  222. });
  223. } catch (e) {
  224. console.log(e);
  225. // this.$Message.error(e.message);
  226. throw "同步照片比较失败!";
  227. }
  228. },
  229. async faceCompare(captureFilePath, examRecordDataId) {
  230. try {
  231. const res = await this.$http.post(
  232. "/api/ecs_oe_student_face/examCaptureQueue/uploadExamCapture?fileUrl=" +
  233. captureFilePath +
  234. "&examRecordDataId=" +
  235. examRecordDataId
  236. );
  237. const fileName = res.data;
  238. try {
  239. await this.showSnapResult(fileName, examRecordDataId);
  240. } catch (error) {
  241. this.$Message.error("设置获取抓拍结果失败!");
  242. }
  243. } catch (e) {
  244. console.log(e);
  245. this.$Message.error(e.message);
  246. throw "异步比较抓拍照片失败";
  247. }
  248. },
  249. async showSnapResult(fileName, examRecordDataId) {
  250. if (!fileName) return; // 交卷后提交照片会得不到照片名称
  251. try {
  252. // 获取抓拍结果
  253. const snapRes =
  254. (await this.$http.get(
  255. "/api/ecs_oe_student_face/examCaptureQueue/getExamCaptureResult?fileName=" +
  256. fileName +
  257. "&examRecordDataId=" +
  258. examRecordDataId
  259. )).data || {};
  260. if (this.$route.name !== "OnlineExamingHome") {
  261. // 非考试页,不显示结果,也不继续查询
  262. return;
  263. }
  264. if (snapRes.isCompleted) {
  265. if (snapRes.isStranger) {
  266. this.$Message.error({
  267. content: "请独立完成考试",
  268. duration: 5,
  269. closable: true
  270. });
  271. } else if (!snapRes.isPass) {
  272. this.$Message.error({
  273. content: "请调整坐姿,诚信考试",
  274. duration: 5,
  275. closable: true
  276. });
  277. }
  278. } else {
  279. setTimeout(
  280. this.showSnapResult.bind(this, fileName, examRecordDataId),
  281. 30 * 1000
  282. );
  283. }
  284. } catch (e) {
  285. console.log(e);
  286. if (this.$route.name !== "OnlineExamingHome") {
  287. // 非考试页,不显示结果,也不继续查询
  288. return;
  289. }
  290. this.$Message.error(e.message);
  291. throw e.message;
  292. }
  293. }
  294. },
  295. computed: {
  296. ...globalMapState(["user"]),
  297. ...mapState(["snapNow"])
  298. }
  299. };
  300. </script>
  301. <style scoped>
  302. .verify-button {
  303. font-size: 16px;
  304. background-color: #ffcc00;
  305. display: inline-block;
  306. padding: 6px 16px;
  307. border-radius: 6px;
  308. }
  309. .verify-button:hover {
  310. color: #444444;
  311. cursor: pointer;
  312. }
  313. </style>