Click here to Skip to main content
Click here to Skip to main content

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

, 21 Jan 2013 CPOL
Control web cameras or the built-in laptop webcams inside IE, Firefox and Chrome with JavaScript.

Editorial Note

This article is in the Product Showcase section for our sponsors at CodeProject. These reviews are intended to provide you with information on products and services that we consider useful and of value to developers.

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 directly. 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 – ImageCapture Suite. Unlike in the first 2 options where developer needs to deal with camera initialization, image capturing, editing encoding and uploading separately, everything is encapsulated in ImageCapture Suite.

Introduction to the Webcam Library

Dynamsoft’s ImageCapture Suite 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).

Three editions are provided for different browsers: ActiveX Edition for IE and Plugin and Mac Edition for Firefox, Chrome, Safari on Windows and Mac OS X.

Client Side Server Side
JavaScript, VBScript, HTML ASP.NET, PHP, JSP, ASP, VB.NET, etc.
ActiveX Edition -  x86  x64
Plugin Edition -      on Windows
Mac Edition -     on Mac OS X  
IIS, Tomcat, Apache and more

Here you can see a working application: http://www.dynamsoft.com/Demo/Webcam/online_demo_scan.aspx

Key Features >>

Sample Code 

Client-side JavaScript

1. Initialize ImageCapture Suite

You can find the related ImageCapture Suite files for deployment under the Resources folder in the installation folder. 

  • ImageCaptureSuite.cab
  • ImageCaptureSuitex64.cab
  • ImageCaptureSuitePlugIn.msi
  • ImageCaptureSuiteMacEditionTrial.pkg

ActiveX Edition

There are 32-bit and 64-bit CAB files for corresponding version of IE. Choose the proper one according to the needs. The trial and full versions of ImageCapture Suite use different class-ids.

// For IE, render the ActiveX Object
objString = "<object id='" + DW_ObjectName + "' style='width:" + DW_Width + "px;height:" + DW_Height + "px'";
        if (DW_InWindowsX86)
            objString += "codebase='" + DW_CABX86Path + "#version=" + DW_VersionCode + "' "; // For 32-bit IE, render the x86 cab file
        else
            objString += "codebase='" + DW_CABX64Path + "#version=" + DW_VersionCode + "' "; // For 64-bit IE, render the x64 cab file

        var temp = DW_IsTrial ? DW_TRAILCLASSID : DW_FULLCLASSID;
        objString += " classid='clsid:" + temp + "' viewastext>";
        objString += " <param name='Manufacturer' value='DynamSoft Corporation' />";

Plug-in & Mac Edition

        objString = " <embed id='" + DW_ObjectName + "'style='display: inline; width:" + DW_Width + "px;height:" + DW_Height + "px' id='" + DW_ObjectName + "' type='" + DW_MIMETYPE + "'";
        objString += " OnPostTransfer='Dynamsoft_OnPostTransfer' OnPostAllTransfers='Dynamsoft_OnPostAllTransfers'";
        objString += " OnMouseClick='Dynamsoft_OnMouseClick'  OnPostLoad='Dynamsoft_OnPostLoadfunction'";
        objString += " OnImageAreaSelected = 'Dynamsoft_OnImageAreaSelected'";
        objString += " OnImageAreaDeSelected = 'Dynamsoft_OnImageAreaDeselected'";
        objString += " OnMouseDoubleClick = 'Dynamsoft_OnMouseDoubleClick'";
        objString += " OnMouseRightClick = 'Dynamsoft_OnMouseRightClick'";
        objString += " OnTopImageInTheViewChanged = 'Dynamsoft_OnTopImageInTheViewChanged'";
        objString += " OnGetFilePath='Dynamsoft_OnGetFilePath'";
        if (DW_InWindows)
            objString += " pluginspage='" + DW_MSIPath + "'></embed>"; // For non-IE on Windows, render the plugin edition

        else
            objString += " pluginspage='" + DW_PKGPath + "'></embed>";// For non-IE on Mac OS X, render the Mac edition

2. Video preview

    DWObject.IfShowUI = document.getElementById("ShowUIForWebcam").checked; // Display the live video stream

3. Take a photo

  if (DW_InWindows) {
        DWObject.SelectMediaTypeByIndex(document.getElementById("MediaType").selectedIndex);
           DWObject.SelectResolutionForCamByIndex(document.getElementById("ResolutionWebcam").selectedIndex);        

DWObject.IfDisableSourceAfterAcquire = true;    
DWObject.AcquireImage();

 

 

4. Edit

ImageCapture Suite 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

        DWObject.HTTPUploadThroughPostEx(
            strHTTPServer,
            DWObject.CurrentImageIndexInBuffer,
            strActionPage,
            uploadfilename,
            strImageType
	) ;

Server side code

ImageCapture Suite 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 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=id;Pwd=pwd;";
    
		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
	{
	}		
%>

Name this file as SavetoDB.aspx, you can use it the same way as SavetoFile.aspx. There are many other functions for saving files, like HTTPUploadThroughPostAsMultiPageTIFF, HTTPUploadAllThroughPostAsPDF, HTTPUploadThroughPostAsMultiPagePDF, etc.

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=id;Pwd=pwd;";
    
    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 ImageCapture Suite. The samples can be found in the installation folder of the SDK.

If you have any questions, you can contact our support team at support@dynamsoft.com.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Dynamsoft

Canada Canada
Dynamsoft is the leading provider of web/.NET image acquisition SDKs and version control solutions.
www.dynamsoft.com
Group type: Organisation (No members)



Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.1411023.1 | Last Updated 21 Jan 2013
Article Copyright 2013 by Dynamsoft
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid