Click here to Skip to main content
15,867,686 members
Articles / Database Development / SQL Server
Article

Storing and Retrieving Images from SQL Server using Microsoft .NET

Rate me:
Please Sign up or sign in to vote.
4.09/5 (75 votes)
30 Jun 20051 min read 902.4K   20.5K   162   60
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:

    SQL
    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.
      C#
      this.openFileDialog1.ShowDialog(this);
      string strFn=this.openFileDialog1.FileName;
    2. By using FileInfo class, I retrieved the file size:
      C#
      FileInfo fiImage=new FileInfo(strFn);
    3. Declare an array of that size.
      C#
      this.m_lImageFileLength=fiImage.Length;
      m_barrImg=new byte[Convert.ToInt32(this.m_lImageFileLength)];
    4. By using FileStream object, I filled the byte array.
      C#
      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

    C#
    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.
      C#
      this.sqlCommand1.CommandText= 
        "INSERT INTO tblImgData(ID,Name,Picture)" + 
        " values(@ID,@Name,@Picture)";
    2. Create parameters.
      C#
      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.
      C#
      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.
      C#
      int iresult=this.sqlCommand1.ExecuteNonQuery();

    Complete Save Image Code

    C#
    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.
    C#
    SqlCommand cmdSelect = new SqlCommand("select Picture" + 
                           " from tblImgData where ID=@ID", 
                           this.sqlConnection1);
  2. Create parameter for the query.
    C#
    cmdSelect.Parameters.Add("@ID",SqlDbType.Int,4);
  3. Provide value to the parameter.
    C#
    cmdSelect.Parameters["@ID"].Value=this.editID.Text;
  4. Open database connection and execute “ExecuteScalar” because we want only “IMAGE” column data back.
    C#
    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.
    C#
    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.
    C#
    pictureBox1.Image=Image.FromFile(strfn);

Complete Image Retrieving Code

C#
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


Written By
Web Developer
Denmark Denmark
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionStoring and Retrieving Images from SQL Server using Microsoft .NET Pin
Mojo Al'Thor10-Jan-20 3:37
Mojo Al'Thor10-Jan-20 3:37 
PraiseThanks a lot of Pin
xisouthros6-Jan-18 9:04
professionalxisouthros6-Jan-18 9:04 
Questionentity framework Pin
Member 1029443818-Mar-15 0:11
Member 1029443818-Mar-15 0:11 
QuestionNice presentation but I was wondering how does one edit or update the database Pin
saldevji27-Nov-14 10:10
saldevji27-Nov-14 10:10 
QuestionStore image in database Pin
Altaf N Patel17-Apr-14 20:12
Altaf N Patel17-Apr-14 20:12 
Question+5 Pin
abbaspirmoradi5-Dec-13 9:36
professionalabbaspirmoradi5-Dec-13 9:36 
BugUnable to download .zip Pin
RedDk3-Dec-13 12:27
RedDk3-Dec-13 12:27 
QuestionRETRIEVING IMAGE Pin
adesewa28-May-13 4:08
adesewa28-May-13 4:08 
GeneralMy vote of 5 Pin
madhav140418-Mar-13 9:11
madhav140418-Mar-13 9:11 
GeneralMy vote of 5 Pin
Kanasz Robert24-Sep-12 6:18
professionalKanasz Robert24-Sep-12 6:18 
Questionout of memory exception Pin
vinayakJJ4-Jun-12 21:06
vinayakJJ4-Jun-12 21:06 
AnswerRe: out of memory exception Pin
jessewimberley26-Nov-13 9:27
jessewimberley26-Nov-13 9:27 
QuestionError!!!!!!!!! Pin
suhail ahmad26-Apr-12 22:43
suhail ahmad26-Apr-12 22:43 
AnswerRe: Error!!!!!!!!! Pin
Wimpie Ratte15-May-12 6:45
Wimpie Ratte15-May-12 6:45 
Questionquestion Pin
Member 884454618-Apr-12 1:15
Member 884454618-Apr-12 1:15 
GeneralMy vote of 5 Pin
MOHIT KUMAR VERMA7-Mar-12 5:17
MOHIT KUMAR VERMA7-Mar-12 5:17 
GeneralExporting images from the Club site template to jpeg files Pin
Martin Kadlec, Czech rep.17-May-11 0:56
Martin Kadlec, Czech rep.17-May-11 0:56 
GeneralRe: Exporting images from the Club site template to jpeg files Pin
awadhendra tiwari22-Aug-11 4:51
awadhendra tiwari22-Aug-11 4:51 
GeneralMy vote of 5 Pin
ZeeroC00l31-Mar-11 21:12
ZeeroC00l31-Mar-11 21:12 
GeneralOut of Memory Pin
curious_mind23-Feb-11 23:40
curious_mind23-Feb-11 23:40 
GeneralOut of Memoty error Pin
ashoks10426-Jul-10 8:20
ashoks10426-Jul-10 8:20 
GeneralThank You Pin
John Hemphill11-May-10 11:59
John Hemphill11-May-10 11:59 
GeneralNice Pin
Nitin S30-Nov-09 18:42
professionalNitin S30-Nov-09 18:42 
QuestionHow Do I delete the temporary files created? Pin
NastyJoe7-Sep-09 4:53
NastyJoe7-Sep-09 4:53 
GeneralThank you kazim Sir Pin
rahulxlash28-Aug-09 1:07
rahulxlash28-Aug-09 1:07 

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

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