Click here to Skip to main content
11,636,300 members (79,286 online)
Click here to Skip to main content

Save An Image Into SQL Server 2000 Database

, 24 Feb 2005 CPOL 582.9K 13.4K 174
Rate this:
Please Sign up or sign in to vote.
How to upload files to Web pages in ASP.NET? How to read an image from a database using ADO.NET and display it in a Web page?

Abstract

.NET is the new distributed computing platform developed by Microsoft and ASP.NET is its programming model for web development. The intent of this article is to get a good experience in developing data driven ASP.NET Web Forms applications by means of a real world application. This application will teach you how to save an image file into a database and how to retrieve it from the database. It uses ADO.NET as the data access mechanism, C# as the development language, and SQL Server 2000 as the backend database.

Overview of the Solution

Normally, images are saved in the web server folder, not in the database; this is for larger file size category. In some cases like, in bank, for example, they scan the user signatures as image files and save that file into the database.

  • Database schema

    MS SQL Server 2000 is used as the backend database for this small demonstration. And I used a special data type in SQL Server called image. The image data type is used to save the image into the database.

  • Controls used in this application
    • System.Web.UI.HtmlControls.HtmlInputFile
    • System.Web.UI.WebControls.TextBox
    • System.Web.UI.WebControls.Button
  • Namespaces used in this application:
    using System.Data.SqlClient;
    using System.Drawing;
    using System.Data;
    using System.IO;
    using System.Drawing.Imaging;

Solution with Code

Use the HtmlInputFile class, which you can declare an instance of with an <input type="file" runat="server"/> tag. The following example is a complete ASPX file that lets a user upload an image file and a comment describing the image. The OnUpload method writes the image and the comment to a table named Pictures in a SQL Server database named iSense.

// Source Code for Save the image file into the database

public void OnUpload(Object sender, EventArgs e)
{
    // Create a byte[] from the input file
    int len = Upload.PostedFile.ContentLength;
    byte[] pic = new byte[len];
    Upload.PostedFile.InputStream.Read (pic, 0, len);
    // Insert the image and comment into the database
    SqlConnection connection = new 
      SqlConnection (@"server=INDIA\INDIA;database=iSense;uid=sa;pwd=india");
    try
    {
        connection.Open ();
        SqlCommand cmd = new SqlCommand ("insert into Image " 
          + "(Picture, Comment) values (@pic, @text)", connection);
        cmd.Parameters.Add ("@pic", pic);
        cmd.Parameters.Add ("@text", Comment.Text);
        cmd.ExecuteNonQuery ();
    }
    finally 
    {
        connection.Close ();
    }
}

The above created function is called using the onClick property of a button.

How do I read an image from a database using ADO.NET and display it in a Web page?

Here, I used the web page to display the image and not any other control. The following is the code for displaying the image from the database.

private void Page_Load(object sender, System.EventArgs e)
{
    // Put user code to initialize the page here
    MemoryStream stream = new MemoryStream ();
    SqlConnection connection = new 
      SqlConnection (@"server=INDIA\INDIA;database=iSense;uid=sa;pwd=india");
    try
    {
        connection.Open ();
        SqlCommand command = new 
          SqlCommand ("select Picture from Image", connection);
        byte[] image = (byte[]) command.ExecuteScalar ();   
        stream.Write (image, 0, image.Length);
        Bitmap bitmap = new Bitmap (stream);
        Response.ContentType = "image/gif";
        bitmap.Save (Response.OutputStream, ImageFormat.Gif);
    } 
    finally
    {
        connection.Close ();
        stream.Close ();
    }
}

The GDI+ functions offer a rich set of features for managing and modifying image data. This article's examples offer only a glimpse into the functionality you can leverage using the classes available in the System.Drawing and System.Drawing.Imaging namespaces. For example, you can develop applications for storing and managing image files on the Web, or you can provide a simple, easily deployed application that enables users to manipulate images.

How to run this application? First, create a virtual directory and put the project files into the virtual directory. And then change the server name, database name, and table name in the following statement.

