img sql

53
Save An Image Into SQL Server 2000 Database By vivekthangaswamy | 25 Feb 2005 .NET1.1 SQL2000 VS.NET2003 C# ASP.NET SQL Windows DBA Dev Intermediate 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 Sta Revisi

Transcript of img sql

Page 1: img sql

Save An Image Into SQL Server 2000 DatabaseBy vivekthangaswamy | 25 Feb 2005 .NET1.1 SQL2000 VS.NET2003 C# ASP.NET SQL Windows DBA Dev Intermediate 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 5Sponsored Links

Page 2: img sql

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 o System.Web.UI.HtmlControls.HtmlInputFile o System.Web.UI.WebControls.TextBox o System.Web.UI.WebControls.Button

Namespaces used in this application:

Collapse

using System.Data.SqlClient;using System.Drawing;using System.Data;

/w EPDwUKMTAy

Page 3: img sql

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.

Collapseprivate void Page_Load(object sender, System.EventArgs e){ // Put user code to initialize the page here

Page 4: img sql

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 1 retweet

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.

Page 5: img sql

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.

Page 6: img sql

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] GOUSE [Employee]GOCREATE 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" />

Page 7: img sql

        &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 dbstring 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();

Page 8: img sql

        }

     }

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#

Page 9: img sql

<%@ 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();        }    }

Page 10: img sql

     public bool IsReusable    {        get        {            return false;        }    }

  }

VB.NET

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

 Imports SystemImports System.ConfigurationImports System.WebImports System.IOImports System.DataImports 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()

Page 11: img sql

        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 databaseImage1.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

Page 12: img sql

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];

Page 13: img sql

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 arrayselectedFile.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;

Page 14: img sql

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

By  Scott Lysle November 27, 2006

This article describes an easy approach to saving an image file into an SQL Server 2000 database table as an SQL Server image data type.

Author Rank: Total page views :  167742 Total downloads :  3722

    Print   Post a

comment   Similar

Articles

Share

Add to Technorati

Digg This

Add to del.icio.us

Kick It

 

    Email to a

friend   Bookmark

  Author's other articles

 

Download Files: SqlServerImages.zi

p  

  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=!

Page 15: img sql

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

Introduction:

This article describes an easy approach to saving an image file into an SQL Server 2000 database table as an SQL Server image data type. The sample windows forms application provides a simple interface used to allow the user to select an image file (bitmap, gif, or jpeg) from the file system, title the image, and load the selected into a table in an SQL Server 2000 database. The user may also open an image viewer and examine the images contained in the database; images displayed in the simple viewer display the image, the title of the image, the image type, and the image height and width.

Page 16: img sql

Figure 1: An Image Stored in SQL Server 2000

Getting Started

In order to get started, unzip the included project and open the solution in the Visual Studio 2005 environment. In the solution explorer, you should note the following:

Figure 2: Solution Explorer

Within the solution, the app.config file contains a connection string used with the SQL Server 2000 database used to contain the images. As the configuration file is aimed at my local instance of SQL Server 2000, you will need to modify the connection to point to your database.

<connectionStrings>    <add name="SqlServerImages.My.MySettings.ImageGalleryConnectionString"        connectionString="Data Source=bxswlt;Initial Catalog=ImageGallery;User                             ID=sa"        providerName="System.Data.SqlClient" /></connectionStrings>

Page 17: img sql

In order to support this example, a simple database entitled, "ImageGallery" was added to my SQL Server instance and a table entitled, "ImageCollection" was added to the database. The image collection table (see figure 3) contains the following columns:

ImageContent ImageTitle ImageType ImageHeight ImageWidth

The specification for each of these columns is shown in figure 3. Given the simplicity of the database, I did not include it with the sample application. If you intend to run the sample code, create the database and table using the table properties shown as a guide; also, go ahead and add a data source to the project and point the source to this database.

Figure 3: Table Definition

Code: Main Form (frmMain.vb)

The main form of the sample application (see figure 4) contains the controls necessary to browse for an image file, provide the file with a title, load the image file selected into SQL Server, and to open a viewer to examine the images stored in the table.

Page 18: img sql

Figure 4: Main Form of the Application

The form class includes the following imports:

Imports System.IOImports System.DataImports System.Data.SqlClientImports System.Data.SqlTypes

