Click here to Skip to main content
6,594,432 members and growing! (16,804 online)
Email Password   helpLost your password?
Database » Database » SQL Server     Intermediate

Storing and Retrieving Images from SQL Server using Microsoft .NET

By Kazim Sardar Mehdi

Storing and retrieving images from SQL Server using Microsoft .NET.
C#, SQL, Windows, .NET 1.1, ADO.NET, SQL 2000, VS.NET2003, DBA, Dev
Posted:30 Jun 2005
Views:229,178
Bookmarked:92 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
38 votes for this article.
Popularity: 5.75 Rating: 3.64 out of 5
5 votes, 13.2%
1
1 vote, 2.6%
2
1 vote, 2.6%
3
11 votes, 28.9%
4
20 votes, 52.6%
5

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


Member

Occupation: Web Developer
Location: Sweden Sweden

Other popular Database articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 37 (Total in Forum: 37) (Refresh)FirstPrevNext
GeneralHow Do I delete the temporary files created? PinmemberNastyJoe5:53 7 Sep '09  
GeneralThank you kazim Sir Pinmemberrahulxlash2:07 28 Aug '09  
GeneralNice post! [modified] PinmemberCrazyTasty21:30 18 Aug '09  
GeneralThank you very much Pinmemberhamid_ss11:16 25 Jul '09  
Generalsimilar code in .net 2003 and sql 2000 Pinmembersanjaydsm16761:27 7 May '09  
GeneralMy vote of 2 Pinmembermaroju.raghava22:40 21 Jan '09  
GeneralMy vote of 2 Pinmembermaroju.raghava22:38 21 Jan '09  
Newssql server related interesting articles [modified] Pinmembercodemobile20:57 31 Oct '08  
QuestionError Checking PinmemberPTTAN21:56 7 Aug '08  
Generalthis code works fine but it inserts null value in to the database........... Pinmemberkkwaghpriya19:26 22 Jul '08  
GeneralExport Gridview data to sql database table Pinmembernaresh15070:10 27 Jun '08  
GeneralRe: Export Gridview data to sql database table PinmemberDeepsoftindia0:32 6 Dec '08  
GeneralProblem regarding viewing of images from sql Pinmembernaresh15072:31 23 Jun '08  
GeneralSave code Pinmemberhoneybone12:10 27 Nov '07  
GeneralRe: Save code Pinmembernaresh150719:55 23 Jun '08  
GeneralRe: Save code Pinmembernaresh15070:09 27 Jun '08  
GeneralPlease help, not working with 2005 PinmemberFerrari_X13:42 22 Oct '07  
GeneralRe: Please help, not working with 2005 Pinmembernaresh150719:19 23 Jun '08  
Generalthis code works well, but a few issues... Pinmemberroger_277:28 16 Aug '07  
GeneralRe: this code works well, but a few issues... Pinmemberroger_278:20 16 Aug '07  
QuestionProblem in Conversion From System....Drawing.Image to System...WebControl.Image Pinmembernareshgoradara22:25 1 Jun '07  
GeneralImage Storage Pinmembersamshah5127:18 19 May '07  
GeneralRe: Image Storage PinmemberKazim Sardar Mehdi19:52 20 May '07  
GeneralNIce Artilce. PinmemberChirag R Darji1:10 24 Apr '07  
Questiondatabases in C# PinmemberMncedi1:11 16 Mar '07  

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

PermaLink | Privacy | Terms of Use
Last Updated: 30 Jun 2005
Editor: Smitha Vijayan
Copyright 2005 by Kazim Sardar Mehdi
Everything else Copyright © CodeProject, 1999-2009
Web16 | Advertise on the Code Project