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

Storing and Retrieving Images from SQL Server using Microsoft .NET

By , 30 Jun 2005
 

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

About the Author

Kazim Sardar Mehdi
Web Developer
Denmark Denmark
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

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5membermadhav140418 Mar '13 - 9:11 
It helped me alot in my college project.
GeneralMy vote of 5mvpKanasz Robert24 Sep '12 - 6:18 
good article
Questionout of memory exceptionmemberhiphopper01234 Jun '12 - 21:06 
hey, i gt out of memory exception
how to deal with it..
QuestionError!!!!!!!!!membersuhail ahmad26 Apr '12 - 22:43 
Hello Kazim Sir,
 
I have converted your code into VS2008 and compiled.
It compiled and run successfully but when try save the images it through an error saying-
"ExecuteNonQuery requires an open and available connection. The connections current state is closed" but when I debug the code it shows the connection is open.
while the line
 
int iresult = this.sqlCommand1.ExecuteNonQuery();
 
shows the error.
Please Help. It Urgent!!!!
AnswerRe: Error!!!!!!!!!memberWimpie Ratte15 May '12 - 6:45 
double check that you open your connection before the "ExecuteNonQuery()" call.
sqlConnection1.Open();
 
--------------------------
 
only one life
it'll soon be past
only what's done for Christ will last
QuestionquestionmemberMember 884454618 Apr '12 - 1:15 
Can u tell me the directories used.
 

Thanks & Regards
Rahul
GeneralMy vote of 5memberMOHIT KUMAR VERMA7 Mar '12 - 5:17 
Excellent explanation
GeneralExporting images from the Club site template to jpeg filesmemberMartin Kadlec, Czech rep.17 May '11 - 0:56 
I recently needed to export the photos from the Club web site template pages. Here is a small snipet. Maybe it helps someone ...
 
Example connection string:
<add key="ConString" value="Data Source=.\SQLEXPRESS;AttachDbFilename=C:\...\www.myweb.com\App_Data\Club.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True" />;
private void buttonLoadAll_Click(object sender, EventArgs e)
        {
            DataSet ds = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter();
            SqlCommand cmdSelect = new SqlCommand("select id, album, origimage from images", this.sqlConnection1);
 
            da.SelectCommand = cmdSelect;
            da.Fill(ds, "tab");
            
            foreach (DataRow dr in ds.Tables["tab"].Rows)
            {
                int id = (int)dr["id"];
                int album = (int)dr["album"];
                byte[] barrImg = (byte[])dr["origimage"]; 
 
                //Get jpg stream and save to file
                FileStream fs = new FileStream(album + "_" + id + ".jpg", FileMode.CreateNew, FileAccess.Write);
                fs.Write(barrImg, 0, barrImg.Length);
                fs.Flush();
                fs.Close();
            }
        }

GeneralRe: Exporting images from the Club site template to jpeg filesmemberawadhendra tiwari22 Aug '11 - 4:51 
Save Image in SQL Server:
http://www.mindstick.com/Articles/982a3316-c8a6-4b81-82ef-c064f27118d9/?Store%20image%20in%20SQL%20Server%20database[^]
 
Save Image in SQL Server by using C#
http://www.mindstick.com/Blog/184/Save%20image%20in%20SqlServer%20using%20C[^]
GeneralMy vote of 5memberharsha narayana31 Mar '11 - 21:12 
Nice work..

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 1 Jul 2005
Article Copyright 2005 by Kazim Sardar Mehdi
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid