Blue Theme Orange Theme Green Theme Red Theme
 
Nevron Chart
Home | Forums | Videos | Photos | Blogs | Beginners
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Safari Books Online
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » ADO.NET & Database » Save an Image to SQL Server

Save an Image to SQL Server


This article describes an easy approach to saving an image file into an SQL Server 2000 database table as an SQL Server image data type.

Author Rank:
Total page views :  138477
Total downloads :  3111
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
SqlServerImages.zip
 
Become a Sponsor

Introduction:

This article describes an easy approach to saving an image file into an SQL Server 2000 database table as an SQL Server image data type. The sample windows forms application provides a simple interface used to allow the user to select an image file (bitmap, gif, or jpeg) from the file system, title the image, and load the selected into a table in an SQL Server 2000 database. The user may also open an image viewer and examine the images contained in the database; images displayed in the simple viewer display the image, the title of the image, the image type, and the image height and width.

Figure 1: An Image Stored in SQL Server 2000

Getting Started

In order to get started, unzip the included project and open the solution in the Visual Studio 2005 environment. In the solution explorer, you should note the following:

Figure 2: Solution Explorer

Within the solution, the app.config file contains a connection string used with the SQL Server 2000 database used to contain the images. As the configuration file is aimed at my local instance of SQL Server 2000, you will need to modify the connection to point to your database.

<connectionStrings>

    <add name="SqlServerImages.My.MySettings.ImageGalleryConnectionString"

        connectionString="Data Source=bxswlt;Initial Catalog=ImageGallery;User                    

        ID=sa"

        providerName="System.Data.SqlClient" />

</connectionStrings>

In order to support this example, a simple database entitled, "ImageGallery" was added to my SQL Server instance and a table entitled, "ImageCollection" was added to the database. The image collection table (see figure 3) contains the following columns:

  • ImageContent
  • ImageTitle
  • ImageType
  • ImageHeight
  • ImageWidth

The specification for each of these columns is shown in figure 3. Given the simplicity of the database, I did not include it with the sample application. If you intend to run the sample code, create the database and table using the table properties shown as a guide; also, go ahead and add a data source to the project and point the source to this database.

Figure 3: Table Definition

Code: Main Form (frmMain.vb)

The main form of the sample application (see figure 4) contains the controls necessary to browse for an image file, provide the file with a title, load the image file selected into SQL Server, and to open a viewer to examine the images stored in the table.

Figure 4: Main Form of the Application

The form class includes the following imports:

Imports System.IO

Imports System.Data

Imports System.Data.SqlClient

Imports System.Data.SqlTypes

The class also creates two private member variables used to share data between methods exposed in the class; one variable is used to capture the selected image and the other is used to capture the path to the selected image:

Private mImageFile As Image
Private mImageFilePath As String

The find button click event handler calls an Open File Dialog which is used to navigate to and select an image file. The dialog supports searches for bitmaps, jpegs, and gif files. The code used if the click event handler is as follows:

Private Sub btnFind_Click_1(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles btnFind.Click

 

   OpenFileDialog1.Title = "Set Image File"

   OpenFileDialog1.Filter = "Bitmap Files|*.bmp" & _

       "|Gif Files|*.gif|JPEG Files|*.jpg"

   OpenFileDialog1.DefaultExt = "bmp"

   OpenFileDialog1.FilterIndex = 1

   OpenFileDialog1.FileName = ""

   OpenFileDialog1.ShowDialog()

 

   If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.Cancel Then

       Exit Sub

   End If

 

   Dim sFilePath As String

   sFilePath = OpenFileDialog1.FileName

   If sFilePath = "" Then Exit Sub

 

   If System.IO.File.Exists(sFilePath) = False Then

       Exit Sub

   Else

       txtImageFile.Text = sFilePath

       mImageFilePath = sFilePath

   End If

 

End Sub

The code opens the Open File Dialog box with the image types used as a filter and the default extension type set to bitmap. The file selected by the user is validated to make sure that it exists, and if it does, the text box used to display the selected file path is updated to display the path to and name of the file selected by the user. Also, the member variable used to display the path to the image file is also updated.

The load button click event handler is used to load the image and image related data into SQL Server. That code is as follows:

Private Sub btnLoad_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoad.Click

 

        Try

            If (Me.txtImageFile.Text = String.Empty Or Me.txtTitle.Text =

                String.Empty) Then

                MessageBox.Show("Complete both form fields prior to submitting",

                "Missing Values", _

                MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

                Exit Sub

            End If

        Catch ex As Exception

            MessageBox.Show(ex.Message.ToString(), "File Test Error")

        End Try

 

        Dim fs As FileStream = New FileStream(mImageFilePath.ToString(),

        FileMode.Open)

        Dim img As Byte() = New Byte(fs.Length) {}

        fs.Read(img, 0, fs.Length)

        fs.Close()

 

        mImageFile = Image.FromFile(mImageFilePath.ToString())

        Dim imgHeight As Integer = mImageFile.Height

        Dim imgWidth As Integer = mImageFile.Width

        Dim imgLength As Integer = mImageFile.PropertyItems.Length

        Dim imgType As String = Path.GetExtension(mImageFilePath)

        mImageFile = Nothing

 

        Dim strConnect As String

        strConnect = "Data Source=bxswlt;Initial Catalog=ImageGallery;User ID=sa"

        Dim conn As SqlConnection = New SqlConnection(strConnect)

 

        Dim sSQL As String = "INSERT INTO ImageCollection (ImageContent, " & _

                "ImageTitle, ImageType, ImageHeight, ImageWidth) VALUES(" & _

                "@pic, @title, @itype, @iheight, @iwidth)"

 

        Dim cmd As SqlCommand = New SqlCommand(sSQL, conn)

 

        ' image content

        Dim pic As SqlParameter = New SqlParameter("@pic", SqlDbType.Image)

        pic.Value = img

        cmd.Parameters.Add(pic)

 

        ' title

        Dim title As SqlParameter = New SqlParameter("@title",

        System.Data.SqlDbType.VarChar, 50)

        title.Value = txtTitle.Text.ToString()

        cmd.Parameters.Add(title)

 

        ' type

        Dim itype As SqlParameter = New SqlParameter("@itype",

        System.Data.SqlDbType.Char, 4)

        itype.Value = imgType.ToString()

        cmd.Parameters.Add(itype)

 

        ' height

        Dim iheight As SqlParameter = New SqlParameter("@iheight",

        System.Data.SqlDbType.Int)

        iheight.Value = imgHeight

        cmd.Parameters.Add(iheight)

 

        ' width

        Dim iwidth As SqlParameter = New SqlParameter("@iwidth",

        System.Data.SqlDbType.Int)

        iwidth.Value = imgWidth

        cmd.Parameters.Add(iwidth)

 

        Try

            conn.Open()

            cmd.ExecuteNonQuery()

            conn.Close()

            MessageBox.Show("Query executed.", "Image Load")

        Catch ex As Exception

            MessageBox.Show(ex.Message.ToString(), "Data Error")

            Exit Sub

        End Try

End Sub

Within this block of code, the first thing that takes place is a validation that the user has supplied a path to the image file and has provided a title for the file:

Try

     If (Me.txtImageFile.Text = String.Empty Or Me.txtTitle.Text =

         String.Empty) Then

         MessageBox.Show("Complete both form fields prior to submitting",

         "Missing Values", _

         MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

         Exit Sub

     End If

Catch ex As Exception

     MessageBox.Show(ex.Message.ToString(), "File Test Error")

End Try

After confirming the user input, the image file is converted to a byte array. This byte array will subsequently be passed to the database as the image.

Dim fs As FileStream = New FileStream(mImageFilePath.ToString(),

FileMode.Open)

Dim img As Byte() = New Byte(fs.Length) {}

fs.Read(img, 0, fs.Length)

fs.Close()

After the file stream object is closed, the image is loaded into an image from the source file and the loaded image is used to capture the characteristics of the image and to set local variables to contain the image information (e.g., height, width, and type of image). By storing this information in the table, it would be easier to filter for image types in the database and to dynamically create picture box controls sized to accommodate the stored image.

mImageFile = Image.FromFile(mImageFilePath.ToString())

Dim imgHeight As Integer = mImageFile.Height

Dim imgWidth As Integer = mImageFile.Width

Dim imgLength As Integer = mImageFile.PropertyItems.Length

Dim imgType As String = Path.GetExtension(mImageFilePath)

mImageFile = Nothing

Once the local variables are set and the image disposed of, the insert query used to submit the data to the database is configured: (update the connection string to match your settings; and no, you would not really put your connection string into the application in this manner, instead, use the one in the app.config file)

Dim strConnect As String

strConnect = "Data Source=bxswlt;Initial Catalog=ImageGallery;User ID=sa"

Dim conn As SqlConnection = New SqlConnection(strConnect)

 

Dim sSQL As String = "INSERT INTO ImageCollection (ImageContent, " & _

        "ImageTitle, ImageType, ImageHeight, ImageWidth) VALUES(" & _

        "@pic, @title, @itype, @iheight, @iwidth)"

 

Dim cmd As SqlCommand = New SqlCommand(sSQL, conn)

After the connection is created and the command text set, the parameters are defined, and each is added to the command's parameter collection:

' image content

Dim pic As SqlParameter = New SqlParameter("@pic", SqlDbType.Image)

pic.Value = img

cmd.Parameters.Add(pic)

 

' title

Dim title As SqlParameter = New SqlParameter("@title",

System.Data.SqlDbType.VarChar, 50)

title.Value = txtTitle.Text.ToString()

cmd.Parameters.Add(title)

 

' type

Dim itype As SqlParameter = New SqlParameter("@itype",

System.Data.SqlDbType.Char, 4)

itype.Value = imgType.ToString()

cmd.Parameters.Add(itype)

 

' height

Dim iheight As SqlParameter = New SqlParameter("@iheight",

System.Data.SqlDbType.Int)

iheight.Value = imgHeight

cmd.Parameters.Add(iheight)

 

' width

Dim iwidth As SqlParameter = New SqlParameter("@iwidth",

System.Data.SqlDbType.Int)

iwidth.Value = imgWidth

cmd.Parameters.Add(iwidth)

After everything is set, the only thing remaining is to post the data to the database:

Try

    conn.Open()

    cmd.ExecuteNonQuery()

    conn.Close()

    MessageBox.Show("Query executed.", "Image Load")

Catch ex As Exception

    MessageBox.Show(ex.Message.ToString(), "Data Error")

    Exit Sub

End Try

Assuming that everything posted properly, the user will be notified that the query has completed; if the insert fails, the user will be provided with a description of the error.

The only other code in the main form is used to handle the viewer button click; this handler creates a new instance of the viewer and displays it to the user:

Private Sub btnViewer_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles btnViewer.Click

    Dim f As New frmViewer()

    f.Show()

End Sub

Code:  Viewer (frmViewer.vb)

This is going to be a short section as the viewer does not contain any hand written code. The viewer contains a binding navigator and a few text fields dragged onto the form from the project data source. The text fields are bound to the binding source and are updated through the binding navigator. The picture box control used to display the image has its data bindings set to point to the image data contained in the database. Whenever the binding navigator is sequenced up or down, the image and bound text are updated to the display the values associated with the current record.

Figure 5: Picture Box Control Data Bindings

Summary

Whether or not it is a terrific idea to store images in a database is debatable, some would advocate the storage of path strings in the database to reduce the overhead in lieu of actually storing the images which is certainly a valid consideration. In systems involving large volumes of imagery data, reliance upon stored paths could very well be a requirement. In other instances where only a limited amount of imagery data is stored, there is less of an argument to be made against it. 

In the simple viewer provided, the display of the images was managed entirely by binding it to the image source from the image content database column; it is possible to reconstruct the image manually from the byte array but I did not include a description of that process as it seems likely that binding the control to the record would be the sufficient for most situations.


Login to add your contents and source code to this article
 About the author
 
Scott Lysle
Freelance software developer residing in Alabama. Bachelors, Masters Degrees from Wichita State University. I spent the first half of my career working on aircraft controls and displays and in that time I worked on the cockpits for the OH-58 AHIP, the AH-1W, the V-22, the F-22, the C-130J, the C-5 AMP, AWACS, JPATS, and a few others. Since 1997 I have been largely involved with Windows and web development, GIS application development, consumer electronics development (embedded linux/java), but still sometimes work on aircraft and military projects, the most recent of which was the presidential transport helicopter. I tend to work primarily with C/C++, Java, VB, and C#.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
SQL and .NET performance profiling in one place
Investigate SQL and .NET code side-by-side with ANTS Performance Profiler 6, so you can see which is causing the problem without switching tools.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from DevExpress - Absolutely Free-of-Charge without any royalties or distribution costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin edit, tab control and so much more!

DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Become a Sponsor
 Comments
wtf?? by adas On April 4, 2009
no entendi j
Reply | Email | Delete | Modify | 
Re: wtf?? by Scott On April 4, 2009

Dè saoghal a th'agad?

Reply | Email | Delete | Modify | 
Nice by sam On June 28, 2009
Nice Code mate ... Well done
Reply | Email | Delete | Modify | 
Good Work by Aguirre On July 16, 2009
Nice one really help me a lots!
God bless!
Reply | Email | Delete | Modify | 
sql inage upload by manikantan On February 19, 2010

Prerequisites


  • Knowledge in Using MS SQL Server Stored Procedure 
  • Knowledge in C#.NET Windows Application
  • Knowledge in ADO.NET 

 

Introduction

How to Store or Save Image in MS SQL Server table

 

This article talks about using Images data type in MS SQL Server and also provides sample code to store  images in MS SQL Server database.

To store an image in to sql server, you need to read image file into a byte array. Once you have image data in byte array, you can easity store this image data in sql server using sql parameters. Following code explains you how to convert the image data  into byte array using byte img = Convert.Tobyte(img);

.  

 

Using the code

A brief description of how to use the article or code. The class names, the methods and properties, any tricks or tips.

Blocks of code should be set as style "Formatted" like this:

Collapse
using System.Data;
using System.Data.Sql
using System.Data.SqlClient;

using System.Web;


using System.Web.Services;





public class FileUploader: System.Web.Services.WebService



{






""MsoNormal""> SqlConnection myConnection = new SqlConnection("Data Source=server name ;Initial Catalog=database name; User ID=username;
Password='password';"
);



SqlCommand myCommand = new SqlCommand();



string queryString = "";


public string UploadFile(byte[] f, string fileName)




{



// the byte array argument contains the content of the file



// the string argument contains the name and extension


// of the file passed in the byte array




string nm = data[0];



string sn =data[1];



string bn =data[2];


string st = data[3];




byte img = Convert.Tobyte(img);



myConnection.Open();


queryString = "INSERT INTO tablename(Name,SchemeName,BeneficiarName,Status,Photo)"


+ "VALUES('" + nm + "','" + sn + "','"+ bn +"','" + st + "',@img,'")";


myCommand.Parameters.AddWithValue("

@img",f);






myCommand.Connection = myConnection;



myCommand.CommandType = CommandType.Text;



myCommand.CommandText = queryString;



int res = myCommand.ExecuteNonQuery();


myConnection.Close();




if (res > 0)




{



strres = "File Uploaded successfully";


}




else
{
strres = "
File not uploaded";



}
return strres;



}




















 

Requirements

Visual Studio.Net 2005

.Net Framework 2.0 

MS SQL Server 2000 database or MS SQL Server 2005 database.
Reply | Email | Delete | Modify | 
asd by watches On July 11, 2010
n general Hogan are made from very flexible materials and have a rubber sole. When they first entered the market Hogan scarpe donna were quite simple but the growing popularity has increased competition and spurned a number of new designs. While other styles of hogan donna such as casual loafers or dress shoes tend to come in one generic mould, Hogan uomo are designed to support and contrast an athlete s foot.
Reply | Email | Delete | Modify | 
Good by Golam On August 7, 2010
Very Useful
Reply | Email | Delete | Modify | 
ASP.Net 4 Hosting is here
 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2010.8.14
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.