Click here to Skip to main content
11,429,154 members (62,782 online)
Click here to Skip to main content

Storing and Retrieving Images from SQL Server using Microsoft .NET

, 30 Jun 2005
Rate this:
Please Sign up or sign in to vote.
Storing and retrieving images from SQL Server using Microsoft .NET.

Introduction

This article is about storing and retrieving images from database in Microsoft .NET using C#.

Tools Used

  • SQL Server 2000
  • Microsoft .NET Version 1.1
  • C# (Windows Forms based application)

Storing Images

  1. Create a table in a SQL Server 2000 database which has at least one field of type IMAGE.

    Here is the script I used:

    CREATE TABLE [dbo].[tblImgData] (
    
            [ID] [int] NOT NULL ,
    
            [Name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    
            [Picture] [image] NULL 
    
    ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
  2. Actually IMAGE field is just holding the reference to the page containing the binary data so we have to convert our image into bytes.
    1. I used a file open dialog box to locate the file.
      this.openFileDialog1.ShowDialog(this);
      string strFn=this.openFileDialog1.FileName;
    2. By using FileInfo class, I retrieved the file size:
      FileInfo fiImage=new FileInfo(strFn);
    3. Declare an array of that size.
      this.m_lImageFileLength=fiImage.Length;
      m_barrImg=new byte[Convert.ToInt32(this.m_lImageFileLength)];
    4. By using FileStream object, I filled the byte array.
      FileStream fs=new FileStream(strFn,FileMode.Open, 
                        FileAccess.Read,FileShare.Read);
      int iBytesRead=fs.Read(m_barrImg,0,
                     Convert.ToInt32(this.m_lImageFileLength));
      fs.Close();

    Complete Load Image Code

    protected void LoadImage()
    {
        try
        {
            this.openFileDialog1.ShowDialog(this);
            string strFn=this.openFileDialog1.FileName;
            this.pictureBox1.Image=Image.FromFile(strFn);
            FileInfo fiImage=new FileInfo(strFn);
            this.m_lImageFileLength=fiImage.Length;
            FileStream fs=new FileStream(strFn,FileMode.Open, 
                              FileAccess.Read,FileShare.Read);
            m_barrImg=new byte[Convert.ToInt32(this.m_lImageFileLength)];
            int iBytesRead = fs.Read(m_barrImg,0, 
                             Convert.ToInt32(this.m_lImageFileLength));
            fs.Close();
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
  3. Saving byte array data to database.
    1. Create command text to insert record.
      this.sqlCommand1.CommandText= 
        "INSERT INTO tblImgData(ID,Name,Picture)" + 
        " values(@ID,@Name,@Picture)";
    2. Create parameters.
      this.sqlCommand1.Parameters.Add("@ID",
                 System.Data.SqlDbType.Int, 4);
      this.sqlCommand1.Parameters.Add("@Name", 
                 System.Data.SqlDbType.VarChar, 50);
      
      this.sqlCommand1.Parameters.Add("@Picture", 
                 System.Data.SqlDbType.Image);

      Notice “@Picture” has “SqlDbType.Image” because it is of IMAGE type Field.

    3. Provide the value to the parameters.
      this.sqlCommand1.Parameters["@ID"].Value=this.editID.Text;
      this.sqlCommand1.Parameters["@Name"].Value=this.editName.Text;
      
      this.sqlCommand1.Parameters["@Picture"].Value=this.m_barrImg;

      this.m_barrImg” is a byte array which we filled in the previous step.

    4. Now execute non-query for saving the record to the database.
      int iresult=this.sqlCommand1.ExecuteNonQuery();

    Complete Save Image Code

    private void btnSave_Click(object sender, System.EventArgs e)
    {
        try
        {
            this.sqlConnection1.Open();
            if (sqlCommand1.Parameters.Count ==0 )
            {
                this.sqlCommand1.CommandText="INSERT INTO tblImgData(ID," + 
                               " Name,Picture) values(@ID,@Name,@Picture)";
                this.sqlCommand1.Parameters.Add("@ID", 
                                 System.Data.SqlDbType.Int,4);
                this.sqlCommand1.Parameters.Add("@Name", 
                                 System.Data.SqlDbType.VarChar,50);
                this.sqlCommand1.Parameters.Add("@Picture", 
                                 System.Data.SqlDbType.Image);
            }
    
            this.sqlCommand1.Parameters["@ID"].Value=this.editID.Text;
            this.sqlCommand1.Parameters["@Name"].Value=this.editName.Text;
            this.sqlCommand1.Parameters["@Picture"].Value=this.m_barrImg;
    
            int iresult=this.sqlCommand1.ExecuteNonQuery();
            MessageBox.Show(Convert.ToString(iresult));
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            this.sqlConnection1.Close();
        }
    }

Retrieving Image

Retrieving images from the database is the exact reverse process of saving images to the database.

  1. First create command text to retrieve record.
    SqlCommand cmdSelect = new SqlCommand("select Picture" + 
                           " from tblImgData where ID=@ID", 
                           this.sqlConnection1);
  2. Create parameter for the query.
    cmdSelect.Parameters.Add("@ID",SqlDbType.Int,4);
  3. Provide value to the parameter.
    cmdSelect.Parameters["@ID"].Value=this.editID.Text;
  4. Open database connection and execute “ExecuteScalar” because we want only “IMAGE” column data back.
    byte[] barrImg=(byte[])cmdSelect.ExecuteScalar();

    As the execute scalar returns data of “Object” data type, we cast it to byte array.

  5. Save this data to a temporary file.
    string strfn=Convert.ToString(DateTime.Now.ToFileTime());
    FileStream fs=new FileStream(strfn,FileMode.CreateNew,FileAccess.Write);
    fs.Write(barrImg,0,barrImg.Length);
    fs.Flush();
    fs.Close();
  6. And display the image anywhere you want to display.
    pictureBox1.Image=Image.FromFile(strfn);

Complete Image Retrieving Code

private void btnLoad_Click(object sender, System.EventArgs e)
{
    try
    {
        SqlCommand cmdSelect=new SqlCommand("select Picture" + 
              " from tblImgData where ID=@ID",this.sqlConnection1);
        cmdSelect.Parameters.Add("@ID",SqlDbType.Int,4);
        cmdSelect.Parameters["@ID"].Value=this.editID.Text;

        this.sqlConnection1.Open();
        byte[] barrImg=(byte[])cmdSelect.ExecuteScalar();
        string strfn=Convert.ToString(DateTime.Now.ToFileTime());
        FileStream fs=new FileStream(strfn, 
                          FileMode.CreateNew, FileAccess.Write);
        fs.Write(barrImg,0,barrImg.Length);
        fs.Flush();
        fs.Close();
        pictureBox1.Image=Image.FromFile(strfn);
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        this.sqlConnection1.Close();
    }
}

Bibliography

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Kazim Sardar Mehdi
Web Developer
Denmark Denmark
No Biography provided

Comments and Discussions

 
QuestionError!!!!!!!!! Pin
suhail ahmad26-Apr-12 23:43
membersuhail ahmad26-Apr-12 23:43 
AnswerRe: Error!!!!!!!!! Pin
Wimpie Ratte15-May-12 7:45
memberWimpie Ratte15-May-12 7:45 
Questionquestion Pin
Member 884454618-Apr-12 2:15
memberMember 884454618-Apr-12 2:15 
GeneralMy vote of 5 Pin
MOHIT KUMAR VERMA7-Mar-12 6:17
memberMOHIT KUMAR VERMA7-Mar-12 6:17 
GeneralExporting images from the Club site template to jpeg files Pin
Martin Kadlec, Czech rep.17-May-11 1:56
memberMartin Kadlec, Czech rep.17-May-11 1:56 
GeneralRe: Exporting images from the Club site template to jpeg files Pin
awadhendra tiwari22-Aug-11 5:51
memberawadhendra tiwari22-Aug-11 5:51 
GeneralMy vote of 5 Pin
harsha narayana31-Mar-11 22:12
memberharsha narayana31-Mar-11 22:12 
GeneralOut of Memory Pin
curious_mind24-Feb-11 0:40
membercurious_mind24-Feb-11 0:40 
GeneralOut of Memoty error Pin
ashoks10426-Jul-10 9:20
memberashoks10426-Jul-10 9:20 
GeneralThank You Pin
John Hemphill11-May-10 12:59
memberJohn Hemphill11-May-10 12:59 
GeneralNice Pin
Nitin Sawant30-Nov-09 19:42
memberNitin Sawant30-Nov-09 19:42 
QuestionHow Do I delete the temporary files created? Pin
NastyJoe7-Sep-09 5:53
memberNastyJoe7-Sep-09 5:53 
GeneralThank you kazim Sir Pin
rahulxlash28-Aug-09 2:07
memberrahulxlash28-Aug-09 2:07 
GeneralNice post! [modified] Pin
CrazyTasty18-Aug-09 21:30
memberCrazyTasty18-Aug-09 21:30 
GeneralThank you very much Pin
hamid_ss25-Jul-09 11:16
memberhamid_ss25-Jul-09 11:16 
Generalsimilar code in .net 2003 and sql 2000 Pin
sanjaydsm16767-May-09 1:27
membersanjaydsm16767-May-09 1:27 
GeneralMy vote of 2 Pin
maroju.raghava21-Jan-09 22:40
membermaroju.raghava21-Jan-09 22:40 
GeneralMy vote of 2 Pin
maroju.raghava21-Jan-09 22:38
membermaroju.raghava21-Jan-09 22:38 
Newssql server related interesting articles [modified] Pin
codemobile31-Oct-08 20:57
membercodemobile31-Oct-08 20:57 
Generalthis code works fine but it inserts null value in to the database........... Pin
kkwaghpriya22-Jul-08 19:26
memberkkwaghpriya22-Jul-08 19:26 
GeneralExport Gridview data to sql database table Pin
naresh150727-Jun-08 0:10
membernaresh150727-Jun-08 0:10 
GeneralRe: Export Gridview data to sql database table Pin
Deepsoftindia6-Dec-08 0:32
memberDeepsoftindia6-Dec-08 0:32 
GeneralProblem regarding viewing of images from sql Pin
naresh150723-Jun-08 2:31
membernaresh150723-Jun-08 2:31 
GeneralSave code Pin
honeybone27-Nov-07 12:10
memberhoneybone27-Nov-07 12:10 
GeneralRe: Save code Pin
naresh150723-Jun-08 19:55
membernaresh150723-Jun-08 19:55 
GeneralRe: Save code Pin
naresh150727-Jun-08 0:09
membernaresh150727-Jun-08 0:09 
GeneralPlease help, not working with 2005 Pin
Ferrari_X22-Oct-07 13:42
memberFerrari_X22-Oct-07 13:42 
GeneralRe: Please help, not working with 2005 Pin
naresh150723-Jun-08 19:19
membernaresh150723-Jun-08 19:19 
Generalthis code works well, but a few issues... Pin
roger_2716-Aug-07 7:28
memberroger_2716-Aug-07 7:28 
GeneralRe: this code works well, but a few issues... Pin
roger_2716-Aug-07 8:20
memberroger_2716-Aug-07 8:20 
QuestionProblem in Conversion From System....Drawing.Image to System...WebControl.Image Pin
nareshgoradara1-Jun-07 22:25
membernareshgoradara1-Jun-07 22:25 
GeneralImage Storage Pin
samshah51219-May-07 7:18
membersamshah51219-May-07 7:18 
GeneralRe: Image Storage Pin
Kazim Sardar Mehdi20-May-07 19:52
memberKazim Sardar Mehdi20-May-07 19:52 
GeneralNIce Artilce. Pin
Chirag R Darji24-Apr-07 1:10
memberChirag R Darji24-Apr-07 1:10 
Questiondatabases in C# Pin
Mncedi16-Mar-07 1:11
memberMncedi16-Mar-07 1:11 
AnswerRe: databases in C# Pin
Kazim Sardar Mehdi16-Mar-07 2:43
memberKazim Sardar Mehdi16-Mar-07 2:43 
GeneralRe: databases in C# Pin
mousemee25-Apr-07 5:00
membermousemee25-Apr-07 5:00 
GeneralRe: databases in C# Pin
mousemee25-Apr-07 23:14
membermousemee25-Apr-07 23:14 
GeneralCopy Pin
Mark Nischalke6-Jul-06 3:44
memberMark Nischalke6-Jul-06 3:44 
GeneralOut of memory exception Pin
Anuarg Jain5-Sep-05 1:04
sussAnuarg Jain5-Sep-05 1:04 
GeneralRe: Out of memory exception Pin
Mah Jin Khai29-Mar-06 7:10
memberMah Jin Khai29-Mar-06 7:10 
GeneralRe: Out of memory exception Pin
psmutiu20-Jun-06 23:13
memberpsmutiu20-Jun-06 23:13 
GeneralRe: Out of memory exception Pin
ChrisStoy14-Jul-06 6:54
memberChrisStoy14-Jul-06 6:54 
AnswerRe: Out of memory exception Pin
Vivek.Sivasamy7-Aug-06 19:36
memberVivek.Sivasamy7-Aug-06 19:36 
GeneralRe: Out of memory exception(Urgentttttttttttttttttttt) Pin
baadri23-Apr-08 22:23
memberbaadri23-Apr-08 22:23 
GeneralThank you Kzmm Pin
David Roh29-Aug-05 10:00
sussDavid Roh29-Aug-05 10:00 
Question????? Pin
g0got23-Jul-05 3:34
memberg0got23-Jul-05 3:34 

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
Web01 | 2.8.150428.2 | Last Updated 1 Jul 2005
Article Copyright 2005 by Kazim Sardar Mehdi
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid