今天,我主要尝试了通过摄像头拍照并保存在本地指定文件。
参考:百度文心一言的回复。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <title>获取摄像头画面并拍照</title> </head> <body> <form id="form" action="test0118-2.jsp" method="post"> <input type="hidden" id="base64Image" name="base64Image"> </form> <video id="video" width="640" height="480" style="border: 1px solid #000;" autoplay></video> <canvas id="canvas" style="display: none;" width="640" height="480"></canvas> <img id="photo" style="width: 640px; height: 480px; border: 1px solid #000;" width="640" height="480"> <button id="snap">拍照</button> <button id="submit">提交图片</button> <script> const video = document.getElementById('video'); const canvas = document.getElementById('canvas'); const context = canvas.getContext('2d'); const snap = document.getElementById('snap'); const photo = document.getElementById('photo'); const base64Image = document.getElementById('base64Image'); const form = document.getElementById('form'); navigator.mediaDevices.getUserMedia({ video: true }) .then(stream => { video.srcObject = stream; video.play(); }) .catch(error => { console.error('无法获取摄像头:' + error); }); snap.addEventListener('click', () => { context.drawImage(video, 0, 0, 640, 480); const dataURL = canvas.toDataURL('image/png'); photo.src = dataURL; //photo.style.display = 'block'; }); document.getElementById('submit').addEventListener('click', () => { // 提交图片的代码部分开始 const photo = document.getElementById('photo'); if (photo.src!='') { const imageUrl = photo.src; // 获取图片的 DataURL 或 URL base64Image.value=imageUrl; form.submit(); } else { alert('请先拍照!'); } }); </script> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <title></title> </head> <body> <% String base64Image = request.getParameter("base64Image").split("base64,")[1]; String path = test0113.Base64ToImage.test(base64Image); out.print(path); %> </body> </html>
标签:2024.1,canvas,const,photo,笔记,getElementById,video,18,document From: https://www.cnblogs.com/zhangxutong/p/17972835