The class also creates two private member variables used to share data between methods exposed in the class; one variable is used to capture the selected image and the other is used to capture the path to the selected image:

Private mImageFile As ImagePrivate mImageFilePath As String

The find button click event handler calls an Open File Dialog which is used to navigate to and select an image file. The dialog supports searches for bitmaps, jpegs, and gif files. The code used if the click event handler is as follows:

Private Sub btnFind_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFind.Click    OpenFileDialog1.Title = "Set Image File"   OpenFileDialog1.Filter = "Bitmap Files|*.bmp" & _       "|Gif Files|*.gif|JPEG Files|*.jpg"   OpenFileDialog1.DefaultExt = "bmp"   OpenFileDialog1.FilterIndex = 1   OpenFileDialog1.FileName = ""   OpenFileDialog1.ShowDialog()

Page 19: img sql

    If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.Cancel Then       Exit Sub   End If    Dim sFilePath As String   sFilePath = OpenFileDialog1.FileName   If sFilePath = "" Then Exit Sub    If System.IO.File.Exists(sFilePath) = False Then       Exit Sub   Else       txtImageFile.Text = sFilePath       mImageFilePath = sFilePath   End If End Sub

The code opens the Open File Dialog box with the image types used as a filter and the default extension type set to bitmap. The file selected by the user is validated to make sure that it exists, and if it does, the text box used to display the selected file path is updated to display the path to and name of the file selected by the user. Also, the member variable used to display the path to the image file is also updated.

The load button click event handler is used to load the image and image related data into SQL Server. That code is as follows:

Private Sub btnLoad_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoad.Click         Try            If (Me.txtImageFile.Text = String.Empty Or Me.txtTitle.Text =                 String.Empty) Then                MessageBox.Show("Complete both form fields prior to submitting",                 "Missing Values", _                MessageBoxButtons.OK, MessageBoxIcon.Exclamation)                Exit Sub            End If        Catch ex As Exception            MessageBox.Show(ex.Message.ToString(), "File Test Error")        End Try         Dim fs As FileStream = New FileStream(mImageFilePath.ToString(),         FileMode.Open)        Dim img As Byte() = New Byte(fs.Length) {}        fs.Read(img, 0, fs.Length)        fs.Close()         mImageFile = Image.FromFile(mImageFilePath.ToString())        Dim imgHeight As Integer = mImageFile.Height        Dim imgWidth As Integer = mImageFile.Width        Dim imgLength As Integer = mImageFile.PropertyItems.Length        Dim imgType As String = Path.GetExtension(mImageFilePath)        mImageFile = Nothing         Dim strConnect As String

Page 20: img sql

        strConnect = "Data Source=bxswlt;Initial Catalog=ImageGallery;User ID=sa"        Dim conn As SqlConnection = New SqlConnection(strConnect)         Dim sSQL As String = "INSERT INTO ImageCollection (ImageContent, " & _                "ImageTitle, ImageType, ImageHeight, ImageWidth) VALUES(" & _                "@pic, @title, @itype, @iheight, @iwidth)"         Dim cmd As SqlCommand = New SqlCommand(sSQL, conn)         ' image content        Dim pic As SqlParameter = New SqlParameter("@pic", SqlDbType.Image)        pic.Value = img        cmd.Parameters.Add(pic)         ' title        Dim title As SqlParameter = New SqlParameter("@title",         System.Data.SqlDbType.VarChar, 50)        title.Value = txtTitle.Text.ToString()        cmd.Parameters.Add(title)         ' type        Dim itype As SqlParameter = New SqlParameter("@itype",         System.Data.SqlDbType.Char, 4)        itype.Value = imgType.ToString()        cmd.Parameters.Add(itype)         ' height        Dim iheight As SqlParameter = New SqlParameter("@iheight",         System.Data.SqlDbType.Int)        iheight.Value = imgHeight        cmd.Parameters.Add(iheight)         ' width        Dim iwidth As SqlParameter = New SqlParameter("@iwidth",         System.Data.SqlDbType.Int)        iwidth.Value = imgWidth        cmd.Parameters.Add(iwidth)         Try            conn.Open()            cmd.ExecuteNonQuery()            conn.Close()            MessageBox.Show("Query executed.", "Image Load")        Catch ex As Exception            MessageBox.Show(ex.Message.ToString(), "Data Error")            Exit Sub        End TryEnd Sub

