Webcam in HTML5

In the previous blog post, I have glanced at HTML5. Probably many people have already experienced some cool functions of HTML5. In this article, I would like to share how to invoke Webcam in HTML5.

While strolling through StackOverflow, I found there are many questions about how to display webcam in a web browser. Using HTML5, with a few tricks, can manage to show a Webcam in a web browser conveniently.

Please follow this tutorial step by step, and you can instantly build a webcam application in a web browser.

Create a <video> element and two <button> elements

<video id="video"></video>
<button id="start">start</button>
<button id="stop">stop</button>

Initialize

var streaming = false,
video = document.querySelector('#video'),
start = document.querySelector('#start'),
stop = document.querySelector('#stop'),
width = 320,
height = 0;

Get video

navigator.getMedia = (navigator.getUserMedia ||
                                   navigator.webkitGetUserMedia ||
                                   navigator.mozGetUserMedia ||
                                   navigator.msGetUserMedia);
navigator.getMedia(
              {
                  video: true,
                  audio: false
              },
              function (stream) {
                  if (navigator.mozGetUserMedia) {
                      video.mozSrcObject = stream;
                  } else {
                      var vendorURL = window.URL || window.webkitURL;
                      video.src = vendorURL.createObjectURL(stream);
                  }
                  video.play();
              },
              function (err) {
                  console.log("An error occured! " + err);
              }
            );

Resize video

video.addEventListener('canplay', function (ev) {
                if (!streaming) {
                    height = video.videoHeight / (video.videoWidth / width);
                    video.setAttribute('width', width);
                    video.setAttribute('height', height);
                    canvas.setAttribute('width', width);
                    canvas.setAttribute('height', height);
                    streaming = true;
                }
            }, false);

 Start or stop video

start.addEventListener('click', function (ev) {
                video.play();
                ev.preventDefault();
            }, false);
stop.addEventListener('click', function (ev) {
                video.pause();
                ev.preventDefault();
            }, false);

Pretty easy. For further reading, you can refer to Mozilla’s WebRTC docs.

HTML5 is definitely the trend of web technology. However, it is not so mature yet. Browsers are adopting features from HTML5 and evolving themselves over time. In the current stage, considering the compatibility and the security, using a 3rd-party webcam plugin, like ImageCapture Suite, would be a good option, especially if your image capture project has a tight schedule. Besides image acquisition, the plugin also allows you to do simple image processing, HTTP uploading and downloading. ImageCapture Suite supports all the mainstream web browsers like Chrome, IE, Firefox, and Opera on both Mac and Windows platform.

If you have any questions or comments, please leave a message in the comments section below or email me at kgao@dynamsoft.com.

Scan and Save Images to a Database in C# Using Dynamic .NET TWAIN

In today’s “big data era”, more and more organizations are using an enterprise content management (ECM) or record management system (RMS) to help maintain and manage the documents. Digitizing documents and storing them in a central database has become an important part of many organization’s document management workflow. For this purpose, we will illustrate creating an application to capture documents as images from scanners and webcams. We’ll also cover how to save them in SQL Server in C#.

We will be using Dynamic .NET TWAIN to expedite development and deployment of such an application. Dynamic .NET TWAIN is a document scanning SDK based on the .NET Framework 2.0/4.0. The SDK enables users to capture images from TWAIN scanners and UVC/WIA webcams. It also allows simple edits or processing. Finally, it enables saving of images to your local/server disk, FTP site or database from your WinForm application.

Using the Code

If you are interested in using a .NET imaging SDK to quickly implement image capturing in your application, you can download the 30-day free trial of Dynamic .NET TWAIN. After installation, in the installation directory, you will find “DynamicDotNetTWAIN.dll” under \Bin\v2.0 and \Bin\v4.0. You can choose the corresponding version to suit your specific .NET framework version.

Capture and upload image to database in .NET

 

Capture Images

With Dynamic .NET TWAIN, you can enable image capturing from TWAIN devices and USB/WIA webcams using just a few lines of code. Here’s a sample of this code:

Public frmCustomizeScan()
        {
            InitializeComponent();

            dynamicDotNetTwain.SupportedDeviceType = Dynamsoft.DotNet.TWAIN.Enums.EnumSupportedDeviceType.SDT_ALL; // enable capturing images from both scanners and webcams
            int lngNum;
            dynamicDotNetTwain.OpenSourceManager();
            for (lngNum = 0; lngNum < dynamicDotNetTwain.SourceCount; lngNum++)
            {     
               cmbSource.Items.Add(dynamicDotNetTwain.SourceNameItems(Convert.ToInt16(lngNum))); // display the available imaging devices
            }
            if (lngNum > 0)
                cmbSource.SelectedIndex = 0;          

        }

        private void cmdScan_Click(object sender, EventArgs e)
        {
            dynamicDotNetTwain.IfAppendImage = true;
		    AcquireImage(); // acquire images
        }

        private void AcquireImage()
        {
            dynamicDotNetTwain.SelectSourceByIndex(Convert.ToInt16(cmbSource.SelectedIndex));
            dynamicDotNetTwain.IfShowUI = chkIfShowUI.Checked;
            dynamicDotNetTwain.OpenSource();
            dynamicDotNetTwain.IfDisableSourceAfterAcquire = true;

            try { dynamicDotNetTwain.AcquireImage(); }
            catch (Exception exp)
            {
                MessageBox.Show(exp.Message);
            }

        }

Uploading

Dynamic .NET TWAIN provides HTTP Upload methods with which you can upload the scanned or captured images to a web server or database. This can be done in file formats including, PDF, TIF, JPG, PNG and BMP. Multi-page TIF and PDF are also supported.

When uploading the images, you can add extra parameters and store them with the image record in the database. Here’s sample code for that:

  private void BtnUpload_Click(object sender, EventArgs e)
        {
            string strActionPage = "Upload.aspx"; // for receiving the uploaded image data on the server side
            string strFileName = textBox1.Text;
            string strFileType = textBox2.Text;
            string strHTTPServer = "localhost"; // the name or the IP of your HTTP Server
            dynamicDotNetTwain.HTTPPort = 8066; //the port number of the HTTP Server
            dynamicDotNetTwain.HTTPUserName = "chloe"; //user name for logging into HTTP Server
            dynamicDotNetTwain.HTTPPassword = "c";
            dynamicDotNetTwain.SetHTTPFormField("FileType", strFileType); // pass extra text parameters when uploading image
            dynamicDotNetTwain.HTTPUploadAllThroughPostAsPDF(strHTTPServer,strActionPage, strFileName+".pdf"); // save the captured images as a multi-page PDF file
            if (dynamicDotNetTwain.ErrorCode !=ErrorCode.Succeed)
            {
                MessageBox.Show(dynamicDotNetTwain.HTTPPostResponseString);
            }
            else
            {
                MessageBox.Show("PDF saved successfully.");
            }
        }

Upload.aspx

The action page – Upload.aspx – referred to in the HTTPUploadAllThroughPostAsPDF method is for receiving the image data on the server side. So make sure to deploy the file in your web server. Here’s how to do that:

<%@ Page Language="c#" AutoEventWireup="false" Debug="True"%>

<%

 	try
	{
		int iFileLength;
		HttpFileCollection files = HttpContext.Current.Request.Files;
		HttpPostedFile uploadfile = files["RemoteFile"];
		String strImageName = uploadfile.FileName; 
		String strFileType = System.Web.HttpContext.Current.Request.Form["FileType"];

		iFileLength = uploadfile.ContentLength;
		Byte[] inputBuffer = new Byte[iFileLength];
		System.IO.Stream inputStream;
		inputStream = uploadfile.InputStream;
		inputStream.Read(inputBuffer,0,iFileLength);	    

	    String strConnString = "Data Source=192.168.8.211;Initial Catalog=WebTwain;User ID=sa;Pwd=sa";

		System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(strConnString);

		String SqlCmdText = "INSERT INTO tblImage (strImageName,imgImageData, strFileType) VALUES (@ImageName,@Image, @ImageType)";
		System.Data.SqlClient.SqlCommand sqlCmdObj = new System.Data.SqlClient.SqlCommand(SqlCmdText, sqlConnection);

		sqlCmdObj.Parameters.Add("@Image",System.Data.SqlDbType.Binary,iFileLength).Value = inputBuffer;
		sqlCmdObj.Parameters.Add("@ImageName",System.Data.SqlDbType.VarChar,255).Value = strImageName;
        sqlCmdObj.Parameters.Add("@ImageType", System.Data.SqlDbType.VarChar, 255).Value = strFileType;

		sqlConnection.Open();
		sqlCmdObj.ExecuteNonQuery();
		sqlConnection.Close();
	}
	catch(Exception e)
	{
       		Response.Write(e.Message);    
       		throw;         

	}

%>

Deploy & Run the Application

For your convenience, the complete source code can be downloaded from this article.

If you get a license error when running the sample code, you can download Dynamic .NET TWAIN from Dynamsoft’s website to get a valid trial license for free:  Dynamic .NET TWAIN 30-Day Free Trial Download

Make sure you deploy the web application, which includes Upload.aspx, in your web server (IIS, Apache, etc.) and update the values of strHTTPServerHTTPPortHTTPUserName and HTTPPassword in BtnUpload_Click()accordingly before running. You can find CreateTable.sql for the script to create the table for storing the PDF files.

 

Read more on CodeProject.

 

New to HTML5

What is HTML5

HTML5 is a markup language based on HTML 4 and XHTML 1. It’s goal is to support the latest multimedia and be much more readable and understandable by humans and devices. Also, it is dedicated to reducing the dependency on RIA (Rich Internet Application) such as Flash, Silverlight, JavaFX and so forth, providing more handy APIs for strengthening Internet applications. A generic definition of HTML5 is “HTML5 + CSS3 + JS”.

Why HTML5

  • Standard
  • Cross-platform
  • Auto-adapt to the web page
  • Update in real-time
  • No plugin needed
  • Open and free
  • Friendly to search engines

What can HTML5 do

For experiencing what HTML5 can do, here are some amazing HTML5 web pages:

http://spielzeugz.de/html5/liquid-particles.html

http://ghost-hack.com/post/jsexperiments/tunneler/tunneler.html

http://playbiolab.com/

http://bellard.org/jslinux/index.html

Features of HTML5

Semantics

HTML5 defines some new HTML elements, which makes document description much more precise and readable.

semantics

Here are some useful HTML5 elements:

<article> <header> <aside> <hgroup> <figure> <figure> <figcaption> <section> <footer> <time>.

Deprecated elements: <acronym> <applet> <basefont> <big> <center> <dir> <font> <frame> <s> <isindex> <noframes> <frameset> <strike> <tt> <u> and <xmp>

Connectivity

WebSocket

WebSocket provides for full-duplex communication, which makes more possible interaction between client and server, facilitating live content and the creation of real-time games.

websocket

 

Notifications

Website can push notifications to the desktop via the following code.

if (window.webkitNotifications.checkPermission() == 0) {
    var title = 'HTML5 notification',
        text = 'Can you see HTML5 notification?';
    window.webkitNotifications.createNotification('', title, text).show(); 
}

Multimedia

In HTML5, inserting a video or audio is as convenient as inserting an image.

HTML5 video

<audio src="sound.mp3" controls></audio>
<video src="movie.webm" autoplay controls></video>

3D Graphics Effects

Canvas

Dynamically draw something on the web page.

<canvas id="canvas" width="300" height="300"></canvas>
<script>
  var ctx = document.getElementById("canvas").getContext("2d");
  ctx.fillRect(20, 25, 150, 100);

  ctx.beginPath();
  ctx.arc(220, 110, 100, Math.PI * 1/2, Math.PI * 3/2);
  ctx.lineWidth = 15;
  ctx.lineCap = 'round';
  ctx.strokeStyle = 'rgba(255, 127, 0, 0.5)';
  ctx.stroke();
</script>

WebGL

Without needing a plugin, WebGL provides some APIs to render 2D and 3D graphics in the web browser. This website helps you check whether your browser supports WebGL. Here are some amazing WebGL samples.

HTML5 vs Flash

HTML5:

  • No plugin for web browser.
  • Complex
  • Low popularity so far
  • Cross-platform
  • Lacks an engine
  • Free development tools.

Flash:

  • Smooth and stunning
  • Easy to learn
  • High popularity
  • High battery cost
  • Not open
  • Paid development tools

For more specifications, refer to Wikipedia: Comparison of HTML5 and Flash

Please feel free to contact kgao@dynamsoft.com.

Dynamic Web TWAIN 9.1 released!

I’m pleased to announce that Dynamic Web TWAIN 9.1 is released on August 27th, 2013.

Three exciting improvements are included in this new version:

  • Added native scanning support for Mac Edition. The new property ImageCaptureDriverType allows Mac users to directly acquire images via native scan (without installing a TWAIN driver).
  • Improved IE users’ experience when using a separate process for document scanning. In v9.0, IE users might need to manually allow the broker process to run. It is now automated with the enhanced security of the ActiveX edition.
  • Fixed a bug where OnPostTransfer event is not triggered in some cases.

 

Check out the Release Notes >>
Download the 30-day free trial >>
Visit online store >>

I’d love to hear any comments or suggestions about this new version. Please don’t hesitate to contact me (kgao@dynamsoft.com).

Cheers!

Using Git-TFS in Visual Studio 2013 Express

Microsoft has released Visual Studio 2013 Preview, and announced the availability of Git for Visual Studio and Team Foundation Service. Today, let’s go through the new experience of version control in VS 2013 Preview.

Account Creation