SqlConnection connection = new SqlConnection
        ("server=localhost;database=mypictures;uid=sa;pwd=");

and publish the project to get the best results.

License

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

Share

About the Author

vivekthangaswamy
Software Developer (Senior) Swordface
Australia Australia
No Biography provided

You may also be interested in...

Comments and Discussions

 
GeneralSave An Image Into SQL Server 2000 Database Pin
awadhendra tiwari23-May-11 6:53
memberawadhendra tiwari23-May-11 6:53 
GeneralMy vote of 4 Pin
patilthegodfather23-Dec-10 23:40
memberpatilthegodfather23-Dec-10 23:40 
GeneralMy vote of 1 Pin
afedor20-Feb-10 3:57
memberafedor20-Feb-10 3:57 
GeneralThx, it's help alot in my assignment Pin
ragk885-Aug-09 6:46
memberragk885-Aug-09 6:46 
Laugh | :laugh:
GeneralI want to retrieve image from sql server 2000 using c#.net 2003 Pin
wingaurav3-May-09 4:16
memberwingaurav3-May-09 4:16 
GeneralErorr Pin
yoyonimol23-Apr-09 16:57
memberyoyonimol23-Apr-09 16:57 
GeneralIT WORKS!!!! Thanks Vivek! Pin
lukaz101023-Apr-09 8:58
memberlukaz101023-Apr-09 8:58 
GeneralRe: thank you friend, it's working Pin
Member 1076117120-Apr-14 1:57
memberMember 1076117120-Apr-14 1:57 
GeneralThank You Man Pin
minatharwat18-Mar-09 0:39
memberminatharwat18-Mar-09 0:39 
GeneralThank You Pin
minatharwat18-Mar-09 0:38
memberminatharwat18-Mar-09 0:38 
GeneralCode to display image in gridview Pin
tab_nil13-Mar-09 1:40
membertab_nil13-Mar-09 1:40 
GeneralThank you!! Pin
Amol_B16-Dec-08 3:42
memberAmol_B16-Dec-08 3:42 
QuestionHow to display image??? Pin
smetaljuan29-Oct-08 8:01
membersmetaljuan29-Oct-08 8:01 
GeneralStore and Retrieve image without using temp file... Pin
anandmmsoft12-Oct-08 20:41
memberanandmmsoft12-Oct-08 20:41 
GeneralNice Article Pin
irshadmohideen30-Aug-08 3:58
memberirshadmohideen30-Aug-08 3:58 
Generalthank you Pin
7sepehr22-Jun-08 21:07
member7sepehr22-Jun-08 21:07 
Generalsql image application Pin
bapu28898-Jun-08 6:53
memberbapu28898-Jun-08 6:53 
Generalcreate image in sql HLPPP!!!@!@! Pin
yaozhong8-May-08 17:36
memberyaozhong8-May-08 17:36 
QuestionHow to resize (zoom in) Image before save to sql Pin
Doan Quynh21-Apr-08 0:22
memberDoan Quynh21-Apr-08 0:22 
GeneralGood work Pin
Alex Archambault28-Nov-07 10:18
memberAlex Archambault28-Nov-07 10:18 
Generalvery goood topic Pin
mkazim8526-Oct-07 1:42
membermkazim8526-Oct-07 1:42 
GeneralGood article [modified] Pin
Bino B4-Oct-07 22:06
memberBino B4-Oct-07 22:06 
GeneralStore Image In SQL 2000 Pin
Abhijit Salokhe16-Sep-07 23:03
memberAbhijit Salokhe16-Sep-07 23:03 
GeneralRe: Store Image In SQL 2000 Pin
vivekthangaswamy18-Sep-07 2:41
membervivekthangaswamy18-Sep-07 2:41 
Questioninvalid paramer(stream) exception Pin
vinuparli23-May-07 20:18
membervinuparli23-May-07 20:18 
AnswerRe: invalid paramer(stream) exception Pin
vivekthangaswamy4-Jun-07 21:28
membervivekthangaswamy4-Jun-07 21:28 
AnswerRe: invalid paramer(stream) exception Pin
The Knowledge5-Oct-07 1:52
memberThe Knowledge5-Oct-07 1:52 
GeneralRe: invalid paramer(stream) exception Pin
Md.Alauddin17-Feb-11 4:52
memberMd.Alauddin17-Feb-11 4:52 
QuestionSave image through DataBase through InagePath Pin
gs_dhaliwal27-Feb-07 0:51
membergs_dhaliwal27-Feb-07 0:51 
AnswerRe: Save image through DataBase through InagePath Pin
vivekthangaswamy27-Feb-07 2:02
membervivekthangaswamy27-Feb-07 2:02 
Generalretriving image from sqlserver2000 using c# Pin
Member #303726316-Jan-07 17:43
memberMember #303726316-Jan-07 17:43 
QuestionSave and retreive files (as word document, excel files) in the database Pin
sagi399920-Dec-06 19:55
membersagi399920-Dec-06 19:55 
AnswerRe: Save and retreive files (as word document, excel files) in the database Pin
Patrish5-Jan-07 9:23
memberPatrish5-Jan-07 9:23 
AnswerRe: Save and retreive files (as word document, excel files) in the database Pin
krishnakumark6-Feb-07 23:40
memberkrishnakumark6-Feb-07 23:40 
Questiondo program in c# + asp.net+sql Pin
al_wrood16-Oct-06 23:10
memberal_wrood16-Oct-06 23:10 
AnswerRe: do program in c# + asp.net+sql Pin
vivekthangaswamy20-Oct-06 6:38
membervivekthangaswamy20-Oct-06 6:38 
GeneralVery useful one Pin
Aravind.Kumar19-Sep-06 2:36
memberAravind.Kumar19-Sep-06 2:36 
GeneralRe: Very useful one Pin
vivekthangaswamy20-Oct-06 6:39
membervivekthangaswamy20-Oct-06 6:39 
Generalinvalid parameter exception Pin
VishalSharmaDev17-Aug-06 7:19
memberVishalSharmaDev17-Aug-06 7:19 
GeneralRe: invalid parameter exception Pin
irspaul13-Jan-07 3:48
memberirspaul13-Jan-07 3:48 
Generali worked out this coding. than how to retrieve multiple images from sql-server Pin
K.Gajalakshmi9-Aug-06 7:57
memberK.Gajalakshmi9-Aug-06 7:57 
AnswerRe: i worked out this coding. than how to retrieve multiple images from sql-server Pin
Quartz...17-Aug-06 7:41
memberQuartz...17-Aug-06 7:41 
Generalinvalid parameter exception Pin
rrd_angelofD23-Jul-06 20:03
memberrrd_angelofD23-Jul-06 20:03 
GeneralRe: invalid parameter exception Pin
The Knowledge5-Oct-07 1:54
memberThe Knowledge5-Oct-07 1:54 
Questionjust take the first picture..why? Pin
ozones25-Jun-06 17:40
memberozones25-Jun-06 17:40 
AnswerRe: just take the first picture..why? Pin
Johnaer26-Mar-07 13:26
memberJohnaer26-Mar-07 13:26 
GeneralRe: just take the first picture..why? Pin
vinuparli23-May-07 20:08
membervinuparli23-May-07 20:08 
AnswerRe: just take the first picture..why? Pin
Akajasimafat8-Jan-08 18:41
memberAkajasimafat8-Jan-08 18:41 
QuestionLoading Image Pin
Bhanumathi S22-Jun-06 23:05
memberBhanumathi S22-Jun-06 23:05 
QuestionIs it possible to Upload text file same way? Pin
PrimalAgsoft14-Jun-06 1:28
memberPrimalAgsoft14-Jun-06 1:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.150728.1 | Last Updated 25 Feb 2005
Article Copyright 2005 by vivekthangaswamy
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid