Take a Photo from a Desktop Webcam and Upload in a Web Browser

Control web cameras or the built-in laptop webcams inside IE, Firefox and Chrome with JavaScript

In some scenarios, such as Visitor Monitoring module for a government department or Patient Tracking module for a hospital, we may need to take a snap of human faces, patient charts, user IDs and so on and then upload them to a central server. How do we implement this for a web application?

How to interact with webcams connected to a computer in browsers?

It’s not possible to access a webcam using JavaScript only. However, it’s possible through the following options:

  • Flash – The web application requests permission to use the camera and the user will be presented with a dialog indicating the site wishes to use the camera. After the user accepts, the application will be able to grab images from the camera. First, you’ll need to initialize and attach the camera
  • HTML5 – The biggest hurdle is only a few browser versions support HTML 5. Details »
  • 3-rd party browser plugin – Internet Explorer can interact with an imaging peripheral through an ActiveX control. Firefox and Chrome can do the same through a plugin of Netscape Plugin Application Programming Interface (NPAPI).

In this article, we are going to take a look at the 3rd option – Dynamic Webcam SDK. Unlike in the first 2 options where a developer needs to deal with camera initialization, an image capturing, editing encoding and uploading separately, everything is encapsulated in Dynamic Webcam SDK.

Introduction to the Webcam API

Dynamic Webcam SDK is a browser plugin which enables users to acquire images from a webcam, edit and then upload/save them to a database, web server or local disk. Also, it can capture a live video stream into a container and grab a snapshot to be exported to a file/binary. The plugin works with all webcams that are compatible with Windows Image Acquisition (WIA) and USB video device class (UVC).

Two editions are provided for different browsers: ActiveX Edition for IE and Plugin Edition for other browsers on Windows OS.

Client Side

Server Side

JavaScript, VBScript, HTML

ASP.NET, PHP, JSP, ASP, VB.NET, etc.

ActiveX Edition - x86 x64 Plugin Edition - on Windows

IIS, Tomcat, Apache and more

 

Here you can see a working application: http://www.dynamsoft.com/demo/dws/onlinedemo_webcam.aspx

Key Features »

Sample Code

Client-side JavaScript

1. Initialize Dynamic Webcam SDK

ActiveX Edition

Firstly, copy DynamicWebcam.cab to the web server. There are 32-bit and 64-bit CAB files. Choose the proper one according to the needs. The trial and full versions of Dynamic Webcam use different class-ids.

DynamicWebcam.cab can be found in the installation folder of Dynamic Webcam SDK.

For the TRIAL version of Dynamic Webcam, insert the following code in your JS code:

<object 
    classid="clsid:A65BC1E1-B2CE-4251-A0CB-721AC7E02B52"
    id="DynamicWebcam1" width="143" height="156"
    CodeBase = "DynamicWebcam.cab#version=8,0">
</object>

Plug-in Edition

Plug-in edition can be used in Gecko-based browsers including Firefox, Chrome, Safari & Opera on PC. Please copy DynamicWebcam.msi to the web server.

DynamicWebcam.msi can be found in the installation folder of Dynamic Webcam SDK.

<embed
	type="Application/DynamicWebcam-Plugin"
	id = "DynamicWebcam"
	width="100"
	height="100"
	pluginspage="DynamicWebcam.msi">
</embed>

2. Property setting

Brightness = document.getElementById("txtBrightness");
Contrast = document.getElementById("txtContrast");
Hue = document.getElementById("txtHue");
Saturation = document.getElementById("txtSaturation");
Sharpness = document.getElementById("txtSharpness");
Gamma = document.getElementById("txtGamma");
WhiteBalance = document.getElementById("txtWhiteBalance");
BacklightCompensation = document.getElementById("txtBacklightCompensation");
Gain = document.getElementById("txtGain");

MediaType = document.getElementById("MediaType");
Resolution = document.getElementById("Resolution");
EnableVideoProperties(false);
seed = setInterval(ControlDetect, 500);

3. Take a photo

document.getElementById("MediaType").value = Webcam.MediaType;
document.getElementById("Resolution").value = Webcam.ResolutionForCam;

CheckErrorString();
Webcam.IfDisableSourceAfterAcquire = true;
Webcam.AcquireImage();

capture-image

In the video container:

in-video-container

4. Edit

Dynamic Webcam SDK supports basic image editing features including Rotate, Crop, Mirror, Flip, Erase and ChangeImageSize. It also supports multiple images selection, switching images, zoom in/zoom out.

5. Upload

{
    Webcam.HTTPUploadThroughPostEx(
        strHTTPServer,
        Webcam.CurrentImageIndexInBuffer,
        strActionPage,
        uploadfilename,
        strImageType
    );
}

Server side code

Dynamic Webcam supports ASP.NET, PHP, JSP, ASP, VB.NET, etc. to call functions on the server side. The followings are some examples for C# ASP.NET.

Captured pictures can be uploaded to file system or a database of a remote server. Later they can be downloaded to the client side for viewing, editing and so on.

1. Save to database

This is a sample for saving images to the database using c#:

<%@ Page Language="C#" %>
<%
	try
	{
        		String strImageName;
		int iFileLength;
		HttpFileCollection files = HttpContext.Current.Request.Files;
		HttpPostedFile uploadfile = files["RemoteFile"];
		strImageName = uploadfile.FileName;   
		iFileLength = uploadfile.ContentLength;

		Byte[] inputBuffer = new Byte[iFileLength];
		System.IO.Stream inputStream;

		inputStream = uploadfile.InputStream;
		inputStream.Read(inputBuffer,0,iFileLength);

        		String strConnString;

       		strConnString = "Data Source=localhost\\\\sqlexpress;Initial Catalog=DemoWebcam;User ID=sa;Pwd=DefeGedetf;";

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

        String SqlCmdText = "INSERT INTO tblWebcam (strImageName,imgImageData) VALUES (@ImageName,@Image)";
		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;

		sqlConnection.Open();
		sqlCmdObj.ExecuteNonQuery();
		sqlConnection.Close();
	}
	catch
	{
	}		
%>

2. Download files from the server

Code bellow is a sample of downloading image files from your server to the client-side. You need to pass the filename, extent name and image index to the program.

<%@ Page Language="C#"%>

<%
	//get temp file name 

    System.Web.HttpRequest request = System.Web.HttpContext.Current.Request;

    String strImageName;
    String strImageExtName;
    String strImageID;

    strImageName = request["ImageName"];
    strImageExtName = request["ImageExtName"];
    strImageID = request["iImageIndex"];

    String strConnString;

    strConnString = "Data Source=localhost\\\\sqlexpress;Initial Catalog=DemoWebcam;User ID=sa;Pwd=DefeGedetf;";

    System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(strConnString);
    System.Data.SqlClient.SqlCommand sqlCmdObj = new System.Data.SqlClient.SqlCommand("SELECT imgImageData FROM tblWebcam WHERE iImageID= " + strImageID, sqlConnection);

    sqlConnection.Open();

    System.Data.SqlClient.SqlDataReader sdrRecordset = sqlCmdObj.ExecuteReader();

    sdrRecordset.Read();

    long iByteLength;
    iByteLength = sdrRecordset.GetBytes(0, 0, null, 0, int.MaxValue);

    byte[] byFileData = new byte[iByteLength];

    sdrRecordset.GetBytes(0, 0, byFileData, 0, Convert.ToInt32(iByteLength));

    sdrRecordset.Close();
    sqlConnection.Close();

    sdrRecordset = null;
    sqlConnection = null;

    Response.Clear();
    Response.Buffer = true;

    if(strImageExtName == "bmp"){
        Response.ContentType = "image/bmp";
    }else if(strImageExtName == "jpg"){
        Response.ContentType = "image/jpg";
    }else if(strImageExtName == "tif"){
        Response.ContentType = "image/tiff";
    }else if(strImageExtName == "png"){
        Response.ContentType = "image/png";
    }else if(strImageExtName == "pdf"){
        Response.ContentType = "application/pdf";
    }

    try{
        String fileNameEncode;
        fileNameEncode = HttpUtility.UrlEncode(strImageName, System.Text.Encoding.UTF8);
        fileNameEncode = fileNameEncode.Replace("+", "%20");
        String appendedheader = "attachment;filename=" + fileNameEncode;
        Response.AppendHeader("Content-Disposition", appendedheader);

        Response.OutputStream.Write(byFileData, 0, byFileData.Length);
    }
    catch(Exception){
        Response.Flush();
        Response.Close();
    }
%>

Get Samples

To try out the above-mentioned features by yourself, you can download the 30-day free trial of Dynamic Webcam.  The samples can be found in the installation folder of the SDK.

If you are developing a desktop application, you may check out Dynamic .NET TWAIN, a .NET component for webcams and scanners.

If you are developing a document scanning web application, you may check out Dynamic Web TWAIN, a browser-based scanner programming library.