翻译|使用教程|编辑:杨鹏连|2020-07-23 14:54:51.717|阅读 389 次
概述:网络摄像头使用户可以实时捕获图像和视频流。它通常内置于笔记本电脑中或通过USB端口物理连接到计算机。网络摄像头可用于许多情况,包括视频电话会议,面部识别,安全监控,计算机视觉和文档扫描。
# 慧都年终大促·界面/图表报表/文档/IDE等千款热门软控件火热促销中 >>
相关链接:
Dynamic Web TWAIN是一个专为Web应用程序设计的TWAIN扫描识别控件。你只需在TWAIN接口写几行代码,就可以用兼容TWAIN的扫描仪扫描文档或从数码相机/采集卡中获取图像。然后用户可以编辑图像并将图像保存为多种格式,用户可保存图像到远程数据库或者SharePoint。该TWAIN控件还支持上传和处理本地图像。
如何通过浏览器访问网络摄像头?
HTML5 为Web开发人员提供了JavaScript API MediaDevices.getUserMedia()。在本指南中,我们将使用Dynamic Web TWAIN SDK网络摄像头插件构建一个在线网络摄像头演示。
为什么选择Dynamic Web TWAIN网络摄像头附加组件为什么有免费的选项时考虑付费选项?我们列出了HTML5不提供的网络摄像头附加组件的一些高级功能。
如果您要构建一个健壮的,功能齐全的企业级应用程序,那么选择Dynamsoft的SDK这样的商业SDK将会为您带来巨大的投资回报。
关于Dynamic Web TWAIN网络摄像头附加组件
Dynamic Web TWAIN网络摄像头附加组件使Web开发人员可以使用JavaScript代码从网络摄像头捕获图像。网络摄像头SDK支持在Windows,macOS和Linux上的所有主流浏览器中嵌入视频流。Dynamic Web TWAIN还支持从移动相机捕获图像。设备支持
服务器端支持
如何逐步使用网络摄像头附加组件
在这里,我们将向您展示如何使用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添加用于上传的按钮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代码
<?php
$strJson = "{\"success\":false}";
try{
$file = $_FILES["RemoteFile"];
$fileName = $_POST["fileName"];
if ($fileName == "" || $fileName == null) $fileName = $file["name"];
$filePath = dirname(__FILE__) . "/upload/";
if (!file_exists($filePath)) {
mkdir($filePath);
}
if (file_exists($filePath . $fileName))
{
$iniNum = 0;
if (strpos($fileName, "(") !== FALSE && strpos($fileName, ")") !== FALSE)
{
$leftPhPos = strrpos($fileName, "(");
$rightPhPos = strrpos($fileName, ")");
if ($leftPhPos < $rightPhPos) {
$numStr = substr($fileName, $leftPhPos + 1, $rightPhPos - $leftPhPos - 1);
if (is_numeric($numStr))
{
$iniNum = intval($numStr);
$fileName = substr($fileName, 0, $leftPhPos) . substr($fileName, $rightPhPos + 1);
}
else {
$iniNum = 0;
}
}
}
$indexPoint = strrpos($fileName, ".");
$str1 = substr($fileName, 0, $indexPoint) . "(";
$str2 = ")" . substr($fileName, $indexPoint);
for ($i = $iniNum; ; ++$i)
{
if (!file_exists($filePath . ($str1 . $i . $str2)))
{
$fileName = $str1 . $i . $str2;
break;
}
}
}
$fileFullPath = $filePath . $fileName;
if(strpos($file["type"], 'text/plain') === false){
move_uploaded_file($file["tmp_name"] , $fileFullPath);
}else{
$file_contents = base64_decode(str_replace(' ', '+', file_get_contents($file['tmp_name'])));
file_put_contents($fileFullPath, $file_contents);
}
$strJson = "{\"success\":true, \"fileName\":\"" . $fileName . "\"}";
}
catch(Exception $ex){
$strJson = "{\"success\":false, \"error\": \"" . ex.Message.Replace("\\", "\\\\") . "\"}";
}
// Response.Clear();
header("Content-Type: application/json; charset=utf-8");
echo $strJson;
?>
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: //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); ListASP.NET(C#)代码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(); %>
<%@ 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(); %>
本站文章除注明转载外,均为本站原创或翻译。欢迎任何形式的转载,但请务必注明出处、不得修改原文相关链接,如果存在内容上的异议请邮件反馈至chenjj@cahobeh.cn
文章转载自: