Click here to Skip to main content
6,595,444 members and growing! (15,878 online)
Email Password   helpLost your password?
Web Development » Charts, Graphs and Images » Images and multimedia     Intermediate License: The Code Project Open License (CPOL)

Save An Image Into SQL Server 2000 Database

By vivekthangaswamy

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?
C#, SQL, Windows, .NET 1.1, ASP.NET, SQL 2000, VS.NET2003, DBA, Dev
Posted:25 Feb 2005
Views:348,720
Bookmarked:139 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
72 votes for this article.
Popularity: 7.58 Rating: 4.08 out of 5
7 votes, 9.7%
1
2 votes, 2.8%
2
2 votes, 2.8%
3
19 votes, 26.4%
4
42 votes, 58.3%
5

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)

About the Author

vivekthangaswamy


Member

Occupation: Architect
Location: India India

Other popular Charts, Graphs and Images articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 70 (Total in Forum: 70) (Refresh)FirstPrevNext
GeneralThx, it's help alot in my assignment Pinmemberragk887:46 5 Aug '09  
GeneralI want to retrieve image from sql server 2000 using c#.net 2003 Pinmemberwingaurav5:16 3 May '09  
GeneralErorr Pinmemberyoyonimol17:57 23 Apr '09  
GeneralIT WORKS!!!! Thanks Vivek! Pinmemberlukaz10109:58 23 Apr '09  
GeneralThank You Man Pinmemberminatharwat1:39 18 Mar '09  
GeneralThank You Pinmemberminatharwat1:38 18 Mar '09  
GeneralCode to display image in gridview Pinmembertab_nil2:40 13 Mar '09  
GeneralThank you!! PinmemberAmol_B4:42 16 Dec '08  
GeneralHow to display image??? Pinmembersmetaljuan9:01 29 Oct '08  
GeneralStore and Retrieve image without using temp file... Pinmemberanandmmsoft21:41 12 Oct '08  
GeneralNice Article Pinmemberirshadmohideen4:58 30 Aug '08  
Generalthank you Pinmember7sepehr22:07 22 Jun '08  
Generalsql image application Pinmemberbapu28897:53 8 Jun '08  
Generalcreate image in sql HLPPP!!!@!@! Pinmemberyaozhong18:36 8 May '08  
GeneralHow to resize (zoom in) Image before save to sql PinmemberDoan Quynh1:22 21 Apr '08  
GeneralGood work PinmemberAlex Archambault11:18 28 Nov '07  
Generalvery goood topic Pinmembermkazim852:42 26 Oct '07  
GeneralGood article [modified] PinmemberBino B23:06 4 Oct '07  
GeneralStore Image In SQL 2000 PinmemberAbhijit Salokhe0:03 17 Sep '07  
GeneralRe: Store Image In SQL 2000 Pinmembervivekthangaswamy3:41 18 Sep '07  
Questioninvalid paramer(stream) exception Pinmembervinuparli21:18 23 May '07  
AnswerRe: invalid paramer(stream) exception Pinmembervivekthangaswamy22:28 4 Jun '07  
AnswerRe: invalid paramer(stream) exception PinmemberThe Knowledge2:52 5 Oct '07  
QuestionSave image through DataBase through InagePath Pinmembergs_dhaliwal1:51 27 Feb '07  
AnswerRe: Save image through DataBase through InagePath Pinmembervivekthangaswamy3:02 27 Feb '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 25 Feb 2005
Editor: Smitha Vijayan
Copyright 2005 by vivekthangaswamy
Everything else Copyright © CodeProject, 1999-2009
Web21 | Advertise on the Code Project