Click here to Skip to main content
6,295,667 members and growing! (12,702 online)
Email Password   helpLost your password?
Database » Database » General     Intermediate License: The Code Project Open License (CPOL)

Store/Save images in SQL Server

By Shabdar Ghata

A sample program to demonstrate how to save or store images in Sql server.
SQL, C# 1.0, C# 2.0, C# 3.0.NET 2.0, Win2K, WinXP, Win2003, Vista, .NET 3.0, .NET 3.5, ADO.NET, SQL 2000, SQL 2005, VS2005, VS2008, DBA, Dev
Version:2 (See All)
Posted:6 Nov 2007
Updated:5 Jan 2009
Views:47,773
Bookmarked:44 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
12 votes for this article.
Popularity: 1.97 Rating: 1.82 out of 5
6 votes, 50.0%
1
1 vote, 8.3%
2
2 votes, 16.7%
3

4
3 votes, 25.0%
5

Introduction

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


How to Store Image in SQL Server table

To store an image in to sql server, you need to read image file into a byte array. Once you have image data in byte array, you can easity store this image data in sql server using sql parameters. Following code explains you how to do this.

        private void cmdSave_Click(object sender, EventArgs e)
        {
            try
            {
                //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", (object)txtImagePath.Text));
                SqlCom.Parameters.Add(new SqlParameter("@ImageData", (object)imageData));

                //Open connection and execute insert query.
                CN.Open();
                SqlCom.ExecuteNonQuery();
                CN.Close();

                //Close form and return to list or images.
                this.Close();
            }

Following code explains how to read image file in to 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()
        {
            try
            {
                //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)
            {
                MessageBox.Show(ex.ToString());
            }
        }

Once you have image data in 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)
        {
            try
            {
                //Get image data from gridview column.
                byte[] imageData = (byte[])dataGridView1.Rows[e.RowIndex].Cells["ImageData"].Value;

                //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)
            {
                MessageBox.Show(ex.ToString());
            }
        }

If you want you can extend this code to save image from Picture Box to a local image file.

            //Store image to a local file.
            pictureBox1.Image.Save("c:\test_picture.jpg",System.Drawing.Imaging.ImageFormat.Jpeg);

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 original picture. When picturebox's size is more than Panel1's size, scrollbars becomes active for Panel.

How to download and run program

  • Download source zip from my website http://www.shabdar.org and extract it.
  • Restore database from SQL Database folder.  
  • If some how you can not restore provided database, you can generate necessary table using script provided in SQL Database directory.
  • Open solution and change connection string on frmImagesStore form.

Requirements

Visual Studio.Net 2005

.Net Framework 2.0

MS SQL Server 2000 database or MS SQL Server 2005 database.

License

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

About the Author

Shabdar Ghata


Member
Software Developer

http://www.shabdar.org
Occupation: Web Developer
Location: Canada Canada

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 12 of 12 (Total in Forum: 12) (Refresh)FirstPrevNext
GeneralAwesome PinmemberKo2 Hunter10:02 12 Apr '09  
GeneralRe: Awesome Pinmemberpeyush.goel14:31 8 Jun '09  
GeneralExample with Sql Server Pinmembermayurmv18:22 5 Sep '08  
GeneralOpen from, edit and then save to database? PinmemberSobia Saeed Magray20:48 3 Aug '08  
Generalstoring images PinmemberAamir Mustafa20:39 6 Mar '08  
GeneralMR. DANH.... PinmemberMrGoodly6:18 21 Jan '08  
GeneralRe: MR. DANH.... PinmemberGevorg18:05 6 Mar '08  
GeneralThink before deciding to put files into a database PinmemberDankarmy10:56 9 Dec '07  
GeneralRe: Think before deciding to put files into a database PinmemberPawJershauge9:30 13 Jan '08  
GeneralRe: Think before deciding to put files into a database PinmemberShabdar Ghata11:55 14 Jan '08  
GeneralRe: Think before deciding to put files into a database PinmemberPIEBALDconsult7:46 30 Jan '08  
GeneralWhat have you added??? PinsupporterMark Nischalke16:15 6 Nov '07  

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

PermaLink | Privacy | Terms of Use
Last Updated: 5 Jan 2009
Editor: Chris Maunder
Copyright 2007 by Shabdar Ghata
Everything else Copyright © CodeProject, 1999-2009
Web09 | Advertise on the Code Project