This is a discussion on Storing and retrieving image from SQL server database? within the C# Programming forums, part of the Software Development category; Storing and retrieving image from SQL server database?...
| |||||||
| Register | FAQ | Members List | Calendar | Mark Forums Read |
| |||
| Create a table in a SQL Server database which has at least one field of type IMAGE. Here is the script : 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] The IMAGE field is just holding the reference to the page containing the binary data so we have to convert our image into bytes. By using FileInfo class, retrieved the file size: FileInfo fiImage=new FileInfo(strFn); Declare an array of that size: this.m_lImageFileLength=fiImage.Length; m_barrImg=new byte[Convert.ToInt32(this.m_lImageFileLength)]; 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)); Saving byte array data to database. execute non-query for saving the record to the database. int iresult=this.sqlCommand1.ExecuteNonQuery(); Retrieving images from the database is the exact reverse process of saving images to the database. Open database connection and execute “ExecuteScalar” because we want only “IMAGE” column data back. byte[] barrImg=(byte[])cmdSelect.ExecuteScalar(); Save this data to a temporary file. string strfn=Convert.ToString(DateTime.Now.ToFileTime()); FileStream fs=new FileStream(strfn,FileMode.CreateNew,FileAccess.Wri te); fs.Write(barrImg,0,barrImg.Length); fs.Flush(); And display the image anywhere you want to display. pictureBox1.Image=Image.FromFile(strfn); |
![]() |
| Thread Tools | |
| Display Modes | |
| |
Similar Threads | ||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Advantages of storing sessions in database | vigneshgets | PHP Programming | 2 | 02-13-2008 07:41 AM |
| Sql server 2005 Database Maintenance | arjkhanna | Server Management | 3 | 10-30-2007 11:11 AM |
| Oracle server - create database | write2ashokkumar | Server Management | 1 | 09-04-2007 04:00 AM |
| Storing cookie in server side | Sivamurugan | PHP Programming | 0 | 08-30-2007 08:50 AM |
| How to monitor image server | vadivelanvaidyanathan | Server Management | 3 | 03-16-2007 08:01 AM |