|
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
- 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]
- Actually
IMAGE field is just holding the reference to the page containing the binary data so we have to convert our image into bytes.
- I used a file open dialog box to locate the file.
this.openFileDialog1.ShowDialog(this);
string strFn=this.openFileDialog1.FileName;
- By using
FileInfo class, I 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));
fs.Close();
Complete Load Image Codeprotected 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);
}
}
- Saving byte array data to database.
- Create command text to insert record.
this.sqlCommand1.CommandText=
"INSERT INTO tblImgData(ID,Name,Picture)" +
" values(@ID,@Name,@Picture)";
- 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.
- 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.
- Now execute non-query for saving the record to the database.
int iresult=this.sqlCommand1.ExecuteNonQuery();
Complete Save Image Codeprivate 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.
- First create command text to retrieve record.
SqlCommand cmdSelect = new SqlCommand("select Picture" +
" from tblImgData where ID=@ID",
this.sqlConnection1);
- Create parameter for the query.
cmdSelect.Parameters.Add("@ID",SqlDbType.Int,4);
- Provide value to the parameter.
cmdSelect.Parameters["@ID"].Value=this.editID.Text;
- 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.
- 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();
- And display the image anywhere you want to display.
pictureBox1.Image=Image.FromFile(strfn);
Complete Image Retrieving Codeprivate 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
| You must Sign In to use this message board. |
|
| | Msgs 1 to 25 of 29 (Total in Forum: 29) (Refresh) | FirstPrevNext |
|
 |
|
|
 |
|
|
How can i do error checking for Save image, for example, the name is already used. So how can i do checking for the database?
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
hi,thanks the code works really fine
but I have an issue........ I hv a table with photo as a column with image datatype in sqlserver2005 Now the code below is used to save the image in this column actually record for the student has already been inserted now i want to only update this field.. ssql = "update Students set Photo=@Pic where ID='2' cmd.CommandText = ssql cmd.Parameters.Add("@Pic",System.Data.SqlDbType.Image) cmd.Parameters.Item("@Pic").Value = barrImg cmd.ExecuteNonQuery()
This code does execute without any error but it inserts null value.. The variable barrimg has the same sense that is represented in this code.
please help me out as where am I going wrng......... Its URGENT........... :
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Hi I am facing a problem, i have a gridview and i want to add gridview's data to sql server database table. how can it possible.
thanx naresh rajput
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
hi sir, this code workds fine but have some difficulties. whenever i want to see the imaged it display a message "C:documents and setteing/..../ file already exists". and it is becoze when we view a photo then a temporary file is created autometically. please tell me how to solve this problem and how to delete autometically the file which is created autometically.
thanks
|
| Sign In·View Thread·PermaLink | 2.00/5 (1 vote) |
|
|
|
 |
|
|
Replace the following lines
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);
With the following line using the memory stream no need to incur the overhead of writing to disk and reading from disk.
pictureBox1.Image=Image.FromStream(new MemoryStream(barrImg));
|
| Sign In·View Thread·PermaLink | 2.00/5 (1 vote) |
|
|
|
 |
|
|
hi This is naresh, thanx for the solution. my problem have been solved. Once again very thanx. Naresh Rajput
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Thanx friend, This is naresh again, i have a problem again, could you please help me this time, i have a gridview and i want transfer its data to sql server database table.How can it possible.
thanx Naresh Rajput
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Hi,
would someone please help me?
I cannot get it to work. Currently I have MS SQL Server 2005 Express installed.
I get this message when I click on save or load "The ConnectionString property has not been initialized".
Someone please post or send me the sql 2005 database file for this code.
Thank you very much.
-Ken
|
| Sign In·View Thread·PermaLink | 1.00/5 (2 votes) |
|
|
|
 |
|
|
hi friend,
this is naresh from chandigarh. the solution of your problem is given below: dim conn as sqlconnection
and when u have to run cmd(Sql command) before this you should open the connection property of the sql server, for example:
conn.open()
mention above line and you will find your problem vanish.
Naresh Rajput Software Engineer
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
this code works great. awesome job. but I have 2 comments to make.
1.for those of you wanting to use this on a smaller scale (like if you only want to store a small image or avatar) you can replace filstream with MemoryStream, which puts the image into memory.
2. how does one delete the temporary file you create when reading the data again? I tried
if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + fs.Name)) { File.Delete(AppDomain.CurrentDomain.BaseDirectory + fs.Name); }
and it doesnt work. anyways good job on the ocde.
It's not a bug it's a f- oh wait... no..It's a bug.
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
OIC you dont need Appdomain.currentdomain.basedirectory
just if(File.Exists(fs.Name)) { File.Delete; }
It's not a bug it's a f- oh wait... no..It's a bug.
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
I am using this code in web application so I am using Web Controls for displaying the Image So the conversion Problem is occured..........
Is there any solution...........
Naresh Patel
|
| Sign In·View Thread·PermaLink | 1.50/5 (3 votes) |
|
|
|
 |
|
|
Hi
I am in a process of storing image in the database in binary and then retriveing the image from the database in orignal form.
I would appreciate if someone could help.
Thanks, Ali
Life is too short to be counted, enjoy life.
|
| Sign In·View Thread·PermaLink | 5.00/5 (1 vote) |
|
|
|
 |
|
|
why dont u use this article for your reference, i hope it will help u alot.
regards
kazim mehdi
|
| Sign In·View Thread·PermaLink | 2.00/5 (1 vote) |
|
|
|
 |
|
|
 |
|
|
how does one retreive an image stored in a database(ms access) using a data grid(view) and then display the image on a picture box?? your help will be highly appreciated!!!!
by Mnce
|
| Sign In·View Thread·PermaLink | 2.00/5 (1 vote) |
|
|
|
 |
|
|
hi Mncedi
the solution i presented here is for sql server. you can consult this article
http://support.microsoft.com/kb/103257
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Hi, i found your code for image storing and receiving very relevant. However, if i am using sql server 2005, will the coding have to be modified? If so, do you have the coding version for sql server 2005? Thanks.
|
| Sign In·View Thread·PermaLink | 1.00/5 (1 vote) |
|
|
|
 |
|
|
kazim
I would like to enquire if the codings you posted for image stroign and retrieving can be applied using sql server 2005? do the syntax need to be modified? Also, do you have a web service version of stroing images in sql database? Thank you very much for your time
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
 |
|
|
While trying to set the Image in the PictureBox control , out of memory exception is thrown.
Please suggest.
|
| Sign In·View Thread·PermaLink | 2.00/5 (1 vote) |
|
|
|
 |
|
|
any suggestion? i also encounter the same problem... if possible pls send email to me, sovietmah@yahoo.com.
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
 |
|
|
OutOfMemoryException
The file does not have a valid image format.
-or-
GDI+ does not support the pixel format of the file.
Chris Stoy chris_stoy@hotmail.com
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
General News Question Answer Joke Rant Admin
|