You are on page 1of 29

Save An Image Into SQL Server 2000

Database
By vivekthangaswamy | 25 Feb 2005
.NET1.1SQL2000VS.NET2003C#ASP.NETSQLWindowsDBADevIntermediate
How to upload files to Web pages in ASP.NET? How to read an image from a database using
ADO.NET and display it in a Web page?

Part of The SQL Zone sponsored by


See Also
• Articles like this
• Articles by this author

Print Article

Twitter

Digg

Facebook

Del.icio.us

Reddit

Stumbleupon

Newsvine

Technorati

Mr. Wong

Yahoo!

Google

Windows Live

Send as Email
Add to your CodeProject bookmarks
Discuss this article

72
Report this article as inappropriate

Article Browse Code StatsRevisions

4.10 (82 votes)

1 2 3 4 5
Sponsored Links
Top of Form
/w EPDw UKMTAy

• Download source - 22.9 Kb

Abstract
.NET is the new distributed computing platform developed by Microsoft and ASP.NET is its
programming model for web development. The intent of this article is to get a good experience
in developing data driven ASP.NET Web Forms applications by means of a real world
application. This application will teach you how to save an image file into a database and how to
retrieve it from the database. It uses ADO.NET as the data access mechanism, C# as the
development language, and SQL Server 2000 as the backend database.
Overview of the Solution
Normally, images are saved in the web server folder, not in the database; this is for larger file
size category. In some cases like, in bank, for example, they scan the user signatures as image
files and save that file into the database.
• Database schema
MS SQL Server 2000 is used as the backend database for this small demonstration. And I
used a special data type in SQL Server called image. The image data type is used to save
the image into the database.
• Controls used in this application
○ System.Web.UI.HtmlControls.HtmlInputFile
○ System.Web.UI.WebControls.TextBox
○ System.Web.UI.WebControls.Button
• Namespaces used in this application:

Collapse
using System.Data.SqlClient;
using System.Drawing;
using System.Data;
using System.IO;
using System.Drawing.Imaging;

Solution with Code


Use the HtmlInputFile class, which you can declare an instance of with an <input
type="file" runat="server"/> tag. The following example is a complete ASPX file that lets
a user upload an image file and a comment describing the image. The OnUpload method writes
the image and the comment to a table named Pictures in a SQL Server database named iSense.

Collapse
// Source Code for Save the image file into the database

public void OnUpload(Object sender, EventArgs e)


{
// Create a byte[] from the input file

int len = Upload.PostedFile.ContentLength;


byte[] pic = new byte[len];
Upload.PostedFile.InputStream.Read (pic, 0, len);
// Insert the image and comment into the database

SqlConnection connection = new


SqlConnection (@"server=INDIA\INDIA;database=iSense;uid=sa;pwd=india");
try
{
connection.Open ();
SqlCommand cmd = new SqlCommand ("insert into Image "
+ "(Picture, Comment) values (@pic, @text)", connection);
cmd.Parameters.Add ("@pic", pic);
cmd.Parameters.Add ("@text", Comment.Text);
cmd.ExecuteNonQuery ();
}
finally
{
connection.Close ();
}
}
The above created function is called using the onClick property of a button.
How do I read an image from a database using ADO.NET and display it in a Web page?
Here, I used the web page to display the image and not any other control. The following is the
code for displaying the image from the database.
Collapse
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here

MemoryStream stream = new MemoryStream ();


SqlConnection connection = new
SqlConnection (@"server=INDIA\INDIA;database=iSense;uid=sa;pwd=india");
try
{
connection.Open ();
SqlCommand command = new
SqlCommand ("select Picture from Image", connection);
byte[] image = (byte[]) command.ExecuteScalar ();
stream.Write (image, 0, image.Length);
Bitmap bitmap = new Bitmap (stream);
Response.ContentType = "image/gif";
bitmap.Save (Response.OutputStream, ImageFormat.Gif);
}
finally
{
connection.Close ();
stream.Close ();
}
}
The GDI+ functions offer a rich set of features for managing and modifying image data. This
article's examples offer only a glimpse into the functionality you can leverage using the classes
available in the System.Drawing and System.Drawing.Imaging namespaces. For example, you
can develop applications for storing and managing image files on the Web, or you can provide a
simple, easily deployed application that enables users to manipulate images.

Save and Retrieve Images from the Database using ASP.NET 2.0 and ASP.NET 3.5
1retweet

Rating: 163 user(s) have rated this article


Posted by: Suprotim Agarwal, on 3/21/2008, in category "ASP.NET"
Views: this article has been read 165602 times
Abstract: At some point or the other, we as ASP.NET developers, face the requirement of
reading and writing images to the database. In this article,we will explore how to store images in
the database as well as use an Http handler to display the image in an ASP.NET server control
along with other controls.
Save and Retrieve Images from the Database
using ASP.NET 2.0 and ASP.NET 3.5

At some point or the other, we as ASP.NET developers, have faced the requirement of
reading and writing images to the database. We have seen loads of articles floating on the
internet which discusses about storing and retrieving images from the database. Some of
them are good. However, I have personally found that the solutions offered are those,
where images are displayed in a ‘standalone fashion’; that is on a separate page containing
only the image. What if we have to show an online form, with the person’s details and his
photo along with it, or for that case, display the image in an ASP.NET server control along
with other controls? In this article, we will explore how to store images in the database and
then display those images along with the other server controls.

To keep the article simple and easy to understand, we will place only a few controls on the
page. I have also not covered any validations associated with image control. In this article,
we will only discuss how to read and write images into the database, and that would be the
focus for this article. If you are interested in discussing validation and other stuff, I would
suggest you to browse through the ASP.NET section of this website to view an article that
discusses that.

So let us get started. We will first see how to upload an image and then display the
uploaded image on the same page. You can extend this sample to create a photo album as
well!! I assume you have some knowledge of creating ASP.NET 2.0 websites.

Let us start off by first creating a sample database and adding a table to it. We will call the
database ‘Employee’ and the table will be called ‘EmpDetails’. This table will contain an
image column along with some other columns. Run the following script in your SQL 2005
Query window (or server explorer) to construct the database and the table.

Database Script

CREATE DATABASE [Employee]


GO
USE [Employee]
GO
CREATE TABLE EmpDetails
(
empid int IDENTITY NOT NULL,
empname varchar(20),
empimg image
)

Step 1: Create a new asp.net website. In the code-behind, add the following namespace

C#

using System.Data.SqlClient;

VB.NET

Imports System.Data.SqlClient

Step 2: Drag and drop two label and one textbox control. Also drag drop a FileUpload
control and a button control to upload the selected image on button click. As mentioned
earlier, there are no validations performed. The source would look similar to the following:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Save Retrieve Images</title>
</head>
<body>
<form id="form1" runat="server">
<div>

<asp:Label ID="lblEmpName" runat="server" Text="Employee


Name"></asp:Label>
&nbsp;&nbsp;&nbsp;&nbsp;
<asp:TextBox ID="txtEName" runat="server"></asp:TextBox>
<br />
<asp:Label ID="lblImage" runat="server" Text="Employee
Image"></asp:Label>
&nbsp;&nbsp;&nbsp;&nbsp;
<asp:FileUpload ID="imgUpload" runat="server" />
<br />
<br />
<asp:Button ID="btnSubmit" runat="server" onclick="btnSubmit_Click"
Text="Submit" />

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp <asp:Label
ID="lblResult" runat="server" ForeColor="#0066FF"></asp:Label>
<br />
<hr />

<asp:Image ID="Image1" style="width:200px" Runat="server" />

</div>
</form>
</body>
</html>

Step 3: In the button click event, add the following code:

C#

protected void btnSubmit_Click(object sender, EventArgs e)


{
SqlConnection connection = null;
try
{
FileUpload img = (FileUpload)imgUpload;
Byte[] imgByte = null;
if (img.HasFile && img.PostedFile != null)
{
//To create a PostedFile
HttpPostedFile File = imgUpload.PostedFile;
//Create byte Array with file len
imgByte = new Byte[File.ContentLength];
//force the control to load data in array
File.InputStream.Read(imgByte, 0, File.ContentLength);
}
// Insert the employee name and image into db
string conn = ConfigurationManager.ConnectionStrings
["EmployeeConnString"].ConnectionString;
connection = new SqlConnection(conn);

connection.Open();
string sql = "INSERT INTO EmpDetails(empname,empimg) VALUES(@enm, @eimg)
SELECT @@IDENTITY";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddWithValue("@enm", txtEName.Text.Trim());
cmd.Parameters.AddWithValue("@eimg", imgByte);
int id = Convert.ToInt32(cmd.ExecuteScalar());
lblResult.Text = String.Format("Employee ID is {0}", id);
}
catch
{
lblResult.Text = "There was an error";
}
finally
{
connection.Close();
}

VB.NET

Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As


System.EventArgs) Handles btnSubmit.Click
Dim connection As SqlConnection = Nothing
Try
Dim img As FileUpload = CType(imgUpload, FileUpload)
Dim imgByte As Byte() = Nothing
If img.HasFile AndAlso Not img.PostedFile Is Nothing Then
'To create a PostedFile
Dim File As HttpPostedFile = imgUpload.PostedFile
'Create byte Array with file len
imgByte = New Byte(File.ContentLength - 1) {}
'force the control to load data in array
File.InputStream.Read(imgByte, 0, File.ContentLength)
End If
' Insert the employee name and image into db
Dim conn As String =
ConfigurationManager.ConnectionStrings("EmployeeConnString").ConnectionString
connection = New SqlConnection(conn)

connection.Open()
Dim sql As String = "INSERT INTO EmpDetails(empname,empimg)
VALUES(@enm, @eimg) SELECT @@IDENTITY"
Dim cmd As SqlCommand = New SqlCommand(sql, connection)
cmd.Parameters.AddWithValue("@enm", txtEName.Text.Trim())
cmd.Parameters.AddWithValue("@eimg", imgByte)
Dim id As Integer = Convert.ToInt32(cmd.ExecuteScalar())
lblResult.Text = String.Format("Employee ID is {0}", id)
Catch
lblResult.Text = "There was an error"
Finally
connection.Close()
End Try
End Sub

In the code above, we are creating a byte array equal to the length of the file. The byte
array will store the image. We then load the image data into the array. The record
containing the Employee Name and Image is then inserted into the database using the
ADO.NET code. The ID inserted is returned back using the @@Identity. We will shortly use
this ID and pass it as a query string parameter to the ShowImage handler. The image will
then be fetched against the EmployeeID (empid).

Step 4: In order to display the image on the page, we will create an Http handler. To do so,
right click project > Add New Item > Generic Handler > ShowImage.ashx. The code shown
below, uses the Request.QueryString[“id”] to retrieve the EmployeeID from it. The ID is
then passed to the ‘ShowEmpImage()’ method where the image is fetched from the
database and returned in a MemoryStream object. We then read the stream into a byte
array. Using the OutputStream.Write(), we write the sequence of bytes to the current
stream and you get to see your image.

C#

<%@ WebHandler Language="C#" Class="ShowImage" %>

using System;
using System.Configuration;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;

public class ShowImage : IHttpHandler


{
public void ProcessRequest(HttpContext context)
{
Int32 empno;
if (context.Request.QueryString["id"] != null)
empno = Convert.ToInt32(context.Request.QueryString["id"]);
else
throw new ArgumentException("No parameter specified");

context.Response.ContentType = "image/jpeg";
Stream strm = ShowEmpImage(empno);
byte[] buffer = new byte[4096];
int byteSeq = strm.Read(buffer, 0, 4096);

while (byteSeq > 0)


{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 4096);
}
//context.Response.BinaryWrite(buffer);
}

public Stream ShowEmpImage(int empno)


{
string conn = ConfigurationManager.ConnectionStrings
["EmployeeConnString"].ConnectionString;
SqlConnection connection = new SqlConnection(conn);
string sql = "SELECT empimg FROM EmpDetails WHERE empid = @ID";
SqlCommand cmd = new SqlCommand(sql,connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@ID", empno);
connection.Open();
object img = cmd.ExecuteScalar();
try
{
return new MemoryStream((byte[])img);
}
catch
{
return null;
}
finally
{
connection.Close();
}
}

public bool IsReusable


{
get
{
return false;
}
}

VB.NET

<%@ WebHandler Language="vb" Class="ShowImage" %>

Imports System
Imports System.Configuration
Imports System.Web
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient

Public Class ShowImage


Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements
IHttpHandler.ProcessRequest
Dim empno As Int32
If Not context.Request.QueryString("id") Is Nothing Then
empno = Convert.ToInt32(context.Request.QueryString("id"))
Else
Throw New ArgumentException("No parameter specified")
End If

context.Response.ContentType = "image/jpeg"
Dim strm As Stream = ShowEmpImage(empno)
Dim buffer As Byte() = New Byte(4095) {}
Dim byteSeq As Integer = strm.Read(buffer, 0, 4096)

Do While byteSeq > 0


context.Response.OutputStream.Write(buffer, 0, byteSeq)
byteSeq = strm.Read(buffer, 0, 4096)
Loop
'context.Response.BinaryWrite(buffer);
End Sub

Public Function ShowEmpImage(ByVal empno As Integer) As Stream


Dim conn As String =
ConfigurationManager.ConnectionStrings("EmployeeConnString").ConnectionString
Dim connection As SqlConnection = New SqlConnection(conn)
Dim sql As String = "SELECT empimg FROM EmpDetails WHERE empid = @ID"
Dim cmd As SqlCommand = New SqlCommand(sql, connection)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("@ID", empno)
connection.Open()
Dim img As Object = cmd.ExecuteScalar()
Try
Return New MemoryStream(CType(img, Byte()))
Catch
Return Nothing
Finally
connection.Close()
End Try
End Function

Public ReadOnly Property IsReusable() As Boolean Implements


IHttpHandler.IsReusable
Get
Return False
End Get
End Property

End Class

Step 5: One final step. Add the following code in the button click (just above the catch
block) to call the handler and display the newly inserted image from the database. In the
code below, we pass the EmployeeID as a query string parameter to the Http Handler.

C#

// Display the image from the database


Image1.ImageUrl = "~/ShowImage.ashx?id=" + id;

VB.NET

' Display the image from the database


Image1.ImageUrl = "~/ShowImage.ashx?id=" & id

That’s it. Run the code and check out the functionality. Just change the connection string in
the web.config to point to your database. The code works fine for .jpg, .gif and .bmp
images. I would encourage you to extend the sample and include validations in it. Some
validations could be to check the size of the image uploaded, make sure that only images
are uploaded, check the length of the Employee name, prevent the user from entering
numeric and special characters, so on and so forth.

Saving Images in a SQL database using ASP.Net

Posted by poonam on Monday, July 05, 2004


This article demonstrates how to upload image file to a sql database
The ability to display images in a web application is a common requirement. There are two ways
you can do this, either store images in a SQL database using the Binary Large Object (commonly
know as BLOB) data type, or store the image on the disk. There are pro’s and cons to each of
these methods, but in this article we’re going to learn how to store images into a SQL database.
For the purpose of this article I have created a table in SQL Server called Images, with three
columns, Image Name, Image Type and the Image itself. Now let’s take a look at the form we
are going to use, to upload images to this table.
<form id="Form1" method="post" runat="server"
enctype="multipart/form-data">
<br> <br>
<asp:panel id="Panel1" runat="server"
style="Z-INDEX: 102; LEFT: 120px; POSITION: absolute; TOP:
120px"
Width="400px" Height="180px">
<br> <br>
<br>Select File :
<input id="File1" type="file" name="File1" runat="server">
<br> <br>
<input id="Submit1" type="submit"
value="Upload the files >" name="Submit1"
runat="server">
<br> <br>
<asp:Label id="Label1" runat="server"></asp:Label>
</asp:panel>
</form>
Note: that the form enctype is multipart/form-data. This is necessary when we upload client files to
a server.
So far, this looks pretty straightforward. Let’s take a look at the code which will process this
request. To start with we see that File1 is derived from the HtmlInputfileclass
protected System.Web.UI.HtmlControls.HtmlInputFile File1;
This allows programmatic access to the HTML <input type= file> element on the server. We are
going to use the PostedFile class to get the properties of the client image file. In the following
piece of code we use the ContentLength and ContentType methods of this class to get the length,
and type of the image file.
HttpPostedFile selectedFile = File1.PostedFile;
int imageLength = selectedFile.ContentLength;
string imageType = selectedFile.ContentType;
If we were going to save this file to the server, all we need to do, is use the SaveAs method. In this
case we are going to store the image in a SQL database, so we need to convert it into a format
that SQL can understand. We are going to create a byte array. The size of the array is the length
of the image that we were able to retrieve using the Contentlength property of the HttpPostedFile
class.
binaryImagedata = new byte[imageLength];
The HttpPostedFile class also has an InputStream method, which returns the image data in bytes.
We are going to use this to populate our byte array
selectedFile.InputStream.Read(binaryImagedata,0,imageLength);
We now have all the fields needed (imageLength, File1.PostedFile.FileName and
binaryImagedata) to populate the database.
This covers the basics of how to upload an image to a database. In a real application, there are
other things we might want to do, for example some validation checks. By checking the value of
selectedFile.ContentLength you can enforce size restrictions on the image file. A ContentLength
of 0, indicates that the file either does not exist or an empty file is being uploaded. The following
code would check for empty files :
if (selectedFile.ContentLength==0)
{
errs ="0 length file ";
}
Note: The default file size that can be uploaded is 4MB, and a larger size will cause .Net to
throw an exception. To change the default size for all applications on the server, the
machine.config file will need to be modified. In the httpRuntime section, there is a
maxRequestLength attribute, <maxRequestLength="4096">. Change the length to whatever new
default you need.
If you want to make the change for only a single application however, then this setting can be
overridden in the web.config file of the application in question. You would need to create a
<httpRuntime> section and add the maxRequestLength attribute with the size you require. For
further information on this topic, see the documentation for the
HttpRuntime element
We can also check the value of selectedFile.ContentType and verify if the file type is one we
allow to be uploaded. The ContentType returns the MIME encoding in string format of the
request. This is typically in category / subcategory format. Some common types include
"text/HTML" or "image/GIF". To ensure that the user can only upload GIF files, add the following
code
if (selectedFile.ContentType.ToLower() != @"image/gif")
{
errs +="Invalid filetype";
}
In some cases we might also need to check for the dimensions of the image. Often, an
application has a pre-determined space to display the image, and you might want to ensure that
the height and width of the image match the allotted space. The HttpPostedFile class is not limited
to just image files, so does not provide for any methods to retrieve this information. To retrieve
further information about images, we are going to use the image class in the System.Drawing
namespace. For the purpose of this article we are only interested in the length and width of the
image, however there is a lot more that you can do with this class, refer to
System.Drawing.Image . To start with we create an Image object
System.Drawing.Image drawingImage = null;
The next step is to read the byte array binaryImagedata into our Image object.
drawingImage = System.Drawing.Image.FromStream(new
System.IO.MemoryStream(binaryImagedata));
Now we have access to both the height and width of the array, so if your application requires
your images have a length and width of 300 px you would use the following code
If ((drawingImage.Width != 300) && (drawingImage.Height != 300)) {
Errs = “Image is the wrong size”;
}
Hopefully this article covers all the basic elements of uploading images to a SQL database. To
retrieve images to display in a web form - Displaying SQL Images in an ASP.Net datagrid,.

Save an Image to SQL Server


Author Rank:
By Scott Lysle November 27, 2006 Total page
views : 167742
This article describes an easy approach to saving an image file into an Total
SQL Server 2000 database table as an SQL Server image data type. downloads :
3722

Share
Add to
Technorati

Post a Similar Digg This


Print
comment Articles
Add to
del.icio.us

Kick It

Email to a Author's other


Bookmark
friend articles
SqlServerImages.zip
Download Files:
Sponsored by
<SCRIPT language='JavaScript1.1'
SRC="http://ad.doubleclick.net/adj/N5621.124662.7163663382421/B4682230;abr=!
ie;sz=336x280;click=;ord=[timestamp]?"> </SCRIPT> <NOSCRIPT> <A
HREF="http://ad.doubleclick.net/jump/N5621.124662.7163663382421/B4682230;abr=!
ie4;abr=!ie5;sz=336x280;ord=[timestamp]?"> <IMG
SRC="http://ad.doubleclick.net/ad/N5621.124662.7163663382421/B4682230;abr=!ie4;abr=!
ie5;sz=336x280;ord=[timestamp]?" BORDER=0 WIDTH=336 HEIGHT=280
ALT="Advertisement"></A> </NOSCRIPT>
Become a Sponsor

Similar ArticlesMost ReadTop RatedLatest


Understand various functionalities and exceptions of System.drawing.image in VB.NET
How to insert an image in database SQL Server with VB.NET.
Saving Images & Image Format Properties in GDI+
Flash Cards Program : How to read and save images in a SQL Server database
Run time XML File create and Image upload and save in VB.NET.

More...

Working with Strings in VB.NET


Displaying data in a DataGrid in VB.NET
Creating an Excel Spreadsheet programmatically using VB.NET
Exception Handling in VB.NET
Creating a SQL Server database programmatically using VB.NET

More...

A Simple Web Service in VB.NET


Flash Player Custom Control for ASP.NET 2.0
Saving and reading Objects
Tic Tac Toe Game in VB.NET
Drawing transparent Images and Shapes using Alpha Blending

More...
How to calll stored procedure in ADO.NET
How to Generate Fibonacci Series with an Algorithm
How to create JQuery Tooltip Plugins
How to find the "Factorial of an Number" an Algorithm
How to find the Quadrant an Algorithm

More...
Storing and retrieving Images from Access
database using VB.Net
• Download source files (38.52 kb)
• Download demo project (52.11 Kb)

Introduction
This is a simple code snippet which is used to store and retrieve images from Access database
using VB.net.
Code
view source

print?

1 Private Sub ShowDetails()

2 Try

Dim cn As New
3
OleDb.OleDbConnection

4 Dim cmd As OleDb.OleDbCommand


5 Dim dr As OleDb.OleDbDataReader

7 cn.ConnectionString = mstrConnection

8 cn.Open()

10 cmd = cn.CreateCommand()

cmd.CommandText = "SELECT I_Image FROM tblImage WHERE I_Name = '" &


11
cbI_Name.Text & "'"

12

13 dr = cmd.ExecuteReader

14

15 If dr.Read Then

16 Dim bytImage() As Byte

17

18 Try

19 bytImage = CType(dr(0), Byte())

Dim ms As New
20
System.IO.MemoryStream(bytImage)

Dim bmImage As New


21
Bitmap(ms)
22 ms.Close()

23

24 pbI_Image.Image = bmImage

25 pbI_Image.Refresh()

26 Catch ex As Exception

27 MsgBox(ex.ToString)

28 End Try

29 End If

30

31 dr.Close()

32 cn.Close()

33

34 cmd.Dispose()

35 cn.Dispose()

36 Catch ex As Exception

37 MsgBox(ex.ToString)

38 End Try

39 End Sub
40

41 Private Sub SaveData()

42 Try

Dim cn As New
43
OleDb.OleDbConnection

44 Dim cmd As OleDb.OleDbCommand

45

46 cn.ConnectionString = mstrConnection

47 cn.Open()

48

49 cmd = cn.CreateCommand()

50

51 If mstrFlag = "N" Then

cmd.CommandText = "INSERT INTO tblImage VALUES (@I_Name,


52
@I_Image)"

53 ElseIf mstrFlag = "M" Then

cmd.CommandText = "UPDATE tblImage SET I_Name = @I_Name,


54
I_Image = @I_Image WHERE I_Name = '" & cbI_Name.Tag.ToString & "'"

55 End If
56

57 Dim bytImage() As Byte

58

59 Try

Dim ms As New
60
System.IO.MemoryStream

Dim bmpImage As New


61
Bitmap(pbI_Image.Image)

62

63 bmpImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)

64 bytImage = ms.ToArray()

65 ms.Close()

66 Catch ex As Exception

67 MsgBox(ex.ToString)

68 End Try

69

cmd.Parameters.Add(New OleDb.OleDbParameter("@I_Name",
70
OleDb.OleDbType.VarChar, 120))

cmd.Parameters.Add(New OleDb.OleDbParameter("@I_Image",
71
OleDb.OleDbType.Binary))
72 cmd.Parameters("@I_Name").Value = cbI_Name.Text

73 cmd.Parameters("@I_Image").Value = bytImage

74

75 If cmd.ExecuteNonQuery() > 0 Then

MsgBox("Record has been " & IIf(mstrFlag = "N", "added",


76
"modified").ToString & " successfully.", MsgBoxStyle.Information)

77 End If

78

79 cmd.Dispose()

80 cn.Dispose()

81 Catch ex As Exception

82 MsgBox(ex.ToString)

83 End Try

84

85 FillData()

86 End Sub

Storing Images into a Database using VB.NET Total page


views :
By aghiondea2 October 18, 2004 111995
In order to provide your application with cool pictures you can employ two Total
techniques (at least). One of them is that you can save the pictures in a folder downloads :
and store the path to each one in a database or configuration file. The other 3009
one is to store the entire file into a database, along with its file name.

Share
Add to
Technorati

Post a Similar Digg This


Print
comment Articles
Add to
del.icio.us

Kick It

Email to a Author's other


Bookmark
friend articles
PicturesInSQLServer.zip
Download Files:
Sponsored by

Introduction

In order to provide your


application with cool
pictures you can employ
two techniques (at least).
One of them is that you
can save the pictures in a
folder and store the path
to each one in a database
or configuration file. The
other one is to store the
entire file into a
database, along with its
file name.

Each of them has its ups


and downs: Become a Sponsor
• If you save your
files to a folder, Similar ArticlesMost ReadTop RatedLatest
you might How to calll stored procedure in ADO.NET
accidentally delete How to retrieve an image from database with VB.NET.
a file from that How to insert an image in database SQL Server with VB.NET.
folder. If this
happens, you will Writing Managed Stored Procedures using VB.NET
end up with a Executing Stored Procedure using LINQ
broken "link" in
your database or
configuration file.
However, the hard More...
disk storage space
is cheap, so you
Working with Strings in VB.NET
can afford to store
a lot of files. Displaying data in a DataGrid in VB.NET
• If you store your
Creating an Excel Spreadsheet programmatically using VB.NET
files into a Exception Handling in VB.NET
database, you can Creating a SQL Server database programmatically using VB.NET
enforce security
by using the
security settings More...
of the database.
Also, there are no
broken links ever.
A Simple Web Service in VB.NET
However, the Flash Player Custom Control for ASP.NET 2.0
database storage Saving and reading Objects
space is more Tic Tac Toe Game in VB.NET
expensive.
Drawing transparent Images and Shapes using Alpha Blending
Another idea is
that you can save
a thumbnail of the

More...
How to calll stored procedure in ADO.NET
How to Generate Fibonacci Series with an Algorithm
How to create JQuery Tooltip Plugins
How to find the Quadrant an Algorithm

More...

Store or Save images in SQL Server


By Shabdar Ghata | 5 Mar 2010
.NET2.0Win2KWinXPWin2003VistaSQL2000SQL2005VS2005C#1.0C#2.0, +
A sample program to demonstrate how to save or store images in SQL server

Part of The SQL Zone sponsored by


See Also
• Articles like this
• Articles by this author

Print Article

Twitter

Digg

Facebook

Del.icio.us

Reddit

Stumbleupon

Newsvine

Technorati

Mr. Wong

Yahoo!

Google

Windows Live

Send as Email
Add to your CodeProject bookmarks
Discuss this article

15
Report this article as inappropriate

Article Browse Code StatsRevisions (4)

2.37 (18 votes)

1 2 3 45
Sponsored Links
Top of Form
/w EPDw UKMTAy

• Download source code - 235.22 KB


• Download latest version of source code (external link)
Introduction
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:

Collapse
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();
}
The following code explains how to read an image file into a byte array:

Collapse
//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.

Collapse
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 the grid, get image data from grid cell. Alternatively you can also
get image data from Dataset table cell.

Collapse
//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 PictureBox to a local image file.

Collapse
//Store image to a local file.
pictureBox1.Image.Save("c:\test_picture.jpg",System.Drawing.Imaging.ImageForm
at.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 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 http://www.shabdar.org 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.

Requirements
• Visual Studio .NET 2005
• .NET Framework 2.0
• Microsoft SQL Server 2000 database or Microsoft SQL Server 2005 database
Bottom of Form
Bottom of Form

You might also like