如何通过浏览器访问网络摄像头?
HTML5 为Web开发人员提供了JavaScript API MediaDevices.getUserMedia()。在本指南中,我们将使用Dynamic Web TWAIN SDK网络摄像头插件构建一个在线网络摄像头演示。
为什么选择Dynamic Web TWAIN网络摄像头附加组件
为什么有免费的选项时考虑付费选项?我们列出了HTML5不提供的网络摄像头附加组件的一些高级功能。
- 浏览器兼容性 – HTML5与某些较旧的浏览器不兼容,例如Internet Explorer 8。
- 精确控制网络摄像头 –您可以完全控制摄像机,例如摇摄,倾斜,滚动,变焦,曝光,光圈和自动对焦。
- 分辨率设置 –使用GetResolution(),SetResolution()API获取和设置分辨率
- 扫描仪质量的图像 – Dynamsoft提供了多种图像增强技术来帮助用户生成高质量的图像,包括自动边界检测,噪声消除和透视校正。
- 上载到服务器 – SDK提供了内置方法,供用户将图像上载到服务器端。
如果您要构建一个健壮的,功能齐全的企业级应用程序,那么选择Dynamsoft的SDK这样的商业SDK将会为您带来巨大的投资回报。
关于Dynamic Web TWAIN网络摄像头附加组件
Dynamic Web TWAIN网络摄像头附加组件使Web开发人员可以使用JavaScript代码从网络摄像头捕获图像。网络摄像头SDK支持在Windows,macOS和Linux上的所有主流浏览器中嵌入视频流。Dynamic Web TWAIN还支持从移动相机捕获图像。
设备支持
- 兼容UVC(USB视频类)的网络摄像头
- 内置笔记本电脑摄像头
- 文件相机
浏览器支持(跨平台)
- Internet Explorer 8+
- 边缘
- 火狐浏览器
- 铬
服务器端支持
- Web服务器:Nginx,IIS,Tomcat,Apache等。
- 操作系统:Linux,Windows等。
- 语言:ASP.NET(C#/ VB.NET),PHP,JSP等
如何逐步使用网络摄像头附加组件
在这里,我们将向您展示如何使用SDK轻松地将HTML网页中的网络摄像头捕获和视频预览集成。首先,下载Dynamic Web TWAIN并将Resources文件夹复制到您的项目中。然后创建一个新的网页HelloWorld.html。
步骤1添加参考
<head>
<script src="Resources/dynamsoft.webtwain.initiate.js"> </script>
<script src="Resources/dynamsoft.webtwain.config.js"> </script>
<script src="Resources/addon/dynamsoft.webtwain.addon.webcam.js"> </script>
</head>
步骤#2创建一个容器
<div id="dwtcontrolContainer"></div>
步骤#3输入一个下拉列表和两个按钮
步骤#4通过调用Dynamsoft_OnReady()初始化对象
<script type="text/javascript"> var DWObject; var isVideoOn = true; function Dynamsoft_OnReady() { DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); // Get the Dynamic Web TWAIN object that is embedded in the div with id 'dwtcontrolContainer' if (DWObject) { DWObject.Width = 504; DWObject.Height = 600; var arySource = DWObject.Addon.Webcam.GetSourceList(); for (var i = 0; i < arySource.length; i++) document.getElementById("source").options.add(new Option(arySource[i], arySource[i]), i); // Get Webcam Source names and put them in a drop-down box } document.getElementById('source').onchange = function () { DWObject.Addon.Webcam.SelectSource(document.getElementById("source").options[document.getElementById("source").selectedIndex].value); SetIfWebcamPlayVideo(true); } document.getElementById('source').onchange(); } </script>
步骤#5控制网络摄像头
您可以使用以下API播放和停止视频流:DWObject.Addon.Webcam.StopVideo()和DWObject.Addon.Webcam.PlayVideo(DWObject,80,function(){})。
function enableButton(element) { element.style.backgroundColor = ""; element.disabled = ""; } function disableButton(element) { element.style.backgroundColor = "#aaa"; element.disabled = "disabled"; } function SetIfWebcamPlayVideo(bShow) { if (bShow) { DWObject.Addon.Webcam.StopVideo(); DWObject.Addon.Webcam.PlayVideo(DWObject, 80, function () { }); isVideoOn = true; enableButton(document.getElementById("btn-grab")); document.getElementById("btn-switch").value = "Hide Video"; } else { DWObject.Addon.Webcam.StopVideo(); isVideoOn = false; disableButton(document.getElementById("btn-grab")); document.getElementById("btn-switch").value = "Show Video"; } } function SwitchViews() { if (isVideoOn == false) { // continue the video SetIfWebcamPlayVideo(true); } else { // stop the video SetIfWebcamPlayVideo(false); } }
步骤#6通过使用CaptureImage()捕获图像
function CaptureImage() { if (DWObject) { var funCaptureImage = function () { SetIfWebcamPlayVideo(false); }; DWObject.Addon.Webcam.CaptureImage(funCaptureImage, funCaptureImage); } }
如何同时从扫描仪和网络摄像头捕获图像
文档/记录管理应用程序通常需要通过Web浏览器从扫描仪和网络摄像机捕获图像。您可以使用Dynamic Web TWAIN核心SDK和网络摄像头附加组件轻松实现此目的。
让我们继续在HelloWorld.html网页上进行工作。
步骤#1重写函数Dynamsoft_OnReady()
要控制TWAIN扫描器,请调用API:DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer')
Dynamsoft.WebTwainEnv.AutoLoad = false; Dynamsoft.WebTwainEnv.RegisterEvent('OnWebTwainReady', Dynamsoft_OnReady); // Register OnWebTwainReady event. This event fires as soon as Dynamic Web TWAIN is initialized and ready to be used var webCamStartingIndex;//This is used to separate scanners and webcams var DWObject; var isVideoOn = true; function Dynamsoft_OnReady() { DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); // Get the Dynamic Web TWAIN object that is embedded in the div with id 'dwtcontrolContainer' if (DWObject) { DWObject.Width = 504; DWObject.Height = 600; document.getElementById('source').options.length = 0; var count = DWObject.SourceCount; for (var i = 0; i < count; i++) { document.getElementById('source').options.add(new Option(DWObject.GetSourceNameItems(i), i)); } webCamStartingIndex = i; var arySource = DWObject.Addon.Webcam.GetSourceList(); for (var i = 0; i < arySource.length; i++) document.getElementById("source").options.add(new Option(arySource[i], arySource[i]), i + webCamStartingIndex); // Get Webcam Source names and put them in a drop-down box } document.getElementById('source').onchange = function () { if (document.getElementById('source').selectedIndex < webCamStartingIndex) { if (arySource.length > 0) DWObject.Addon.Webcam.StopVideo(); isVideoOn = false; document.getElementById("btn-grab").style.backgroundColor = ""; document.getElementById('btn-grab').value = 'Acquire From a Scanner'; document.getElementById("btn-switch").style.display = 'none'; } else { DWObject.Addon.Webcam.SelectSource(document.getElementById("source").options[document.getElementById("source").selectedIndex].value); SetIfWebcamPlayVideo(true); document.getElementById('btn-grab').value = 'Acquire From a Webcam'; document.getElementById("btn-switch").style.display = ''; } document.getElementById("btn-grab").disabled = ""; } document.getElementById('source').onchange(); }
步骤#2捕获图像
function CaptureImage() { if (DWObject) { if (document.getElementById('source').selectedIndex < webCamStartingIndex) { DWObject.IfShowUI = true; DWObject.IfDisableSourceAfterAcquire = true; DWObject.SelectSourceByIndex(document.getElementById('source').selectedIndex); DWObject.CloseSource(); DWObject.OpenSource(); DWObject.AcquireImage(); } else { var funCaptureImage = function () { SetIfWebcamPlayVideo(false); }; DWObject.Addon.Webcam.CaptureImage(funCaptureImage, funCaptureImage); } } }
如何将扫描的图像上传到服务器端
步骤#1添加用于上传的按钮
步骤#2上传图片
准备好图像后,您可以通过调用HTTPUploadThroughPost()将其上传到Web服务器。
function upload() { if (DWObject) { // If no image in buffer, return the function if (DWObject.HowManyImagesInBuffer == 0) return; var strHTTPServer = location.hostname; //The name of the HTTP server. For example: "www.dynamsoft.com"; var CurrentPathName = unescape(location.pathname); var CurrentPath = CurrentPathName.substring(0, CurrentPathName.lastIndexOf("/") + 1); var strActionPage = CurrentPath + "filename"; // Action page DWObject.IfSSL = false; // Set whether SSL is used DWObject.HTTPPort = location.port == "" ? 80 : location.port; var Digital = new Date(); var uploadfilename = Digital.getMilliseconds(); // Uses milliseconds according to local time as the file name //Upload image in JPEG DWObject.HTTPUploadThroughPost(strHTTPServer, DWObject.CurrentImageIndexInBuffer, strActionPage, uploadfilename + ".jpg", OnHttpUploadSuccess, OnHttpUploadFailure); } }
该SDK支持ASP.NET(C#/ VB.NET),PHP,JSP,ASP等,以在服务器端接收图像数据。
PHP代码
JSP代码
<%@page import="java.util.*,java.io.File,java.io.FileOutputStream,org.apache.commons.fileupload.FileUpload,org.apache.commons.fileupload.FileItem,org.apache.commons.fileupload.disk.DiskFileItemFactory,org.apache.commons.fileupload.servlet.ServletFileUpload,sun.misc.BASE64Decoder"%> <%@page contentType="application/json; charset=utf-8" %> <%@page language="java" %> <% String strJson = "{\"success\":false}"; try{ // get more info from: http://commons.apache.org/proper/commons-fileupload/ DiskFileItemFactory factory = new DiskFileItemFactory(); ServletContext servletContext = this.getServletConfig().getServletContext(); File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir"); factory.setRepository(repository); ServletFileUpload upload = new ServletFileUpload(factory); List items = upload.parseRequest(request); Iterator iter = items.iterator(); String fileName = null; String tempFileName = null; String contentType = null; FileItem fileItem = null; while (iter.hasNext()) { FileItem item = iter.next(); String fieldName = item.getFieldName(); if(fieldName.equals("fileName")){ fileName = item.getString(); }else if(fieldName.equals("RemoteFile")){ tempFileName = item.getName(); contentType = item.getContentType(); fileItem = item; } } if(fileName == null || fileName.isEmpty()){ fileName = tempFileName; } String path = application.getRealPath(request.getServletPath()); String dir = new java.io.File(path).getParent(); String filePath = dir + "/UploadedImages/" + fileName; File file = new File(filePath); if(!file.getParentFile().exists()){ file.getParentFile().mkdir(); } if(!file.exists()){ file.createNewFile(); } if(!contentType.contains("text/plain")){ fileItem.write(file); }else{ String base64Str = fileItem.getString(); byte[] b = null; b = (new BASE64Decoder()).decodeBuffer(base64Str); FileOutputStream fileOutStream = new FileOutputStream(file); fileOutStream.write(b); fileOutStream.flush(); fileOutStream.close(); } strJson = "{\"success\":true, \"fileName\":\"" + fileName + "\"}"; } catch(Exception ex){ strJson = "{\"success\":false, \"error\": \"" + ex.getMessage().replace("\\", "\\\\") + "\"}"; } out.clear(); out.write(strJson); out.close(); %>
ASP.NET(C#)代码
<%@ Page Language="C#" %> <%@ Import Namespace="System.IO" %> <% string strJson = "{\"success\":false}"; try { HttpPostedFile file = Request.Files["RemoteFile"]; string fileName = Request.Form["fileName"]; if (string.IsNullOrEmpty(fileName)) fileName = file.FileName; string filePath = Server.MapPath(".") + "\\UploadedImages\\" + fileName; if (!file.ContentType.Contains("text/plain")) { file.SaveAs(filePath); } else { Stream fs = file.InputStream; byte[] base64Bytes = new byte[fs.Length]; fs.Read(base64Bytes, 0, (int) fs.Length); StringBuilder base64Str = new StringBuilder(); foreach (byte b in base64Bytes) { base64Str.Append((char) b); } File.WriteAllBytes(filePath, Convert.FromBase64String(base64Str.ToString())); } strJson = "{\"success\":true, \"fileName\":\"" + fileName + "\"}"; } catch (Exception ex) { strJson = "{\"success\":false, \"error\": \"" + ex.Message.Replace("\\", "\\\\") + "\"}"; } Response.Clear(); Response.ContentType = "application/json; charset=utf-8"; Response.Write(strJson); Response.End(); %>
来源:oschina
链接:https://my.oschina.net/u/4587239/blog/4455954