German Wear Discount Shop - Click Here Write for Dotnet-friends and earn for your each submission [Dot]Net-Friends
Skip Navigation Links
Home
Latest
Fast Code
Articles
Tutorials
Online Resources
Forums
Login   | Hi, Guest


Saving and Retrieving Images From SQL Server Using ADO.NET 2.0

Written by omerkamal on Dec 06, 2006
Saving and Retrieving Images From SQL Server Using ADO.NET 2.0

Introducation:

Now a days, with the availibillity of alote of web-spaces and bandwidths it is getting criticle to manage Images in a website. If Images are saved in a Database it would be more convinient to save information of each image in it.
In this way Images Managment get easy. Now Images can be searched by any developer in the team and will be easily found and retrive from the resources.

Explanation:

Our fisrt step is to create a Table in our MS SQL DataBase. We are going to create the Table using following SQL Script.

Our MS SQL Table:

CREATE TABLE [dbo].[Photos](
[PhotoID] [int] IDENTITY(1,1) NOT NULL,
[Caption] [nvarchar](50) NOT NULL,
[Photo] [image] NOT NULL,
CONSTRAINT [PK_Photos] PRIMARY KEY CLUSTERED
([PhotoID] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


Retrieving an image from the hard disk and inserting it into SQL Server:


byte[] image;
string fileName = @"c:\yourImage.jpg";
// Open File and Read Into Byte Array
using (FileStream fs = new FileStream(fileName, FileMode.Open)) {
BinaryReader reader = new BinaryReader(fs);
image
= reader.ReadBytes((int)fs.Length);
fs.Close();
}

using (SqlConnection conn = new
SqlConnection(ConfigurationManager.ConnectionStrings["Personal"].ConnectionString))
{
SqlCommand command = new
SqlCommand("INSERT INTO Photos (Caption,Photo) VALUES (@Caption,@Photo)");
command.Parameters.Add("@Caption", SqlDbType.NVarChar).Value = textbox1.Text;
command.Parameters.Add("@Photo", SqlDbType.Image).Value = image;
conn.Open();
command.EndExecuteNonQuery();
}


Retrieving an image from SQL Server:

// Get Database
Database db = DatabaseFactory.CreateDatabase();
// Create Example DbCommand
string selectSql = "SELECT Photo FROM Photos  WHERE PhotoID = 1";
DbCommand selectCommand
= db.GetSqlStringCommand(selectSql);
// Execute Command
byte[] storedImage = (byte[])db.ExecuteScalar(selectCommand);
// Convert byte[] to Image
Image newImage;
using (MemoryStream stream = new MemoryStream(storedImage)) {
newImage = Image.FromStream(stream);
}

// Display to make sure code works
pictureBox1.Image = newImage;


Upload an Image using FileUpload Control


If you are loading the picture from a FileUpload Control in a web page, the code will be slightly different. Here is the same example of saving the image to SQL Server using a FileUpload Control :


//Use a TextBox (say textbox1) for the Image Caption
//FileUpload1 is our FileUpload Control
if (FileUpload1.HasFile && !string.IsNullOrEmpty(textbox1.Text))
{ BinaryReader reader = new BinaryReader(FileUpload1.PostedFile.InputStream);
byte[] image = reader.ReadBytes(FileUpload1.PostedFile.ContentLength);

using (SqlConnection conn = new
SqlConnection(ConfigurationManager.ConnectionStrings["Personal"].ConnectionString))
{
SqlCommand command=new SqlCommand("INSERT INTO Photos (Caption,Photo) VALUES (@Caption,@Photo)");
command.Parameters.Add("@Caption", SqlDbType.NVarChar).Value = textbox1.Text;
command.Parameters.Add("@Photo", SqlDbType.Image).Value = image;
conn.Open();
command.EndExecuteNonQuery();
}
}

Visitors/Readers Comments



Martin

good work!

14/12/2006 16:41:17 UTC

gaurav jain

nice article.

25/12/2006 05:07:00 UTC

piyush

what is picturebox1 ?

13/03/2007 01:32:12 UTC

Omer kamal

This is a Picture Box Control. You can find this in your Contols Tools Bar. Please read more about Picture Box in here http://msdn2.microsoft.com/en-us/library/3e74696e(VS.80).aspx

 

13/03/2007 05:08:25 UTC

nikhil

how to attach with ASP:IMAGE  ?

10/04/2007 05:34:20 UTC

kamal

In the src Attribute of the Image Tage give link of your Handler. You can find a detailed Article in the Following link:

https://dotnet-friends.com/articles/asp/artinasp03e650de-2b15-4fb1-9bdb-aad1a1e5ac5c.aspx

11/04/2007 01:37:15 UTC

mrudula

parameter is invalid error is coming while executing the program of retrieving image

 

02/09/2007 03:19:47 UTC

Hi

I'm getting an error msg when i'm uploading an image using fileupload control

insert query is not executing i mean


command.EndExecuteNonQuery(); ---- here it is showing me an error saying Connection Property is not initialized

can any one please help me

18/09/2007 14:40:28 UTC

bharath

  hi

   in this one ur using picturebox1,i want the images is displayed in datagrid,that to path type.that to it will displayed as path in datagrid,if we click that path it will displayed the images and total content of that one........

 

 

helpme.......................

23/09/2007 06:50:04 UTC

kamini

tum log kya tu bhi likh deye, choti bacchi ko samjh mey aye wesa likha karo

 

 

29/09/2007 03:41:12 UTC

hi

i want to display an image in text box control from sqlserver using c#.

17/10/2007 23:34:40 UTC

jith

Image.Fromstream >>>>>>Error: Invalid Parameter...??????????

22/10/2007 17:58:41 UTC

Jith

I solved the problem

24/10/2007 11:58:54 UTC

Sonali Diwan

Image.FromStream>>>>>>>>>>>>>>>>>>......Error: Invalid Parameter ????????///

Sonali Diwan

23/11/2007 00:17:53 UTC

Swarna

Hi

 

          I dont understand the code which is  there in retrive images from databse

30/11/2007 05:04:10 UTC

Umar

Plz Help..........

Exception: Parameter is not valid....

when i use to execute the code

06/12/2007 02:24:06 UTC

Smitha

Image.fromstream missing

12/12/2007 23:41:18 UTC

San

Plz Help..........

Exception: Parameter is not valid....

when i use to execute the code


Hey why do u write wrong code on the net.....

14/12/2007 06:55:54 UTC

Sri Swapna

Its working thanks...

16/12/2007 09:34:21 UTC

D.Asuncion

Good Idea... Thanks a lot.. :)

21/01/2008 20:01:37 UTC

amar shukla

i get this error while creating the table using ur code

Server: Msg 170, Level 15, State 1, Line 7
Line 7: Incorrect syntax near '('.

23/01/2008 10:44:15 UTC

jamal

the idea is clear

but there's no picturebox in web application can i know how to load the picture in image controle

25/01/2008 02:08:33 UTC

Ramu

Hi,

Iam getting Error here Command.EndExecuteNonQuery()

it showing this error.

Argument not specied for parameter.

 

28/01/2008 02:42:51 UTC

krishnamoorthy

ya its very fine  and very helpful for my project

10/03/2008 06:35:12 UTC




Add your Comments

Name:  
Message:
Note: For faster response please use Forums >> for your questions instead of the comments area! (Admin)