Click here to Skip to main content
15,511,274 members
Articles / Programming Languages / C#
Posted 12 Sep 2013


7 bookmarked

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

12 Sep 2013CPOL3 min read
Scan and Save Images to a Database in C# Using Dynamic .NET TWAIN

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


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.

 Image 1 

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

            dynamicDotNetTwain.SupportedDeviceType = Dynamsoft.DotNet.TWAIN.Enums.EnumSupportedDeviceType.SDT_ALL; // enable capturing images from both scanners and webcams
            int lngNum;
            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.IfShowUI = chkIfShowUI.Checked;
            dynamicDotNetTwain.IfDisableSourceAfterAcquire = true;
            try { dynamicDotNetTwain.AcquireImage(); }
            catch (Exception exp)



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("PDF saved successfully.");


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"%>

		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;
	    String strConnString = "Data Source=;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;

	catch(Exception e)

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 strHTTPServer, HTTPPort, HTTPUserName 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.


Is your organization currently undergoing a project to digitize documents? Have you deployed the SDK? If so, how has it helped? Let us know in the comments section or by contacting us. You can also contact us if you need any help to get this sample code up and running. To do so, reach us by email at For pricing or licensing questions, call us at 1-877-605-5491 or email our sales team at


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

Written By
Canada Canada
Dynamsoft has more than 15 years of experience in TWAIN SDKs, imaging SDKs and version control solutions.

Our products include:

- Dynamic Web TWAIN: a TWAIN scanning SDK optimized for web document management applications.
- Dynamic .NET TWAIN: a .NET TWAIN and Directshow Image Capture SDK for WinForms/WPF applications.

Imaging SDKs
- Barcode Reader for Windows, Linux, macOS, iOS, Android and Raspberry Pi.
- OCR addon for both web and .NET TWAIN SDKs

Version Control
- SourceAnywhere: a SQL server-based source control solution. Both on-premise and hosting options are provided.
This is a Organisation

21 members

Comments and Discussions

-- No messages could be retrieved (timeout) --