Click here to Skip to main content
Click here to Skip to main content

Save An Image Into SQL Server 2000 Database

By , 24 Feb 2005
 

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
Architect
India India
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 1membermostafa3586 Feb '13 - 12:23 
file not run
GeneralthnksmemberMember 87883404 Apr '12 - 22:18 
thnks sir..................
QuestionTHANK YOU.memberAlejandro Alas26 Mar '12 - 6:59 
THE WAS MAKE THAT I NEED.
QuestionNICE- ONE MORE DOUBTmemberRamkumar0619 Feb '12 - 0:47 
i have a image control. i want the image from db is to be loaded into that image control.   Thanks
GeneralMy vote of 3membersugumar srinuvas20 Oct '11 - 3:26 
if more than a image is uploaded means, while retriving it returns 1s image only......
QuestionThanxmemberrangachisi20 Oct '11 - 2:33 
Easy to follow and it works   thanx man
QuestionSave and Open a Image into SQL 2000 using Visual Basic 6memberMian Zahid6 Oct '11 - 19:17 
Hello!!!!!!!   i want to save and open a image into sql 2000 using the VB 6.   here want to help????????   Any body Help me?????   Thanks   Regards....
Questionhow to read imagemembersaravanakumar.nr19 Jul '11 - 20:42 
i want 2 know the image upload and retrieve in SQL-server using C# code
GeneralSave An Image Into SQL Server 2000 Databasememberawadhendra tiwari23 May '11 - 6:53 
Its a nice article. I had also write a small blog in which we see that how to insert image in sqlserver using c#.   http://www.mindstick.com/Blog/184/Save%20image%20in%20SqlServer%20using%20C[^] Please take a look at here. Its useful for you.
GeneralMy vote of 4memberpatilthegodfather23 Dec '10 - 23:40 
Great!
GeneralMy vote of 1memberafedor20 Feb '10 - 3:57 
Outdated, poor or no explanations, it doesn't work and not worth the trouble to try to fix it.
GeneralThx, it's help alot in my assignmentmemberragk885 Aug '09 - 6:46 
GeneralI want to retrieve image from sql server 2000 using c#.net 2003memberwingaurav3 May '09 - 4:16 
I am making a web page application in which i m getting one problem, i have a table in sql server 2000 which contains Id, Image columns, i am able to save images with id in sql server 2000 and also retrieving the same on my web page. But when i retrieve image it shows on whole web page which i...
GeneralErorrmemberyoyonimol23 Apr '09 - 16:57 
Hi, I ard follow up your code as below then i've got this message error "Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'."   MemoryStream stream = new MemoryStream(); try { conn.Open(); ...
GeneralIT WORKS!!!! Thanks Vivek!memberlukaz101023 Apr '09 - 8:58 
Thank you very much for your introduction Vivek. Have a good day   Lukaz
GeneralThank You Manmemberminatharwat18 Mar '09 - 0:39 
Big Thanks it really helped me
GeneralThank Youmemberminatharwat18 Mar '09 - 0:38 
Big Thanks it really helped me
GeneralCode to display image in gridviewmembertab_nil13 Mar '09 - 1:40 
Can any one send me the code to display the image in the gridview control. I had tried in many ways and I am on this task from 5 days. my code is: -----------   using System; using System.Data; using System.IO; using System.Data.OleDb; using System.Configuration; using...
GeneralThank you!!memberAmol_B16 Dec '08 - 3:42 
I was looking for the same. Thank you sir for Help!!   Amol
QuestionHow to display image???membersmetaljuan29 Oct '08 - 8:01 
Hi, my name is Juan Solórzano, from Venezuela this is an excelent article! thanks!   My question is about to show the image in a ImageControl, because your article set it on a new page, please tell me how to do that   thanks again   Juan
GeneralStore and Retrieve image without using temp file...memberanandmmsoft12 Oct '08 - 20:41 
Hello sir,   I am using ASP.Net & C#(code behind)....   my problem is "i have to upload a image to a database field(blob) and immediatly i have to display in a imagebox in a web form without saving in any temporary folder". process is   upload image -> store in database...
GeneralNice Articlememberirshadmohideen30 Aug '08 - 3:58 
Simple and nice article. This article provided instant help in finding a quick way to programatically save images in sql database. Thank you.
Generalthank youmember7sepehr22 Jun '08 - 21:07 
thank you. it help me.
Generalsql image applicationmemberbapu28898 Jun '08 - 6:53 
hi i am new in vb.net and now i am learning sql and i have create one small application with sql and in table there are two columns one is imageID and second one is Image i can save and delete image with sql database but problme is when i add or delete image is dosent shows changes i mean if...
Generalcreate image in sql HLPPP!!!@!@!memberyaozhong8 May '08 - 17:36 
how to insert images into sql database using sql sever management express ?

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

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