Within this block of code, the first thing that takes place is a validation that the user has supplied a path to the image file and has provided a title for the file:

Try     If (Me.txtImageFile.Text = String.Empty Or Me.txtTitle.Text =          String.Empty) Then

Page 21: img sql

         MessageBox.Show("Complete both form fields prior to submitting",          "Missing Values", _         MessageBoxButtons.OK, MessageBoxIcon.Exclamation)         Exit Sub     End IfCatch ex As Exception     MessageBox.Show(ex.Message.ToString(), "File Test Error")End Try

After confirming the user input, the image file is converted to a byte array. This byte array will subsequently be passed to the database as the image.

Dim fs As FileStream = New FileStream(mImageFilePath.ToString(), FileMode.Open)Dim img As Byte() = New Byte(fs.Length) {}fs.Read(img, 0, fs.Length)fs.Close()

After the file stream object is closed, the image is loaded into an image from the source file and the loaded image is used to capture the characteristics of the image and to set local variables to contain the image information (e.g., height, width, and type of image). By storing this information in the table, it would be easier to filter for image types in the database and to dynamically create picture box controls sized to accommodate the stored image.

mImageFile = Image.FromFile(mImageFilePath.ToString())Dim imgHeight As Integer = mImageFile.HeightDim imgWidth As Integer = mImageFile.WidthDim imgLength As Integer = mImageFile.PropertyItems.LengthDim imgType As String = Path.GetExtension(mImageFilePath)mImageFile = Nothing

Once the local variables are set and the image disposed of, the insert query used to submit the data to the database is configured: (update the connection string to match your settings; and no, you would not really put your connection string into the application in this manner, instead, use the one in the app.config file)

Dim strConnect As StringstrConnect = "Data Source=bxswlt;Initial Catalog=ImageGallery;User ID=sa"Dim conn As SqlConnection = New SqlConnection(strConnect) Dim sSQL As String = "INSERT INTO ImageCollection (ImageContent, " & _        "ImageTitle, ImageType, ImageHeight, ImageWidth) VALUES(" & _        "@pic, @title, @itype, @iheight, @iwidth)" Dim cmd As SqlCommand = New SqlCommand(sSQL, conn)

After the connection is created and the command text set, the parameters are defined, and each is added to the command's parameter collection:

' image contentDim pic As SqlParameter = New SqlParameter("@pic", SqlDbType.Image)pic.Value = imgcmd.Parameters.Add(pic) ' title

Page 22: img sql

Dim title As SqlParameter = New SqlParameter("@title", System.Data.SqlDbType.VarChar, 50)title.Value = txtTitle.Text.ToString()cmd.Parameters.Add(title) ' typeDim itype As SqlParameter = New SqlParameter("@itype", System.Data.SqlDbType.Char, 4)itype.Value = imgType.ToString()cmd.Parameters.Add(itype) ' heightDim iheight As SqlParameter = New SqlParameter("@iheight", System.Data.SqlDbType.Int)iheight.Value = imgHeightcmd.Parameters.Add(iheight) ' widthDim iwidth As SqlParameter = New SqlParameter("@iwidth", System.Data.SqlDbType.Int)iwidth.Value = imgWidthcmd.Parameters.Add(iwidth)

After everything is set, the only thing remaining is to post the data to the database:

Try    conn.Open()    cmd.ExecuteNonQuery()    conn.Close()    MessageBox.Show("Query executed.", "Image Load")Catch ex As Exception    MessageBox.Show(ex.Message.ToString(), "Data Error")    Exit SubEnd Try

Assuming that everything posted properly, the user will be notified that the query has completed; if the insert fails, the user will be provided with a description of the error.

The only other code in the main form is used to handle the viewer button click; this handler creates a new instance of the viewer and displays it to the user:

Private Sub btnViewer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnViewer.Click    Dim f As New frmViewer()    f.Show()End Sub

Code:  Viewer (frmViewer.vb)

This is going to be a short section as the viewer does not contain any hand written code. The viewer contains a binding navigator and a few text fields dragged onto the form from the project data source. The text fields are bound to the binding source and are updated through the binding navigator. The picture box control used to display the image has its data bindings set to point to the image data contained in the database. Whenever the binding navigator is sequenced up or

Page 23: img sql

down, the image and bound text are updated to the display the values associated with the current record.

