Search This Blog

Friday, March 12, 2010

Working with Images Using .NET

In this code snippet I will examine how to work with images using Visual Studio .NET 2003 and SQL Server 2000 database.

Some applications, be it desktop or web, require working with images.  Aptly speaking, the good paradigm is banking applications.  Withdrawal of an amount of money from a bank account requires signature verification of the account holder.  Normally, specimen signatures of customers are archived as images in such applications.

There can be a couple of ways to work around to store images.  One is typically to tag each image with a unique identifier and save the image at a physical location accessible by the application. Store that unique identifier and the physical absolute/relative path in a database table.  Now, when the application looks in for a given identifier from database table then the path against the identifier can be pulled from the table and uses that path in any image control to display the image.
A little tweak in the approach renders more scalability, dependability and boost application’s security with playing around images.
In the second approach, images can be stored in database in bytes, assigning each image with a unique identifier.  For a quick tour of this approach we can use SQL Server database and a .NET application.
Let us discuss the advantages of the later approach than that of the previous one.
Storing images in byte format in database enforce security and let the application implement access privileges to users of the images.
The database administrator can manage read-only/write permission to database table once images are stored.
This approach prevents users from interacting with physical image files and does not require file read write permission to a specific directory on the file system and reduce the burden on file I/O.

Steps to build a demo application for storing/retrieving images
Step 1
Verify that SQL Server 7/2000 is installed on the machine.
Create table tblImgData, stored procedure rkReadPicture, rkInsertPicture in pubs database and if the SQL Server version is 2000 and above then allow execute permission to two stored procedures.  The SQL scripts for these database objects have been provided in the application folder on the ZIP file.

Step 2
Unzip the ZIP file which can be downloaded from the Downloads section at the end of this article and open the solution file in Visual Studio .NET 2003 and run the application. For the first time the table tblImgData will be blank.  Now enter an ID and name for the image in the given input on the windows form and select a image from the image folder available in the application folder and click on button "Save new image to database."  The code in routine btnSave_Click() will insert the image to the table in byte format.

Listing 1

private void btnSave_Click(object sender, System.EventArgs e)
  if (strFn != null && ID.Text != "")
    this.pictureBox1.Image = Image.FromFile(strFn);
    FileInfo fiImage = new FileInfo(strFn);
    this.lImageFileLength = fiImage.Length;
    FileStream fs = new FileStream(strFn, FileMode.Open, FileAccess.Read,
    barrImg = new byte[Convert.ToInt32(this.lImageFileLength)];
    int iBytesRead = fs.Read(barrImg, 0, Convert.ToInt32(this.lImageFileLength))

    SqlCommand cmdInsert = new SqlCommand("rkInsertPicture", con);
    cmdInsert.CommandType = CommandType.StoredProcedure;
    cmdInsert.Parameters.Add("@ID", System.Data.SqlDbType.Int, 4);
    cmdInsert.Parameters.Add("@Name", System.Data.SqlDbType.VarChar, 50);
    cmdInsert.Parameters.Add("@Picture", System.Data.SqlDbType.Image);

    cmdInsert.Parameters["@ID"].Value = this.ID.Text;
    cmdInsert.Parameters["@Name"].Value = this.txtName.Text;
    cmdInsert.Parameters["@Picture"].Value = this.barrImg;
    cmdInsert.Connection = con;
    int iresult = cmdInsert.ExecuteNonQuery();
    MessageBox.Show("Check ID and Name, these two cannot be blank");

Step 3
In order to view and verify the image enter the ID in the provided textbox in form and click on button "Show Image," this will read the byte stored in database table, convert to image and display on the form.

Listing 2

private void btnShowImage_Click(object sender, System.EventArgs e)
  label3.Text = "";
  this.pictureBox1.Visible = true;
    SqlCommand cmdsp = new SqlCommand("rkReadPicture", con);
    cmdsp.CommandType = CommandType.StoredProcedure;
    cmdsp.Parameters.Add("@ID", SqlDbType.Int, 4);
    if (this.ID.Text != "")
      cmdsp.Parameters["@ID"].Value = this.ID.Text;
      cmdsp.Connection = con;
      SqlDataAdapter da = new SqlDataAdapter(cmdsp);
      DataSet ds = new DataSet();
      da.Fill(ds, "tblImgData");
      foreach (DataRow row in ds.Tables["tblImgData"].Rows)
        label3.Text = row[1].ToString();
      byte[]barrImg = (byte[])cmdsp.ExecuteScalar();

      string strfn = Convert.ToString(DateTime.Now.ToFileTime());
        FileStream fs = new FileStream(strfn, FileMode.CreateNew,
        fs.Write(barrImg, 0, barrImg.Length);
        pictureBox1.Image = Image.FromFile(strfn);
      catch (Exception exp)
        this.pictureBox1.Visible = false;
        MessageBox.Show("No records found for the given ID " + ID.Text);

      MessageBox.Show("Enter a ID which is integer type for the search");
  catch (Exception exp1)

There is some definite purpose of using stored procedure in this application.  Stored procedures enhance security.  The permissions to execute a stored procedure can be granted, denied, or revoked on the data objects.  Here is a code snip which tells how to grant permissions.

Listing 3

-- grant select permission on the tblImgData table to specific user account.
-- role
-- deny UPDATE, DELETE and INSERT permissions

Notes: Validation has not been implemented on the application. This might be implemented as per requirement.

[Download Sample]

This is how we work with images and enforce better security on signature verification on any commercial application.

No comments:

Post a Comment

Leave your suggession & comment...