如何使用Dynamic Web TWAIN从网络摄像头捕获图像

如何通过浏览器访问网络摄像头?

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添加参考

步骤#2创建一个容器

步骤#3输入一个下拉列表和两个按钮
在这里插入图片描述

步骤#4通过调用Dynamsoft_OnReady()初始化对象

步骤#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和网络摄像头附加组件轻松实现此目的。
网络摄像头和扫描仪捕获JavaScript
让我们继续在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代码

<?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; ?>

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 <% 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(); %>

本文转载自【慧都科技】。欢迎任何形式的转载,但请务必注明出处、不得修改原文相关链接,尊重他人劳动成果

好的,我会根据你的要求为你提供关于使用 Dynamic Web TWAIN 扫描识别工具的教程,下面是一个建立一个“Hello World”扫描页面的示例: 1. 首先,你需要在你的项目中引入 Dynamic Web TWAIN 的库文件。你可以直接使用它的在线 CDN 地址,也可以将它下载到本地并引入。 ```html <script src="https://cdn.dynamsoft.com/dwt/16.1.1/dynamsoft.webtwain.min.js"></script> ``` 2. 接下来,你需要在你的 HTML 文件中建立一个扫描按钮和一个容器来展示扫描结果。 ```html <button id="btnScan">扫描</button> <div id="dwtcontrolContainer"></div> ``` 3. 在你的 JavaScript 文件中,你需要初始化 Dynamic Web TWAIN 并为扫描按钮添加一个点击事件。在初始化时,你需要设置它的授权密钥和容器 ID。 ```javascript // 初始化 Dynamic Web TWAIN Dynamsoft.WebTwainEnv.AutoLoad = false; Dynamsoft.WebTwainEnv.RegisterEvent("OnWebTwainReady", onReady); Dynamsoft.WebTwainEnv.ProductKey = "授权密钥"; Dynamsoft.WebTwainEnv.Load(); // 扫描按钮的点击事件 document.getElementById("btnScan").onclick = function() { var dwtObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); dwtObject.IfShowUI = true; dwtObject.AcquireImage(); } // 初始化成功后的回调函数 function onReady() { var dwtObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); dwtObject.IfShowUI = false; dwtObject.HTTPPort = 80; dwtObject.HTTPDownload( "http://localhost/HelloWorld.tif", function() { console.log("下载成功!"); }, function(errorCode, errorString) { console.log(errorString); } ); } ``` 4. 最后,你需要在你的服务器上建立一个用于保存扫描结果的接口。你可以使用 Java、PHP 等语言来实现这个接口,具体实现方式可以参考 Dynamic Web TWAIN 的官方文档。 以上就是一个使用 Dynamic Web TWAIN 建立一个“Hello World”扫描页面的示例。希望对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值