Figure 5: Picture Box Control Data Bindings

Summary

Whether or not it is a terrific idea to store images in a database is debatable, some would advocate the storage of path strings in the database to reduce the overhead in lieu of actually storing the images which is certainly a valid consideration. In systems involving large volumes of imagery data, reliance upon stored paths could very well be a requirement. In other instances where only a limited amount of imagery data is stored, there is less of an argument to be made against it. 

In the simple viewer provided, the display of the images was managed entirely by binding it to the image source from the image content database column; it is possible to reconstruct the image manually from the byte array but I did not include a description of that process as it seems likely that binding the control to the record would be the sufficient for most situations.

Storing and retrieving Images from Access database using VB.Net

Download source files (38.52 kb) Download demo project (52.11 Kb)

Page 24: img sql

 

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

3         Dim cn As New OleDb.OleDbConnection

4         Dim cmd As OleDb.OleDbCommand

5         Dim dr As OleDb.OleDbDataReader

6

7         cn.ConnectionString = mstrConnection

8         cn.Open()

9

10         cmd = cn.CreateCommand()

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

Page 25: img sql

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())

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

21                 Dim bmImage As New 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()

Page 26: img sql

36     Catch ex As Exception

37         MsgBox(ex.ToString)

38     End Try

39 End Sub

40

41 Private Sub SaveData()

42     Try

43         Dim cn As New 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

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

53         ElseIf mstrFlag = "M" Then

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

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

55         End If

56

57         Dim bytImage() As Byte

58

59         Try

Page 27: img sql

60             Dim ms As New System.IO.MemoryStream

61             Dim bmpImage As New 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

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

71        cmd.Parameters.Add(New OleDb.OleDbParameter("@I_Image", 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

76            MsgBox("Record has been " & IIf(mstrFlag = "N", "added", "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

Page 28: img sql

84

85     FillData()

86 End Sub

Storing Images into a Database using VB.NET

By  aghiondea2  October 18, 2004

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.

Total page views :  111995 Total downloads :  3009

    Print   Post a

comment   Similar

Articles

Share

Add to Technorati

Digg This

Add to del.icio.us

Kick It

 

    Email to a

friend   Bookmark

  Author's other articles

 

Download Files: PicturesInSQLServer.zip  

  Sponsored by

Page 29: img sql

Become a Sponsor Similar ArticlesMost ReadTop RatedLatest How to calll stored procedure in ADO.NET How to retrieve an image from database with VB.NET. How to insert an image in database SQL Server with VB.NET. Writing Managed Stored Procedures using VB.NET Executing Stored Procedure using LINQ

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

Introduction

Page 30: img sql

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:

If you save your files to a folder, you might accidentally delete a file from that folder. If this happens, you will end up with a broken "link" in your database or configuration file. However, the hard disk storage space is cheap, so you can afford to store a lot of files.

If you store your files into a database, you can enforce security by using the security settings of the database. Also, there are no broken links ever. However, the database storage space is more expensive. Another idea is that you can save a thumbnail of the image on the database for quick access and to save the actual picture on hard drive.

Of course, each application has its particularities and you have to choose which one you will use. Ok. Enough of the philosophical talk! Let's dive into the good stuff.

The application

The problem of uploading files to a database is not that difficult. You have to use, on the server, a certain data type when creating the table. This data type has to be capable of storing large amounts of binary data. When using Microsoft SQL Server, this data type is called image. For more information see BLOB (Binary Large OBject) for a short definition and Books Online for a complete reference.

The client has to obtain the data from the file in binary format - a byte array - and to call a procedure on the server with that array as a parameter.

In this presentation I assume that I have a database Pictures on the server with a table called Pictures. The structure of this table is as follows:

Field Name Field Type

kFileName Long

Picture Image

FileName Varchar(250)

I also have stored procedures for uploading, downloading and retrieving the list of uploaded files. These procedures are shown below:

Procedure Name Procedure body

UploadFile CREATE PROCEDURE [dbo].[UploadFile]( @Picture image, @FileName varchar(250), @kFileName bigint output)ASinsert into Pictures (Picture, FileName) values (@Picture,@FileName)

Page 31: img sql

set @kFileName = @@IDENTITYGO

DownloadFile

CREATE PROCEDURE [dbo].[DownloadFile]( @kFileName bigint, @FileName varchar(250) output)ASselect Picture, FileName from Pictures where kFileName=@kFileNameGO

getUploadedFiles

CREATE PROCEDURE [dbo].[getUploadedFiles]ASselect ltrim(str(kFileName)) + " - " + FileName as Name from PicturesGO

The code presented below was written using VB.Net and was tested in Visual Studio .NET 2003. The client code that gets the byte array from the file and calls these procedures is shown below.

Imports Microsoft.VisualBasicImports SystemImports System.IOImports System.DataImports System.TextImports System.Data.SqlClient''* Autor: Ghiondea Alexandru'* Date: 08 october 2004'* Description: Implements methods for uploading and downloading files'* with MS SQL Server'*Namespace PicturesInSQLServer''' <summary>''' This class manages uploads and downloads to and from an SQL Server

''' </summary>Public Class TransferPictures''' <summary>''' Gets from the server a list of uploaded files into a dataSet''' </summary>''' <param name="ds">The dataset</param>''' <param name="table">The table in the dataset</param>

Public Sub GetUploadedFiles(ByRef ds As DataSet, ByVal table As String)'' The variables required for connecting to the server.'Dim conn As SqlConnection = NothingDim cmd As SqlCommand = NothingDim da As SqlDataAdapter = Nothing' ----------------------------------------------

Page 32: img sql

Try'' If the table already exists, cleares its content. Else adds a new table.'If ds.Tables.Contains(table) Thends.Tables(table).Clear()Elseds.Tables.Add(table)End If' ----------------------------------------------'' Creates a connection to the database and initilizes the command'conn = New SqlConnection(ConnectionString())cmd = New SqlCommand("getUploadedFiles", conn)cmd.CommandType = CommandType.StoredProcedure' ----------------------------------------------'' Initializes the DataAdapter used for retrieving the data'da = New SqlDataAdapter(cmd)' ----------------------------------------------'' Opens the connection and populates the dataset'conn.Open()da.Fill(ds, table)conn.Close()' ----------------------------------------------Catch e As Exception'' If an error occurs, we assign null to the result and display the error to the user,' with information about the StackTrace for debugging purposes.'Console.WriteLine(e.Message & " - " & e.StackTrace)End TryEnd Sub''' <summary>''' Uploads a file to the database server.''' </summary>''' <param name="fileName">The filename of the picture to be uploaded</param>''' <returns>The id of the file on the server.</returns>Public Function UploadFile(ByVal FileName As String) As LongIf (Not File.Exists(FileName)) ThenReturn -1End IfDim fs As FileStream = NothingTry'#Region "Reading file"fs = New FileStream(FileName, FileMode.Open)'' Finding out the size of the file to be uploaded'Dim fi As FileInfo = New FileInfo(FileName)Dim temp As Long = fi.Length

Page 33: img sql

Dim lung As Integer = Convert.ToInt32(temp)' ------------------------------------------'' Reading the content of the file into an array of bytes.'Dim picture As Byte() = New Byte(lung - 1) {}fs.Read(picture, 0, lung)fs.Close()' ------------------------------------------'#End RegionDim result As Long = uploadFileToDatabase(picture, fi.Name)Return resultCatch e As ExceptionConsole.WriteLine(e.Message & " - " & e.StackTrace)Return -1End TryEnd Function''' <summary>''' Wrapper for downloading a file from a database.''' </summary>''' <param name="kFileName">The Unique ID of the file in database</param>''' <param name="fileName">The file name as it was stored in the database.</param>''' <returns>The byte array required OR null if the ID is not found</returns>Public Function DownloadFile(ByVal kFileName As Long, ByRef fileName As String) As Byte()Dim result As Byte() = downloadFileFromDatabase(kFileName, fileName)Return resultEnd Function''' <summary>''' Returns the connection string for connecting to the database''' </summary>''' <returns>The Connection string.</returns>Public Shared Function ConnectionString() As String'' We consider that the database is situated on the same computer that runs the program.' To connect to a remote server, replace 'Data Source' with the name of that server.'Return "Connect Timeout=600;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Pictures;Packet Size=4096;Data Source=" & System.Environment.MachineName.Trim()'.........You can also use........'Dim Conn As String = "Server=.;uid=sa;pwd=;database=Pictures"'Return ConnEnd Function''' <summary>''' Uploades a file to an SQL Server.''' </summary>''' <param name="picture">A byte array that contains the information to be uploaded.</param>''' <param name="fileName">The file name asociated with that byte array.</param>''' <returns>The unique ID of the file on the server OR -1 if an error occurs. </returns>Private Function uploadFileToDatabase(ByVal picture As Byte(), ByVal fileName As String) As Long'' Defining the variables required for accesing the database server.'

Page 34: img sql

Dim conn As SqlConnection = NothingDim cmd As SqlCommand = NothingDim kFileName As SqlParameter = Nothing'INSTANT VB NOTE: The local variable FileName was renamed since Visual Basic will not uniquely identify local variables when other local variables have the same name:Dim FileName_Renamed As SqlParameter = NothingDim pic As SqlParameter = Nothing' By default, we assume we have an error. If we succed in uploading the file, we'll change this ' to the unique id of the fileDim result As Long = -1Try'' Connecting to database.'conn = New SqlConnection(ConnectionString())cmd = New SqlCommand("UploadFile", conn) ' We assume there is a stored procedure called UploadFilecmd.CommandType = System.Data.CommandType.StoredProcedure' ----------------------------------------------'' Initializing parameters and assigning the values to be sent to the server'kFileName = New SqlParameter("@kFileName", System.Data.SqlDbType.BigInt, 4)kFileName.Direction = ParameterDirection.Output' This parameter does not have a size because we do not know what the size is going to be.pic = New SqlParameter("@picture", SqlDbType.Image)pic.Value = pictureFileName_Renamed = New SqlParameter("@FileName", SqlDbType.VarChar, 250)FileName_Renamed.Value = fileName' ----------------------------------------------'' Adding the parameters to the database. Remember that the order in which the parameters ' are added is VERY important!'cmd.Parameters.Add(pic)cmd.Parameters.Add(FileName_Renamed)cmd.Parameters.Add(kFileName)' ----------------------------------------------'' Opening the connection and executing the command.'conn.Open()cmd.ExecuteNonQuery()conn.Close()' ----------------------------------------------'' The result is the unique identifier created on the database.'result = CLng(kFileName.Value)' ----------------------------------------------'' Disposing of the objects so we don't occupy memory.'conn.Dispose()

Page 35: img sql

cmd.Dispose()' ----------------------------------------------Catch e As Exception'' If an error occurs, we report it to the user, with StackTrace for debugging purposes'Console.WriteLine(e.Message & " - " & e.StackTrace)result = -1' ----------------------------------------------End TryReturn resultEnd Function

''' <summary>''' Downloades a file from a database according to the unique id in that database.''' </summary>''' <param name="kFile">The ID of the file in the database</param>''' <param name="FileName">The filename of the file as it was stored in the database.</param>''' <returns>A byte array containing the information required.</returns>Private Function downloadFileFromDatabase(ByVal kFile As Long, ByRef FileName As String) As Byte()Dim conn As SqlConnection = NothingDim cmd As SqlCommand = NothingDim kFileName As SqlParameter = Nothing'INSTANT VB NOTE: The local variable fileName was renamed since Visual Basic will not uniquely identify local variables when other local variables have the same name:Dim fileName_Renamed As SqlParameter = NothingDim dr As SqlDataReader = NothingDim result As Byte() = NothingTry'' Connecting to database.'conn = New SqlConnection(ConnectionString())cmd = New SqlCommand("DownloadFile", conn)cmd.CommandType = System.Data.CommandType.StoredProcedure' ----------------------------------------------'' Initializing parameters and assigning the values to be sent to the server'kFileName = New SqlParameter("@kFileName", System.Data.SqlDbType.BigInt, 8)kFileName.Value = kFilefileName_Renamed = New SqlParameter("@FileName", SqlDbType.VarChar, 250)fileName_Renamed.Direction = ParameterDirection.Output' ----------------------------------------------'' Adding the parameters to the database. Remember that the order in which the parameters ' are added is VERY important!'cmd.Parameters.Add(kFileName)cmd.Parameters.Add(fileName_Renamed)' ----------------------------------------------'' Opening the connection and executing the command.

Page 36: img sql

' The idea behind using a dataReader is that, on the SQL Server, we cannot assign to a' variable the value of an image field. So, we use a querry to select the record we want ' and we use a datareader to read that query.' Because we are returnig information based on a primary key, we are always returning' only one row of data.'conn.Open()dr = cmd.ExecuteReader()dr.Read()'' We are casting the value returned by the datareader to the byte[] data type.'result = CType(dr.GetValue(0), Byte())'' We are also returning the filename associated with the byte array.'FileName = CStr(dr.GetValue(1))'' Closing the datareader and the connection'dr.Close()conn.Close()' ------------------------------------------'' Disposing of the objects so we don't occupy memory.'conn.Dispose()cmd.Dispose()' ------------------------------------------Catch e As Exception'' If an error occurs, we assign null to the result and display the error to the user,' with information about the StackTrace for debugging purposes.'Console.WriteLine(e.Message & " - " & e.StackTrace)result = NothingEnd TryReturn resultEnd FunctionEnd ClassEnd Namespace

I have also written a small application to demonstrate how to use these methods. A screenshot of it is shown below.

Page 37: img sql

Here are some snippets of relevant code for this application:

Private Sub UploadFile_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles UploadFile.Click'' Gets the file to be uploaded'Dim ofd As OpenFileDialog = New OpenFileDialog()ofd.ShowDialog()If ofd.FileName="" OrElse (Not File.Exists(ofd.FileName)) Then'' If the requested file is not ok...'ReturnEnd IfDim up As TransferPictures = New TransferPictures()Dim id As Long =up.UploadFile(ofd.FileName)Dim msg As String=NothingIf id >0 Thenmsg = "Upload succesful"LoadInformationFromDataBase()Elsemsg = "An error has occured"End IfMessageBox.Show(msg)End Sub

''' <summary>''' Gets from the server a list of uploaded files.''' </summary>

Page 38: img sql

Private Sub LoadInformationFromDataBase()Dim up As TransferPictures = New TransferPictures()up.GetUploadedFiles(ds,"Pictures")UploadedFiles.DataSource = ds.Tables("Pictures")UploadedFiles.DisplayMember = "Name"End Sub

Private Sub frmMain_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.LoadLoadInformationFromDataBase()End Sub

Private Sub UploadedFiles_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles UploadedFiles.DoubleClick'' Downloads the selected file and displays it in the picture box.''' Finds the unique id of the file.'Dim drv As DataRowView = CType(UploadedFiles.SelectedItem, DataRowView)Dim selectedText As String = drv.Row("Name").ToString()Dim id As Long=-1'' the id is stored in text. The structure is: id - FileName.'id = Long.Parse(selectedText.Substring(0,selectedText.IndexOf(" - ",0)).Trim())Dim filename As String=NothingDim up As TransferPictures = New TransferPictures()Dim result As Byte() = up.DownloadFile(id,filename)up = NothingTry'' We cannot assign a byte array directly to an image. ' We use MemoryStream, an object that creates a file in memory' and than we pass this to create the image object.'Dim ms As MemoryStream = New MemoryStream(result, 0, result.Length)Dim im As Image = Image.FromStream(ms)Picture.Image = imCatch ee As ExceptionMessageBox.Show("An error has occured.\n" + ee.Message)End TryEnd Sub

Conclusion

Well, choosing which type of image - file - storage technique is up to the person designing a specific application. I have tried here to show you how you can store them in a database.

Happy Coding!

Bibliography

1. Books Online

Page 39: img sql

2. MSDN

NOTE: THIS ARTICLE IS CONVERTED FROM C# TO VB.NET USING A CONVERSION TOOL. ORIGINAL ARTICLE CAN BE FOUND ON C# CORNER (WWW.C-SHARPCORNER.COM).

Store or Save images in SQL ServerBy Shabdar Ghata | 5 Mar 2010 .NET2.0 Win2K WinXP Win2003 Vista SQL2000 SQL2005 VS2005 C#1.0 C#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

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 45Sponsored Links

Download source code - 235.22 KB Download latest version of source code (external link)

Introduction

/w EPDwUKMTAy

Page 40: img sql

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

Page 41: img sql

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:

Collapseprivate 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);

Page 42: img sql

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

Collapsevoid 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)

Page 43: img sql

{ 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.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 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.

Page 44: img sql

Requirements

Visual Studio .NET 2005 .NET Framework 2.0 Microsoft SQL Server 2000 database or Microsoft SQL Server 2005 database