Click here to Skip to main content
13,000,569 members (55,986 online)
Click here to Skip to main content
Add your own
alternative version


115 bookmarked
Posted 6 Nov 2007

Store or Save images in SQL Server

, 5 Mar 2010
Rate this:
Please Sign up or sign in to vote.
A sample program to demonstrate how to save or store images in SQL server


This sample code explains how you can store images in a SQL Server database. It uses ADO.NET System.Data.SqlClient namespace. Images can be stored in SQL server using SQL parameters.

How to Store Images in SQL Server Table

To store an image into SQL Server, you need to read an image file into a byte array. Once you have image data in a byte array, you can easily store this image data in SQL Server using SQL parameters. The following code explains how to do this:

private void cmdSave_Click(object sender, EventArgs e)
          //Read Image Bytes into a byte array
          byte[] imageData = ReadFile(txtImagePath.Text);
          //Initialize SQL Server Connection
          SqlConnection CN = new SqlConnection(txtConnectionString.Text);

          //Set insert query
          string qry = "insert into ImagesStore 
		(OriginalPath,ImageData) values(@OriginalPath, @ImageData)";

          //Initialize SqlCommand object for insert.
          SqlCommand SqlCom = new SqlCommand(qry, CN);

          //We are passing Original Image Path and 
          //Image byte data as SQL parameters.
          SqlCom.Parameters.Add(new SqlParameter("@OriginalPath", 
          SqlCom.Parameters.Add(new SqlParameter("@ImageData", (object)imageData));

          //Open connection and execute insert query.

          //Close form and return to list or images.

The following code explains how to read an image file into a byte array:

//Open file in to a filestream and read data in a byte array.
byte[] ReadFile(string sPath)
    //Initialize byte array with a null value initially.
    byte[] data = null;

    //Use FileInfo object to get file size.
    FileInfo fInfo = new FileInfo(sPath);
    long numBytes = fInfo.Length;

    //Open FileStream to read file
    FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);

    //Use BinaryReader to read file stream into byte array.
    BinaryReader br = new BinaryReader(fStream);

    //When you use BinaryReader, you need to supply number of bytes 
    //to read from file.
    //In this case we want to read entire file. 
    //So supplying total number of bytes.
    data = br.ReadBytes((int)numBytes); 

    return data;

How to Read Image Data from SQL Server Table

To read images from SQL Server, prepare a dataset first which will hold data from SQL Server table. Bind this dataset with a gridview control on form.

void GetImagesFromDatabase()
        //Initialize SQL Server connection.

        SqlConnection CN = new SqlConnection(txtConnectionString.Text);

        //Initialize SQL adapter.
        SqlDataAdapter ADAP = new SqlDataAdapter("Select * from ImagesStore", CN);

        //Initialize Dataset.
        DataSet DS = new DataSet();

        //Fill dataset with ImagesStore table.
        ADAP.Fill(DS, "ImagesStore");

        //Fill Grid with dataset.
        dataGridView1.DataSource = DS.Tables["ImagesStore"];
    catch(Exception ex)

Once you have image data in the grid, get image data from grid cell. Alternatively you can also get image data from Dataset table cell.

//When user changes row selection, display image of selected row in picture box.
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
        //Get image data from gridview column.
        byte[] imageData = 

        //Initialize image variable
        Image newImage;
        //Read image data into a memory stream
        using (MemoryStream ms = new MemoryStream(imageData, 0, imageData.Length))
            ms.Write(imageData, 0, imageData.Length);

            //Set image variable value using memory stream.
            newImage = Image.FromStream(ms, true);

        //set picture
        pictureBox1.Image = newImage;
    catch(Exception ex)

If you want, you can extend this code to save image from PictureBox to a local image file.

//Store image to a local file.

Points of Interest

If you see frmImageStore in design mode, I have placed picturebox1 into a panel. This panel's AutoScroll property is set to True and SizeMode property of PictureBox1 is set to True. This allows picturebox to resize itself to the size of the original picture. When picturebox's size is more than Panel1's size, scrollbars becomes active for Panel.

How to Download and Run the Program

  • Download the source zip from my website and extract it.
  • Restore the database from SQL Database folder.
  • If somehow you cannot restore the provided database, you can generate the necessary table using the script provided in SQL Database directory.
  • Open the solution and change connection string on frmImagesStore form.


  • Visual Studio .NET 2005
  • .NET Framework 2.0
  • Microsoft SQL Server 2000 database or Microsoft SQL Server 2005 database


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Shabdar Ghata
Web Developer
Canada Canada
Software Developer

You may also be interested in...


Comments and Discussions

Generalstoring images Pin
Aamir Mustafa6-Mar-08 19:39
memberAamir Mustafa6-Mar-08 19:39 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170624.1 | Last Updated 5 Mar 2010
Article Copyright 2007 by Shabdar Ghata
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid