翻譯|使用教程|編輯:楊鵬連|2020-07-23 14:54:51.717|閱讀 479 次
概述:網絡攝像頭使用戶可以實時捕獲圖像和視頻流。它通常內置于筆記本電腦中或通過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@fc6vip.cn
文章轉載自: