Create new account I forgot my password    

Save and Retrieve Images from the Database using ASP.NET 2.0 and ASP.NET 3.5
Rating: 126 user(s) have rated this article Average rating: 4.6
Posted by: Suprotim Agarwal, on 3/21/2008, in category "ASP.NET 2.0 & 3.5"
Views: this article has been read 91495 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.
The source code of this article, both in C# and VB.NET, can be downloaded from here.
I hope this article was useful and I thank you for viewing it.







Follow me on twitter

Page copy protected against web site content infringement by Copyscape


How would you rate this article?

User Feedback
Comment posted by jeba on Saturday, March 29, 2008 6:47 AM
hi, thanks for this article..it gives relief from great headache.. but i want to retrive image from database(sqlserver2000) with using Handler file.. if possible please send to my mail id..thanks in advance
Comment posted by Brijesh on Thursday, April 03, 2008 2:31 AM
Its very  effective and helpful  
Comment posted by Rathi on Thursday, April 03, 2008 4:45 AM
hai

i have used this code ,image is saved but it is not retrirvr,hanler page error declred ,Error: Input string was not in a correct format.

what can i do,give me the solution
Comment posted by subrat kumar bhoi on Friday, April 04, 2008 8:02 AM
its really very fine
Comment posted by sathya on Monday, April 07, 2008 7:20 AM
hi,

i used this code,but image can't be retrive,what to do?i facing handler page;why ur declare empno as int32;pl explain it because now i am facing this line
Comment posted by abrar hussain ansari on Tuesday, April 08, 2008 3:20 AM
Acually Iam unable to understand that how will be access database becouse of in access there is no stored procedure ,in this coding  CREATE DATABASE [Employee]
GO
USE [Employee], what 's mean in this code plz describe in easily.
GO
Comment posted by Suprotim Agarwal on Tuesday, April 08, 2008 1:34 PM
Rathi..Did you download the code and try it out.

Sathya..Empid are usually stored as int or bigint in the database. Hence i use int32 for int and int64 if i want to target a bigint.

Abrar..this example does not target Access database. It works well on Sql 2005.
Comment posted by Radhey Shyam on Thursday, April 10, 2008 2:36 AM
This is very useful.
Comment posted by murali on Sunday, April 13, 2008 6:38 AM
there is no error while exting but no image is dispaying in image control wat to do???

plz....
give me solution  ..

to my  mail or here



Comment posted by Joshua on Monday, April 14, 2008 4:12 AM
This article saved me from hours and hours of google searching and trial and error. I've been trying to manipulate the size of the image so I'm not filling my DB up as fast, also I've been trying to get a thumbnail version working properly. I'm using C# if you have any suggestions I would be grateful. Thanks

Josh
Comment posted by Suprotim Agarwal on Monday, April 14, 2008 9:59 AM
Murali..Did you download the code given along with this article and try out the sample.

Joshua..To create thumbnails, there is an article on dotnetcurry over here http://www.dotnetcurry.com/ShowArticle.aspx?ID=140
Comment posted by Maulik on Wednesday, April 16, 2008 5:17 AM
image
Comment posted by Pankaj on Thursday, April 17, 2008 4:50 PM
hi, thanks a lot for code help. really great it is.  if possible please let us know your latest updates in feature.

thanks once again.
Comment posted by Igor on Monday, April 21, 2008 5:59 PM
I'm trying to solve this problem , but without succes.Every time when debugging i get message as with ...=new Bitmap(Stream str); that it has a wrong parameter...
I don't say I'm experienced and this is part of my school project , and it drives me crazy.. but still no photo's Iused your code and especially that method that returns Stream instead of MemoryStream i used earlier and still the same message and off course no photos.If anything here rings a bell , please write a note to me...
Thanks..
Comment posted by Suprotim Agarwal on Tuesday, April 22, 2008 11:29 AM
Igor : Did you download the source code and try that out?
Comment posted by om prakash on Wednesday, April 30, 2008 8:27 AM
i had stored image in database but i unable to display image on his web page (default.aspx)using Generic Handler errore show (ExecuteScalar: Connection property has not been initialized.) kindly help me
Comment posted by soma on Sunday, May 04, 2008 6:35 AM
thx for such areal great explnation it was very useful for me , it is first time i right acomment in any code i used thx agien
Comment posted by santosh on Tuesday, May 06, 2008 6:18 AM
its good it helped me a lot .its simply superb.
Comment posted by khuram on Thursday, May 08, 2008 9:45 AM
send me the code to save the data in database
Comment posted by Doog on Friday, May 09, 2008 1:38 PM
Hi:
This is a great article and thanks for supplying both VB and C# in the example.
I have one request for a follow up article:
How about doing everything the same but showing us how to use Stored Procedures and the Parameters needed for them.
That would be much appreciated.
Comment posted by Suprotim Agarwal on Friday, May 09, 2008 2:31 PM
Om Prakash, khuram: The code has been attached with the article. Please d/l it and let me know if you still face issues.
Doog: I will try to put up some code over the weekend, although it's not much. You have to set the cmd.CommandType to StoredProcedure and the string sql will have the stored procedure name. One or more additional lines of code here and there and you are done :) Try it out and let me know if you face any issues
Comment posted by GSpY on Friday, May 09, 2008 2:53 PM
Hi there.
Very good article. Very useful.
Just a question: as it concerns the caching of the browser. Is this the same behavior like the normal image files? E.g. if browser downloads an image once, then this image is cached and if requested again then it is loaded form cache from the client machine? With this approach, if you don’t use explicit caching in the page/config/..e.tc. then the image is downloaded again?
My point is, do you think this is an efficient way to handle images for e.g. an Image Gallery section (where you have a lot and big images?) Or you think it is efficient only for specific needs? (like your example where clients upload small photos for their e.g. profile)?
Thanks in advanced; I hope you understand my considerations.
Keep up the good work.
Comment posted by GSpY on Friday, May 09, 2008 2:55 PM
Hi there.
Very good article. Very useful.
Just a question: as it concerns the caching of the browser. Is this the same behavior like the normal image files? E.g. if browser downloads an image once, then this image is cached and if requested again then it is loaded form cache from the client machine? With this approach, if you don’t use explicit caching in the page/config/..e.tc. then the image is downloaded again?
My point is, do you think this is an efficient way to handle images for e.g. an Image Gallery section (where you have a lot and big images?) Or you think it is efficient only for specific needs? (like your example where clients upload small photos for their e.g. profile)?
Thanks in advanced; I hope you understand my considerations.
Keep up the good work.
Comment posted by Serg Aprelov on Friday, May 09, 2008 5:07 PM
I prefer to use saving images in Cache. It reduce SQL connections count.
Comment posted by imran on Saturday, May 10, 2008 12:51 AM
Very informative article. i never save images into database and now i decide to do this.

Regards
http://dotnetclassic.com
Comment posted by satalaj on Saturday, May 10, 2008 1:06 PM
very good article. Can you uncomment

//context.Response.BinaryWrite(buffer);  ?

Satalaj
Comment posted by ash on Saturday, May 10, 2008 9:42 PM
Very good article. Simple and to the point. Thanks
Comment posted by Todd on Monday, May 12, 2008 1:41 AM
Very nice.

One question, I'm getting duplicate records each time I submit a record.  Any ideas on where to look for what may be the cause?

Thanks!  and good work!
Comment posted by Martin on Monday, May 12, 2008 3:01 AM
Thanks for your article, it was a real help and is much appreciated. Writing with simplicity its and art, your article was easy to follow
Comment posted by Suprotim Agarwal on Monday, May 12, 2008 12:26 PM
Thanks everyone for their comments.

GSpY: This example would suit small images. However it can be clubbed with caching in between. I would go in for caching when the images are large as you mentioned/ or the number of images to be displayed are many. Here we are ok since we are adding and displaying one image at a time.

Satalaj: I will test the sample again before uncommenting

Todd: Put a breakpoint and test if the image is getting submitted twice. Check the database for entries. Also make sure the ShowEmpImage() is not getting called twice.

Comment posted by Michael on Wednesday, May 14, 2008 8:51 AM
Great article.  Just one comment to make you create the database using SSMS.  Yet you use a deprecated data type of image.  Changing the data type to varbinary(max) for future proofing in the short term.  Would this have any affect on the rest of the code?
Comment posted by Suprotim Agarwal on Wednesday, May 14, 2008 12:05 PM
Michael..That's a good idea. Will need to check that out and see if there are any code changes!!
Comment posted by Stilgar on Wednesday, May 14, 2008 2:25 PM
some parts look too complicated
I may be wrong but...
1) why cast FileUpload to FileUpload?
FileUpload img = (FileUpload)imgUpload;
2) why use so complicated methods to get the byte array can't you just use
imgUpload.FileBytes
3) Why use stream + loop + buffer to write to the response when you canjust write the original byte array to the response?
Comment posted by Keijo on Thursday, May 15, 2008 5:51 AM
Oh. My. God.

The author should go back to really learn this stuff before posting such collections WTF code.
Comment posted by MLMRescuer on Thursday, May 15, 2008 8:41 PM
Solution works great except the VB code is wrong you either have to remove the "Handles btnSubmit.Click" from the btnSubmit Sub or you have to remove the onclick="btnSubmit_Click" from the asp code

If you don't then it stores the file in the DB the first time, but then the FileUploader clears and the blank file is then put into the DB

I hope this helps...
This one had me stumped for a while.
Comment posted by Seenu on Friday, May 16, 2008 6:33 AM
This article helped me a lot. But i want to know which oen is better to store and retreive images, Using SQL Server or is there any other way...
Comment posted by Talib_dotnet on Sunday, May 18, 2008 9:29 AM
Pretty nice article. Please keep  up  the  good  work..
Comment posted by manzoor on Tuesday, May 20, 2008 7:52 AM
This code is to upload and download attachments of muliple type files

If rdUploadFile.UploadedFiles.Count > 0 And dbupdate = True Then
                    Dim breader As System.IO.BinaryReader = Nothing
                    For i As Integer = 0 To rdUploadFile.UploadedFiles.Count - 1
                        breader = New System.IO.BinaryReader(rdUploadFile.UploadedFiles(i).InputStream)
                        dbupdate = oReply.AddAttachment(ReplyId, rdUploadFile.UploadedFiles(i).GetName, breader.ReadBytes(rdUploadFile.UploadedFiles(i).InputStream.Length))
                        breader.Close()
                        breader = Nothing
                        If dbupdate = False Then Exit For
                    Next
                End If




Dim lblFileName As String = Request.QueryString("file")
            Dim Id As Long = Val(Request.QueryString("rid"))
            Try
                Dim oReply As New clsReplyActivity(oConnection)
                Dim bfile As Byte() = Nothing
                If oConnection.SqlConnection_Connect = True Then
                    bfile = oReply.GetReplyAttachment(Id)
                    oConnection.SqlConnection_Disconnect()
                End If
                If Not bfile Is Nothing Then
                    Response.Clear()
                    Response.ClearHeaders()
                    Response.AddHeader("Content-Disposition", "attachment;filename=""" + lblFileName + """")
                    Response.AddHeader("Content-Length", bfile.Length.ToString())
                    Response.ContentType = "application/octet-stream"
                    Response.BinaryWrite(bfile)
                    Response.End()
                End If
                bfile = Nothing
            Catch ex As Exception
                'Response.Write(ex.Message)
            End Try
Comment posted by Carlos Willian on Tuesday, May 20, 2008 9:42 AM
Congratulations

This code is very good.

Comment posted by paul p on Tuesday, May 20, 2008 10:00 AM
This really helped. I'm a newbie but would like to know a few things more.
1. Why use httphandler?
2. Someone said why use stream + loop + buffer. Is this for large files? I used this instead:

//set the content type
        context.Response.ContentType = "image/jpeg";

        //get the image content
        byte[] imageContent = GetImage(sToolGUID, lGrid);
        context.Response.BinaryWrite(imageContent);
    }
    public byte[] GetImage(string sToolGUID, int lGrid)
    {
        try
        {
            using (SqlConnection connection = ConnectionManager.GetConnection())
            {
                using (SqlCommand command = new SqlCommand("select simagedata from strgrid where stoolguid = @stoolguid and lgrid = @lgrid", connection))
                {
                    command.Parameters.Add(new SqlParameter("stoolguid", SqlDbType.NVarChar, 50)).Value = sToolGUID;
                    command.Parameters.Add(new SqlParameter("lgrid", SqlDbType.Int)).Value = lGrid;

                    connection.Open();
                    byte[] img = (byte[])command.ExecuteScalar();
                    connection.Close();
                    return img;  
                }
            }
        }
        catch (Exception ex)
        {
            Logger.LogException(ex);
            throw;
        }
Comment posted by venky on Tuesday, May 27, 2008 8:30 AM
Hi
A lot of thanks to u.
It very very useful
Comment posted by soujanya on Sunday, June 01, 2008 8:13 AM
Wonderful!!!...
Comment posted by Bilal Haider on Wednesday, June 04, 2008 1:43 AM
Great Articles.
After searching the google for hours, reading articles and implementing code i was unable to do this.
Someone said "uthor should go back to really learn this stuff before posting such collections WTF code." and " Why use stream + loop + buffer to write to the response...."I think this code is written for understanding. Author did not focus on Code Optimization, thats no problem.
Great job done.
How can we bind the Images to a gridview or details view as datafield property doesnot work for the image column.
Comment posted by Christian Harris I. Septimo on Tuesday, June 10, 2008 3:41 AM
Hi, I was wondering how can i retrieve multiple images from the database and display it in my web page like a gallery?
Comment posted by Nitin khadloya on Wednesday, June 11, 2008 1:55 AM
#region By Nitin Khadloya
        Directory.SetCurrentDirectory(Server.MapPath("~\\Image\\"));
        cn.Open();
        sDa = new SqlDataAdapter("select Image_id,Image_Path from ImageGallery where Image_id='3'", cn);
        sCmdB = new SqlCommandBuilder(sDa);
        ds = new DataSet();
        sDa.Fill(ds, "img");      
        grpImage.DataSource = ds.Tables["img"];
        grpImage.DataBind();
        cn.Close();
#endregion
Comment posted by Ravi lad on Wednesday, June 11, 2008 1:58 AM
Very nice Articles Nitin.this article is very helpful for me
Thanks a lot
Comment posted by Carlos Willian on Wednesday, June 11, 2008 2:09 AM
good article nitin
Comment posted by praveen on Wednesday, June 11, 2008 7:11 AM
i need to store the content of image  under varbinary(max) column from sql server 2005,into a file at my application deploy server. can any body know this.thanks in advance.
Comment posted by Suprotim Agarwal on Tuesday, June 17, 2008 1:07 PM
Nitin: Thanks for the code snippet
Praveen: SqlDbType.VarBinary is mapped to a byte array. So you need to pass a byte array as the value of a parameter that takes varbinary.
Comment posted by durai on Wednesday, June 18, 2008 7:18 PM
I am using the same code.. but it wont show any image in image control.. Anybody know the solution...plz reply
Comment posted by Ashish on Thursday, June 19, 2008 1:23 AM
Hi all

I m getting a exception upon storing a Image into a database , i will mention the exception below and the line where is get the exception.

The line where is get the exception is =>
string conn = ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString;

And the Exception is =>Object reference not set to the instance of an object

Please tell me how can i remove this exception

hope u reply me soon
Thanks in advance  
Comment posted by Suprotim Agarwal on Thursday, June 19, 2008 10:14 AM
durai: Did you download the code attached with this article. Also make sure that the connection has been established to the db and that there are images in the db.

Ashish: It looks like there is some problem with the connection string. Double check your web.config and see if you have the connection string correct. Download the code attached with this article and see how it is declared over there.
Comment posted by priya on Friday, July 04, 2008 4:45 AM
the code helped us thanx but i wanted to display the image from the database when i click some other button whereas you have given both insert & retrieve image on same button pls help....i need it
Comment posted by carlos willim on Friday, July 04, 2008 8:59 AM
very nice article Nitin
Comment posted by Rakesh Kumar on Tuesday, July 15, 2008 6:11 AM
Realy this is very superb article and logical too. It is easily understandable also. Also updates new features like multiple file uploading. check for duplicate value and upload only image files etc.
Comment posted by Nirav on Friday, July 25, 2008 10:47 AM
Hey Your code is just fantastic n useful too.
But i hd some trouble with it,as i hd alredy stored image in byte[] in one database,now i want to retrive it nd store it in datatable n then store it in another db in same form as former.could you please help me
Comment posted by Suprotim Agarwal on Friday, July 25, 2008 1:14 PM
Thanks everyone for their comments!!

Nirav: You can use SqlParameter and keep the DbType.Binary. Set the value of the parameter to byte array.

Also explore the option of using varbinary instead of image.
Comment posted by Nirav on Saturday, July 26, 2008 3:25 AM
Suprotim:Thanks for reply.But m not getting solution.As i said i hd stored image ,also m able to retrive it and store it in datatable with column of datatype "byte[]".But now how to pass it as sqlparameter when receiving parameter in storedprocedure is of image type(which i think stores data in byte[]).Please show me d direction to follow.You can just have a bird eye to following.

Dim img As Object
img = (.Item(SQLParam.ParameterName))'its value from 1st db
Dim strm As Stream = New MemoryStream(CType(img, Byte()))
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
'parameter which i wud pass to db
SQLParam.Value = ???????'this is wht m not gettting
Comment posted by Nirav on Saturday, July 26, 2008 3:55 AM
Suprotim:Thanks for reply.But m not getting solution.As i said i hd stored image ,also m able to retrive it and store it in datatable with column of datatype "byte[]".But now how to pass it as sqlparameter when receiving parameter in storedprocedure is of image type(which i think stores data in byte[]).Please show me d direction to follow.You can just have a bird eye to following.

Dim img As Object
img = (.Item(SQLParam.ParameterName))'its value from 1st db
Dim strm As Stream = New MemoryStream(CType(img, Byte()))
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
'parameter which i wud pass to db
SQLParam.Value = ???????'this is wht m not gettting
Comment posted by Md. Atikul Haque on Sunday, July 27, 2008 4:54 AM
i'm impressed by the solution u provide. that's realy a total solution.thank u very much.

best of luck.
Comment posted by Nil on Monday, August 11, 2008 6:37 AM
I got this eeror  "Object reference not set to an instance of an object."
while exicuting above code in c#+asp.net

on part of coding

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

can you specify me how this code work
&
which conditions are specify here




Comment posted by Suprotim Agarwal on Tuesday, August 12, 2008 5:54 AM
Nirav: Are you still facing the error?

Nil: Did you download the source code attached with this article? Just run that and see if you still get errors.
Comment posted by Nirav on Wednesday, August 13, 2008 5:09 AM
HI Suprotim.
Yes I had downloded the code and i was facin some problems.
But I had got the solution other way.So no more probs.
Any ways thanks for helping me and spading your precious time for it.Thanks again.
Comment posted by abc on Wednesday, September 10, 2008 5:09 AM
I tested the sample code in my desktop and it worked fine. But as i uploaded the same coding for my website, i am unable to save the image to the table of the database located on a remote server provided by the hosting company.
Can you suggest me why this is happening.
Comment posted by Suprotim Agarwal on Wednesday, September 10, 2008 12:53 PM
abc: I hope you have appropriate permissions on the database. Do one thing, try executing a query outside the application and see if it success. You can use SSMS to do so.
Comment posted by Tom on Thursday, September 11, 2008 9:29 AM
Thx!!!!
A
Lot!!!
Comment posted by jeyasanthan on Friday, September 12, 2008 2:45 AM
thanks more useful
Comment posted by Dhananjay Kumar on Saturday, September 20, 2008 4:45 AM
Hey Its great article. I really used this . Thank you so much for such a desciptive article .
Comment posted by Madhu on Tuesday, September 30, 2008 3:21 PM
Very good code u given,Really i am very thankful to you.
do one thing can u write the code with store procedure.
if like this any updates please mail me.
Comment posted by Mutharasan on Thursday, October 23, 2008 1:31 AM
Hi every one,
   Please sent me the code any one to following qustion....

Upload Multiple images and save as database in ASP.NET 2.0 with C# code.

Please send me...
Comment posted by pilli chandra shekhar on Monday, October 27, 2008 7:12 AM
urs article is good but u have to show it pictorially so that it is easy to every body to fallow the article
Comment posted by Suprotim Agarwal on Wednesday, October 29, 2008 12:33 AM
pilli chandra: We will certainly do so. Thanks for your suggestion.
Comment posted by Senthil on Tuesday, November 25, 2008 12:36 AM
cool buddy... great work..im searching for this stuff for a couple of days n ur code is really simple and perfect...
Comment posted by sdfsd on Wednesday, November 26, 2008 6:13 AM
code is wrong
Comment posted by naveen on Monday, December 01, 2008 7:17 AM
Thanks A lot,Code is Good.Can u give me ur EmailID,if any doubts i will contact u,My Id is naveen.gopagani@gmail.com.
Thanks
Comment posted by Suprotim Agarwal on Tuesday, December 02, 2008 10:10 PM
naveen - You can use the Contact Page to contact me.
Comment posted by Jinu jose on Wednesday, December 03, 2008 11:07 PM
This is really helpfull.I can store and retrieve images very perfectly
Comment posted by Anier Seyer on Wednesday, December 17, 2008 5:41 AM
Hi Suprotim,

I used the VB code.  I was able to save the image, but wasn't able to retrieve and display it.  Are there changes on the original code you created to fix this?

Kindly reply asap.

I also need a code that will send this image as an attachment.
Comment posted by Anier Seyer on Wednesday, December 17, 2008 5:48 AM
Hi Suprotim,

I used the VB code.  I was able to save the image, but wasn't able to retrieve and display it.  Are there changes on the original code you created to fix this?

Kindly reply asap.

I also need a code that will send this image as an attachment.
Comment posted by Anier Seyer on Wednesday, December 17, 2008 6:08 AM
Hi Suprotim,

I used the VB code.  I was able to save the image, but wasn't able to retrieve and display it.  Are there changes on the original code you created to fix this?

Kindly reply asap.

I also need a code that will send this image as an attachment.
Comment posted by Rahul Sharma on Tuesday, December 23, 2008 9:22 AM
Hy this is Rahul
I Used this code Image is uploaded on server but,
Query String is not fired.
Comment posted by Rick on Thursday, December 25, 2008 11:24 PM
Greate job I've been looking for something like this for months
I found a couple of articals like this on at
http://dotnetcurry.com/ShowArticle.aspx?ID=175

allso I've been playing with the new image generation
tool take a look at my post on this forum and see if you can
fix the problem I'm having with it and maybe you could do an articale
http://forums.asp.net/t/1363105.aspx

i'm a novice learning along the way articales like this one are a big help I've allso used this code with varbinary I allso set the Image url in the Image tag on the aspx page
I'll keep an eye on this site for any other good stuff
Thanks keep up the good work
Comment posted by Suprotim Agarwal on Friday, December 26, 2008 8:59 PM
Anier, Rahul: Please download the source code attached with this article and try.

Rick: Thanks. Those comments are very encouraging.I will check up that link.
Comment posted by Sreenivas on Thursday, January 08, 2009 10:14 AM
Hi
  this one is really helpful? but i am getting some problem
A namespace does not directly contain members such as fields or methods   
pls give me replay.
Comment posted by E. vamsi on Saturday, January 10, 2009 1:39 AM
Hi,
   I have gone through all the steps and did as the same way.It was really helpful and worked out.I got the output.Thanq
Comment posted by Aashish Patidar on Saturday, January 24, 2009 2:52 AM
hi
This is relay a very good code.
can u give me the idea how to retrieve the image in DATAGRIDVIEW. if u have that coding plz mail me.
Comment posted by Divya Bhardwaj on Friday, January 30, 2009 11:58 AM
Hi,
Thank u so much.This coding is really helpful for storing a data/image in database.But I m unable retrieve an image through Grid View.Plz if know reply me as early as possible.
Comment posted by Divya Bhardwaj on Friday, January 30, 2009 12:30 PM
Hi,
Thank u so much.This coding is really helpful for storing a data/image in database.But I m unable retrieve an image through Grid View.Plz if know reply me as early as possible.
Comment posted by thomas ugah on Saturday, January 31, 2009 8:46 PM
the lblresult displays there was an error.pls do i need to create a new database with the name Employee so i can run the downloaded code.I need it urgent.
Comment posted by premkumar on Monday, February 09, 2009 8:34 AM
hi can you please explain to get thumbnail image in datagrid  
Comment posted by Suprotim Agarwal on Monday, February 09, 2009 9:10 PM
To retrieve images in a gridview, check this article
www.dotnetcurry.com/ShowArticle.aspx?ID=193
Comment posted by Thankyou on Tuesday, February 17, 2009 7:31 AM
Thank You Really much.. Really.. Thank you for your article.
I just don't know what to say except thank you. Thanks
Comment posted by Suprotim Agarwal on Wednesday, February 18, 2009 8:37 PM
Thankyou: Your thanks means most to us. Thanks for letting us know that you liked it so much!
Comment posted by Pavan Kumar on Tuesday, February 24, 2009 12:11 AM
Hi,
      Thank you: This artile is very useful for uploading and retriving images .
Comment posted by thefockerizer on Thursday, March 05, 2009 6:42 PM
Just a question, how would a the generic handler deal with cases where we have a user with more the one photo....like those in facebook or myspace?
Comment posted by Miraj on Friday, March 27, 2009 7:59 AM
Hi this is Miraj your Article is very useful it help a lot
thanks once again
Comment posted by Nguyen Hong Ky on Tuesday, April 07, 2009 4:28 AM
Can you help me to fix error:

Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:


Line 34:             lblResult.Text = "There was an error"
Line 35:         Finally
Line 36:             connection.Close()
Line 37:         End Try
Line 38:     End Sub


Comment posted by Dean Armstrong on Saturday, April 11, 2009 6:36 AM
Hi, I downloaded and run this code, and iam getting this mesage when i go to run it in the browser-
Exception Details: System.ArgumentException: No parameter specified

Source Error:


Line 16:             empno = Convert.ToInt32(context.Request.QueryString["id"]);
Line 17:        else
Line 18:             throw new ArgumentException("No parameter specified");
Line 19:
Line 20:        context.Response.ContentType

iam using Visual web dev, 2005 express, for a college project,
any help would be greatly appreciated..
Dean..
Comment posted by Nimol on Friday, April 24, 2009 6:14 AM
Hi guys,
I ard follow up your coding but it sill show error message "Object reference not set to an instance of an object."
---int byteSeq = strm.Read(buffer, 0, 4096);---//error place

Please Help!
Comment posted by Azhar KHan on Monday, May 04, 2009 6:51 AM
Hi, its very usefull code, but i have one question, if we dont use code behind for uploading the image then we can directly assign the imageUpload.FileBytes to Databse field using SqlDataSource? is this approach will be same the one you mentioned? beacuse i am able to retreive image in both ways. Plus you mentioned that you are storing Emply name and Image both in arrays wherewas you are storing only image, is it mistake in text or anyother thing? thanks , i appreciate sharing this usefull code. Thanks a Lot
Comment posted by Azhar Khan on Monday, May 04, 2009 6:53 AM
Nimol, you are getting this refrence error beacuse its not able to find any data in database, try to hardcode any id which exist in database and then run, it will work
Comment posted by Suprotim Agarwal on Tuesday, May 05, 2009 4:40 AM
Azhar: Using a handler helps as it gives you control over the image being displayed. For eg: You may add a watermark to the image before displaying it or add a copyright info. Check this article to understand what I mean

http://www.dotnetcurry.com/ShowArticle.aspx?ID=214

I have mentioned the following about storing image into an array :-

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.
Comment posted by Fábio Teixeira on Wednesday, May 27, 2009 12:02 PM
Hi, very nice work. I started working with .asp 1 month ago, and I'm currently doing a project for my school. What I have to change in the code for I select the image that I want. I have many in my d.b how can I select which one will appear in the image? thks
Comment posted by vanjikumaran on Monday, June 01, 2009 1:54 PM
hey buddy ... itzz really nice wrk :):)
Comment posted by vanjikumaran on Monday, June 01, 2009 1:56 PM
hey!!! Dean Armstrong

check ur database and data type of parameter
Comment posted by praveen verma on Saturday, June 06, 2009 1:40 AM
hai Sir,

i have used this code ,image is saved but it is not retrirvr,hanler page error declred ,Error: Input string was not in a correct format.

what can i do,give me the solution
Comment posted by MKM on Friday, July 03, 2009 2:08 AM
hello, this code is very useful, bt one problem in  this, image cannot display  . wht is the solution. i try many ways. i use image stream   that time it is working .pls gave me solution 4 that
Comment posted by Admin on Friday, July 03, 2009 8:43 PM
MKM: Are you trying it with the code available here? 'image cannot display' does not explain your problem too well.
Comment posted by NickJ on Monday, July 06, 2009 10:03 AM
Very handy snippet of code. It has saved me loads of messing around time. Thank you very much. I will be using it again and again.
Comment posted by sumitha on Thursday, July 30, 2009 4:03 AM
Hi, very nice work. I started working with .asp 1 month ago, and I'm currently doing a project for hrm. i save to more employees photos in my database i want to retrive the particular employee image to given the empid...plz i need coding
Comment posted by nitin on Sunday, August 02, 2009 5:15 AM
Hi sumitha, i unstand ur prblm.if u want plz mail me i hve solution this one
Comment posted by Nikhilesh Sorte on Wednesday, September 02, 2009 2:22 AM
Its a great article to refer for inserting and displaying image in active server pages......
thanks
Comment posted by Manoj Kumar on Monday, September 14, 2009 3:34 PM
Hi, This is very nice article.I sarting learn asp .net.I want to retrieve record of Employee as Name, Image, eid. How to display image and record from database.pls send me code. I need coding in c#........
Comment posted by Patrick on Tuesday, September 15, 2009 10:15 AM
can u provide code by uploading the file not int db, but in a remote server, since u r saving the image in the db, it can burst up the performance of your db
Comment posted by pradeep on Thursday, October 01, 2009 3:42 PM
Very Good Article
Comment posted by Richi on Saturday, October 03, 2009 12:36 AM
hi, This is very gud article  n i have solve my problem
thank you very much
Comment posted by SmsJunk.Com on Saturday, October 03, 2009 2:20 PM
Excellent Tutorial. Great Explanation . I usually search for codes in C# but every where it is given in vb.net .Here I am lucky to find the codes in C#.
Thanks a lot.
Comment posted by ling on Wednesday, November 04, 2009 10:11 AM
Hello, i am getting this error when using your code:
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:


Line 34:             lblResult.Text = "There was an error"
Line 35:         Finally
Line 36:             connection.Close()
Line 37:         End Try
Line 38:     End Sub

Please advice me on what to do, thank you
Comment posted by ling on Wednesday, November 04, 2009 10:25 AM
The above note can be ignored, i resolved it by changing the web.config file :P
Comment posted by LancyB on Tuesday, December 29, 2009 9:37 AM
Hi, after executing your code, the images are being saved in Database but I cannot retreive those images.

Also, I need to retreive multiple images in Datagrid/Grid View. I mean each row has one image (Clickable). Can you forward the codings.

Thanks.

LB
Comment posted by puneet on Wednesday, December 30, 2009 3:42 AM
Hii, I have used this code earlier and i hv a ques that hw can i display the image to a particular image control? hw can this will be binary write to an image box?plz answer my questions
Comment posted by Suprotim Agarwal on Friday, January 01, 2010 1:51 AM
LancyB: Did you download the source code and try the example given in it? That could help you identify issues in your code.

Puneet: Are you looking out for this?  http://www.asp.net/learn/data-access/tutorial-55-cs.aspx
Comment posted by sabah on Tuesday, January 05, 2010 4:27 AM
good work..but its not working
error at : context.Response.ContentType = "image/jpg";
Comment posted by sabah on Wednesday, January 06, 2010 1:39 AM
problem resolved code working fine but why not inserting in DB???:(
Comment posted by Sharam Akhzar on Friday, January 08, 2010 4:29 PM
I am getting error because of connection!! Dont we have to hace DataSet in this code. How do I link dBase to your code after creating dbase?
Thanks.
Comment posted by Elmer on Thursday, February 04, 2010 12:24 PM
This worked great. Thank you for sharing the information.

Post your comment
Name:
E-mail: (Will not be displayed)
Comment:
Insert Cancel