Microsoft provides Team Foundation Service Free Plan for up to 5 users. I’m using the service for demo in this article. If you don’t have an in-house TFS Server, you can also take advantage of it and sign up for an account here. If you need a TFS Hosting service with good customer service, you may check out Dynamsoft TFS Hosting plans.

After creating an account with Microsoft TFS Service, you will be directed to your TFS page like the one shown below. You can see two options for creating a team project. The account URL is located below “Getting started”.

TFS main page

Team Project Creation

Click “New team project + Git” to create a team project using Git as the source control provider.

create git project

 

Specify the project name and select Git for version control.

specify new project

 

This is the page for my newly created team project. After creating the team project, we can then push the local repo to remote server.

project created

Local Project Creation

Create a new project in Visual Studio, and do not forget to check “Add to source control”.

create local project

 

Choose Git as your source control system.

choose git

 

Now you will be able to view the changes of your source code.

changes of source code

 

Commit your code.

commit changes

 

Right click a file in Team Explorer, you can compare version differences with syntax highlighting.

diff files

 

Also, checking repo history is convenient by right click.

view history

Publish to Remote Repository

Switch to Commits.

switch to Commits

 

Find Git URL on your TFS account.

git URL

 

Copy the URL to remote repository configuration, and click “Publish” to upload your local files to remote server.

publish to remote repo

 

Check commits information online.

commit log

 

Import Git from GitHub

Clone Git repo.

git clone

 

Download source code to local disk.

clone finished

 

Double-click your repo and click “Open” to mount your project.

open cloned project

 

That’s all about how to simply use Git between Visual Studio 2013 Express and Git remote server. Don’t hesitate to email kgao@dynamsoft.com if you have any idea to share with me.

 

 

SourceAnywhere 4.4 is Released!

I’m pleased to announce that Dynamsoft SourceAnywhere 4.4 is released on July 9th, 2013. This is a SQL server-based version control software designed as a VSS replacement.

Based on all our customers’ valuable feedback on SourceAnywhere Standalone 4.3, we have made some further improvements in this new version.

Highlights in SourceAnywhere 4.4:

    • Improved the performance of LAN file transfer for the “Get” and “Check out” operations
    • Optional warnings available at Tools -> Options. You can choose to display a warning message when
      • Check out an already checked out file
      • Exit SourceAnywhere Client when there are checked out items
      • Delete/Purge a file or project
    • More options in the “Add Files” dialog
      • You can “Check out Immediately” the added files
      • You can “Remove local copy” of the added files
    • Do Diff when checking in a file or project

 

Check out the Release Notes >>
Download the 30-day free trial >>
How to upgrade to the latest version? >>

If you have any questions or comments regarding the new release, please feel free to let me know (kgao@dynamsoft.com).

Cheers!

How to log in TFS as a different user?

Sometimes you may want to switch to another user to log into your Team Foundation Server (TFS) service. However, you would find that Windows remembers your credentials and log you in automatically. So how to make TFS forget the old credentials so that you can get the chance to enter the user name and password of TFS again? Where is the credentials information stored?

TFS - connect to team project

Actually Windows stores the credentials information at Control panel\User Accounts\Manage Your Network Passwords (or Control Panel\User Accounts and Family Safety\Credential Manager).

For example, I’m using Dynamsoft TFS Hosting service. As we can see in the screenshot below, there is a record of credentials for auto logon to “s01.tfshosted.com” which is the TFS Server URL of my hosting account. So we can click Remove from vault to remove the automatic logon to TFS server using the current user. If you want to keep using another user for future logon, you can click Edit and update the credentials accordingly.

Windows Credential Manager

After you remove the record for TFS service logon from Windows Credentials, you will be prompted for a new set of credentials when you go into Team Explorer the next time.

Log in dialog box for TFS

Vice versa, if you find you get the prompt for entering credentials to log into TFS Service every time and want to make it automatic, you can click Add a Windows credential to let Windows remember your credentials.

Add a Windows credential for TFS logon

Let me know in the comments section below if you have any questions or comments on changing the TFS credentials.

If you are looking for a TFS hosting service, you may check out Dynamsoft TFS hosting plans and contact support@dynamsoft.com with any questions.

APIs for Image Capture Applications

When developing an online image capture application, which API shall we choose?

Catherine wrote an article which introduces three popular APIs for imaging apps – TWAIN, WIA and DirectShow. It will give you some ideas on TWAIN vs WIA vs Direcshow and will give you some clues on which API to go for your application.

Read more the artice posted on Drdobbs. 

If you want to take advantage of 3rd-party imaging SDKS to accelerate development and integration, you can check out Dynamsoft’s .NET & web Image Capture SDKs.

New Article on CodeProject: Reading Barcodes from an Image in a Web App

Because of its accuracy and its ease of use, Barcodes have become more and more popular as a part of daily document management workflow. You can use barcodes to identify documents, separate batch scanning, or even get reliable metadata as a document identifier.

This article will show you how to decode barcodes from an image captured or scanned in a web application with the help of ImageCapture Suite.

 

Dynamsoft’s Image Capture Suite is an online image acquisition and processing toolkit designed for web applications. It allows you to capture images from scanners, webcams and other TWAIN/UVC/WIA compatible devices from all mainstream browsers – Internet Explorer (32-bit/64-bit), Firefox, Chrome and Safari – on Windows and Mac. The toolkit also comes with a Barcode Reader SDK which allows you to decode both 1D and 2D barcode symbols online.

If you are interested in the SDK, the 30-day Free Trial can be downloaded from Dynamsoft website.

 

Read more: Reading Barcodes from an Image in a Web App

ImageCapture Suite Barcode Reader Online Demo

 

ImageCapture Suite 30-Day Free Trial Download

Dynamsoft Enhances Barcode Reader for its .NET TWAIN Software Dev Kit

Updated Barcode Reader Increases 1D and 2D Barcode Recognition and Performance in Dynamic .NET TWAIN SDK for Use in Developing Image Acquisition and Processing Applications

 

VANCOUVER – June 3, 2013 – Dynamsoft Corp., a developer of scanner programming libraries and JavaScript webcam plug-ins, has upgraded the barcode reader add-in for its latest Dynamic .NET TWAIN software development kit (SDK), version 4.3, to improve its overall performance. Barcode reader performance (1D or 2D) is improved from 50 to 300 percent compared to previous versions. Barcode recognition accuracy has also been improved.

 

The larger the barcode image, the more pronounced the improved performance of the barcode reader. Also, the SDK now allows developers to use zone optical character recognition (OCR) on scanned / captured documents. The Dynamic .NET TWAIN SDK enables a simpler development path for applications to capture images from most imaging devices for sale or in use. The SDK has built-in webcam support. It also supports TWAIN, WIA and UVC application programming interfaces (API). These features and more practically eliminate worries related to ensuring device compatibility. Extension features include image editing and uploading capabilities to allow post-capture processing in WinForm, WPF or other .NET applications.

 

“Barcodes continue to grow in popularity and as this happens it becomes important that developers be able to leverage their advantages,” said Amy Gu, Vice President of Dynamsoft.  “Accurate barcode recognition is critical, regardless of the size of the barcode. Dynamic .NET TWAIN’s latest barcode add-in address these performance needs.”

 

Dynamic .NET TWAIN is based on Microsoft’s .NET framework and the TWAIN library is optimized for use in C# and Visual Basic .NET. Customizable scanning configurations include, ADF; duplex; resolution; pixel type, and more. Multiple support channels are provided for the SDK, including email, live chat, forum and phone.

 

Pricing and Availability

Dynamsoft’s Dynamic .NET TWAIN SDK is available starting June 4, 2013. It is licensed for $799 per developer and allows royalty-free distribution. The purchase of a yearly subscription includes Premier Support, offering advantages such as one-to-one product training, code reviews up to three times annually and more. The SDK can be purchased online at https://www.dynamsoft.com/Secure/.Net-TWAIN-Scanner-BuyIt.aspx. Full details on Premier Support are available at https://www.dynamsoft.com/Products/Yearly-Subscription-Benefits.aspx#TWAIN-Benefits.

 

About Dynamsoft Corp.

Founded in 2003, Dynamsoft Corp. provides enterprise-class source control / version control software. Its SourceAnywhere™ software enables efficient file management of source code versions. This ensures greater collaboration and integrity of source code. It is ideal for web, software and application development throughout the lifecycle of development and support. Dynamsoft also provides TWAIN™ software development kits (SDK) and other image capture SDKs. Dynamsoft is an associate member of the TWAIN Working Group that develops TWAIN standards. Thousands of customers use Dynamsoft’s source control and TWAIN SDK solutions. Customers include: 3M®; Apple®; EMC®; Fujitsu®; GE®; H&R Block®; HP®; IBM®, Intel®; InfoSys®; Lockheed Martin®; Olympus®; Philips®; PricewaterhouseCoopers®; Samsung®; Siemens®; Symantec®; Unisys®; Verizon®; and more.  More information is available at http://www.dynamsoft.com.

 

Note: Whether noted or not, references to certain words may be trademarks or registered trademarks of their respective owners.