使用Dynamic Web TWAIN從網(wǎng)絡(luò)攝像頭捕獲圖像的綜合指南
Dynamic Web TWAIN是一個(gè)專為Web應(yīng)用程序設(shè)計(jì)的TWAIN掃描識(shí)別控件。你只需在TWAIN接口寫幾行代碼,就可以用兼容TWAIN的掃描儀掃描文檔或從數(shù)碼相機(jī)/采集卡中獲取圖像。然后用戶可以編輯圖像并將圖像保存為多種格式,用戶可保存圖像到遠(yuǎn)程數(shù)據(jù)庫或者SharePoint。該TWAIN控件還支持上傳和處理本地圖像。
點(diǎn)擊下載Dynamic Web TWAIN正式版
如何通過瀏覽器訪問網(wǎng)絡(luò)攝像頭?
HTML5 為Web開發(fā)人員提供了JavaScript API MediaDevices.getUserMedia()。在本指南中,我們將使用Dynamic Web TWAIN SDK網(wǎng)絡(luò)攝像頭插件構(gòu)建一個(gè)在線網(wǎng)絡(luò)攝像頭演示。
為什么選擇Dynamic Web TWAIN網(wǎng)絡(luò)攝像頭附加組件為什么有免費(fèi)的選項(xiàng)時(shí)考慮付費(fèi)選項(xiàng)?我們列出了HTML5不提供的網(wǎng)絡(luò)攝像頭附加組件的一些高級(jí)功能。
- 瀏覽器兼容性 – HTML5與某些較舊的瀏覽器不兼容,例如Internet Explorer 8。
- 精確控制網(wǎng)絡(luò)攝像頭 –您可以完全控制攝像機(jī),例如搖攝,傾斜,滾動(dòng),變焦,曝光,光圈和自動(dòng)對(duì)焦。
- 分辨率設(shè)置 –使用GetResolution(),SetResolution()API獲取和設(shè)置分辨率
- 掃描儀質(zhì)量的圖像 – Dynamsoft提供了多種圖像增強(qiáng)技術(shù)來幫助用戶生成高質(zhì)量的圖像,包括自動(dòng)邊界檢測(cè),噪聲消除和透視校正。
- 上載到服務(wù)器 – SDK提供了內(nèi)置方法,供用戶將圖像上載到服務(wù)器端。
如果您要構(gòu)建一個(gè)健壯的,功能齊全的企業(yè)級(jí)應(yīng)用程序,那么選擇Dynamsoft的SDK這樣的商業(yè)SDK將會(huì)為您帶來巨大的投資回報(bào)。
關(guān)于Dynamic Web TWAIN網(wǎng)絡(luò)攝像頭附加組件
Dynamic Web TWAIN網(wǎng)絡(luò)攝像頭附加組件使Web開發(fā)人員可以使用JavaScript代碼從網(wǎng)絡(luò)攝像頭捕獲圖像。網(wǎng)絡(luò)攝像頭SDK支持在Windows,macOS和Linux上的所有主流瀏覽器中嵌入視頻流。Dynamic Web TWAIN還支持從移動(dòng)相機(jī)捕獲圖像。設(shè)備支持
- 兼容UVC(USB視頻類)的網(wǎng)絡(luò)攝像頭
- 內(nèi)置筆記本電腦攝像頭
- 文件相機(jī)
- Internet Explorer 8+
- 邊緣
- 火狐瀏覽器
- 鉻
服務(wù)器端支持
- Web服務(wù)器:Nginx,IIS,Tomcat,Apache等。
- 操作系統(tǒng):Linux,Windows等。
- 語言:ASP.NET(C#/ VB.NET),PHP,JSP等
如何逐步使用網(wǎng)絡(luò)攝像頭附加組件
在這里,我們將向您展示如何使用SDK輕松地將HTML網(wǎng)頁中的網(wǎng)絡(luò)攝像頭捕獲和視頻預(yù)覽集成。首先,下載Dynamic Web TWAIN并將Resources文件夾復(fù)制到您的項(xiàng)目中。然后創(chuàng)建一個(gè)新的網(wǎng)頁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創(chuàng)建一個(gè)容器
<div id="dwtcontrolContainer"></div>
步驟#3輸入一個(gè)下拉列表和兩個(gè)按鈕
步驟#4通過調(diào)用Dynamsoft_OnReady()初始化對(duì)象
<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控制網(wǎng)絡(luò)攝像頭
您可以使用以下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); } }
如何同時(shí)從掃描儀和網(wǎng)絡(luò)攝像頭捕獲圖像
文檔/記錄管理應(yīng)用程序通常需要通過Web瀏覽器從掃描儀和網(wǎng)絡(luò)攝像機(jī)捕獲圖像。您可以使用Dynamic Web TWAIN核心SDK和網(wǎng)絡(luò)攝像頭附加組件輕松實(shí)現(xiàn)此目的。讓我們繼續(xù)在HelloWorld.html網(wǎng)頁上進(jìn)行工作。
步驟#1重寫函數(shù)Dynamsoft_OnReady()
要控制TWAIN掃描器,請(qǐng)調(diào)用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); } } }
如何將掃描的圖像上傳到服務(wù)器端
步驟#1添加用于上傳的按鈕步驟#2上傳圖片
準(zhǔn)備好圖像后,您可以通過調(diào)用HTTPUploadThroughPost()將其上傳到Web服務(wù)器。
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等,以在服務(wù)器端接收?qǐng)D像數(shù)據(jù)。
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: 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); 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(); %>