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

Posted by: Suprotim Agarwal , on 3/21/2008, in Category ASP.NET
Views: 431602
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.
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

Suprotim is the founder and primary contributor to DotNetCurry, DNC .NET Magazine, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls. and is authoring another one at The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal


Page copy protected against web site content infringement by Copyscape


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 3, 2008 2:31 AM
Its very  effective and helpful  
Comment posted by Rathi on Thursday, April 3, 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 4, 2008 8:02 AM
its really very fine
Comment posted by sathya on Monday, April 7, 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 8, 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 8, 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 4, 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 6, 2008 6:18 AM
its good it helped me a lot .its simply superb.
Comment posted by khuram on Thursday, May 8, 2008 9:45 AM
send me the code to save the data in database
Comment posted by Doog on Friday, May 9, 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 9, 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 9, 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 9, 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 9, 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 1, 2008 8:13 AM
Wonderful!!!...
Comment posted by Bilal Haider on Wednesday, June 4, 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 4, 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 4, 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 1, 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 2, 2008 10:10 PM
naveen - You can use the Contact Page to contact me.
Comment posted by Jinu jose on Wednesday, December 3, 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 8, 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 9, 2009 8:34 AM
hi can you please explain to get thumbnail image in datagrid  
Comment posted by Suprotim Agarwal on Monday, February 9, 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 5, 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 7, 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 4, 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 4, 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 5, 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 1, 2009 1:54 PM
hey buddy ... itzz really nice wrk :):)
Comment posted by vanjikumaran on Monday, June 1, 2009 1:56 PM
hey!!! Dean Armstrong

check ur database and data type of parameter
Comment posted by praveen verma on Saturday, June 6, 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 3, 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 3, 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 6, 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 2, 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 2, 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 1, 2009 3:42 PM
Very Good Article
Comment posted by Richi on Saturday, October 3, 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 3, 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 4, 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 4, 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 1, 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 5, 2010 4:27 AM
good work..but its not working
error at : context.Response.ContentType = "image/jpg";
Comment posted by sabah on Wednesday, January 6, 2010 1:39 AM
problem resolved code working fine but why not inserting in DB???:(
Comment posted by Sharam Akhzar on Friday, January 8, 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 4, 2010 12:24 PM
This worked great. Thank you for sharing the information.
Comment posted by ping on Sunday, February 14, 2010 6:08 AM
i follow the ShowImage.ashx to click the page and need to display in gridview, but when i run will display error of "Object reference not set to the instance of an object" in Dim line "byteSeq As Integer = strm.Read(buffer, 0, 4096)", i already do this in 2 day but still cant solve, can help me? after 1 week need testing this fyp system oledy!!
Comment posted by sharath Chandra on Thursday, February 18, 2010 2:12 AM
how to get the value of ID in context.Request.QueryString["id"] from .aspx.cs page to Handler,.ashx
Comment posted by Jake Blawch on Thursday, February 18, 2010 7:41 AM
I got it running! Thanks for the code.
Comment posted by raji on Sunday, February 21, 2010 12:35 AM
Thanku so much !!!
Comment posted by Felix on Tuesday, February 23, 2010 1:17 AM
Hi, very nice piece of code, but may some1 tell me what is 4096 in this case i saw its the number of bytes to be read from current stream, does it always has to be  (buffer, 0, 4096)???, may some1 pls clarify to me, siply becase i dont get to see the image but its there in the database
Comment posted by Felix on Tuesday, February 23, 2010 7:56 AM
Hey dont worry about responce I managed to show the image from the database it was a small mistake I did, there is nothing wrong with your code. Once again Thanks for the post
Comment posted by Jeet on Friday, March 19, 2010 4:51 AM
Hi,Actually i want  to save image in sql server2005 using C# on button click event and retrive the image on image tool using button2 click event. This code is use in web application.plz give me any solution.
thanks you..
Comment posted by ranu on Tuesday, April 20, 2010 3:48 PM
sir if we want to fetch images in datagrid with same code insteaded you used <asp:Image ID="Image1" style="width:200px" Runat="server" />

i used datagrid its error for Images1 does not exist in current contex in cs page .tell me where to change coe for this......
Comment posted by Hugo on Wednesday, April 21, 2010 4:53 AM
I LOVE YOU !!!!!!!!!!!!!!!!!!!!!!!!
THIS ROCKS !
Comment posted by mario on Thursday, April 22, 2010 12:52 PM
SUPER
Comment posted by evren YILDIRIM on Saturday, April 24, 2010 6:14 AM
thanks to you for example
Comment posted by Payal on Thursday, April 29, 2010 2:19 PM
the above article is very useful.I want to know is we insert the images or table in a dropdown list control? Whoch one is better to use cookies or session management? If we upload the image by a fileupload control then how we retrieve that image at the same time at the different places so it can easily displayed.
Kindly send me the answers of my questions in my mail id.
Thanx in advance
Comment posted by chandan kumar bensagar on Monday, May 3, 2010 12:42 AM
Thanks.................
the above article is very useful.
Comment posted by linlin on Wednesday, May 5, 2010 4:00 PM
after I click sumit button, i can't  see anydesign and no error line. kindly send me the solution. thanks
Comment posted by venkat on Monday, May 10, 2010 9:20 AM
code will be executed perfectly but unable to display the image ???
Comment posted by Saakshi on Monday, May 17, 2010 4:57 AM
Thank U Very Much.Ur Content helped me alot.
Comment posted by vimali on Saturday, May 22, 2010 2:30 AM
followed the code: the following error comes, can anyone says how to fix it, i'm a beginner in this.

--------------
Cannot view XML input using style sheet. Please correct the error and then click the Refresh button

Invalid at the top level of the document. Error processing resource 'http://localhost:2965/landparcel/sketch_show.aspx?parc...

System.Byte[]  ^

pls answer me , many days i tried , no soln... pl help anyone



Comment posted by Foo on Monday, June 7, 2010 2:54 AM
can anyone pls help me?
i have no error with the codes....
but when i upload an image...it will store two image in database (duplicated)
for example when i 1st upload,the ID is 1,but it will store 2 record...so now the database will have 2 record. i also don't know why the second record cannot display the image.
so to display,i need to put a -1 in the showimage.ashx page.

can anyone tell me why it will store 2 records in database for 1 uploaded image?
is there something to do with the IsIdentity in database?
Comment posted by Himanshu on Wednesday, June 16, 2010 1:05 PM
Thanks a lot for the code. I m really thankful to u!
Comment posted by Himanshu Sikka on Saturday, June 19, 2010 8:15 AM
Thanks for the code!
Comment posted by Shashank on Sunday, June 20, 2010 4:23 AM
Great code thanks
Comment posted by anny on Monday, June 28, 2010 6:44 AM
ur code...very nice...
but i wnt code abt retriving stored images from sql server and displaying in gridview...by using...datareader...plz.help.me..
Comment posted by Patrick on Monday, July 26, 2010 10:06 AM
Hi, I put the same code but don't show the image. In another article, the author at the end put 'context.Response.End()', but i get the error: Unable to cast object of type 'HandlerImage' to type 'System.Web.UI.Page'.

Someone can help me?

Tks
Comment posted by Patrick on Monday, July 26, 2010 10:19 AM
Hi, I put the same code but don't show the image. In another article, the author at the end put 'context.Response.End()', but i get the error: Unable to cast object of type 'HandlerImage' to type 'System.Web.UI.Page'.

Someone can help me?

Tks
Comment posted by milon on Thursday, August 19, 2010 9:37 AM
Hi, I put the same code but don't show the image. In another article, the author at the end put 'context.Response.End()', but i get the error: Unable to cast object of type 'HandlerImage' to type 'System.Web.UI.Page'.
Comment posted by robert on Friday, August 27, 2010 5:49 AM
hai ,I have yet to understand the parameter @ ID from where, because out error
Comment posted by Sam Anand on Wednesday, September 1, 2010 9:14 AM
super...article....very easy step by step procedure...Thank You so much.....
Comment posted by Ankita on Wednesday, September 8, 2010 6:56 AM
hey... the code is working perfectly for storing the image but for retriving it isnt... not getting error also..
could u please help me with it...????
i actually wanna display in gridview...
Comment posted by Suprotim Agarwal on Thursday, September 9, 2010 1:36 AM
Ankita: Did you try the example given in the source code?
Comment posted by Ganga on Tuesday, September 14, 2010 4:11 AM
its good...and easy...thanku..
Comment posted by Ntombi on Thursday, September 16, 2010 6:31 AM
i'm working on a VB.NET project. I have to send an email and sms. I have to save images to the databas and retrieve them to the image control pls help.
Comment posted by Navneet Saini on Monday, September 27, 2010 5:06 AM
The code given here is correct.
first you will have to create Default.aspx file paste the code from <html ... to </html>
after that you will have to create database connection and comfigure in web.config file with the name "EmployeeConnString" and create table "EmpDetails" as mentioned above i.e. id as int identiry, empname varchar(20) and empimg image.
after that create a Generic Handler file ShowImage.ashx and paste the code into it.
Create a textbox and button for "show image" and paste the code into its click event
as
Image1.ImageUrl = "~/ShowImage.ashx?id=" + id;
Now run the project
First browse the file from file upload and click submit button.
Now to see the image type image id number in the textbox click button to see the image.
Comment posted by Navneet Saini on Monday, September 27, 2010 5:11 AM
identiry is typed incorrect in the above comment which is identity. If the textbox name is  txtId then id should be txtId.Text for C# code. like
Image1.ImageUrl = "~/ShowImage.ashx?id="+txtId.Text;
Comment posted by Rakesh Kumar Sandhibigraha on Monday, October 11, 2010 7:09 AM
thank u somuch for this article..
again agin thank u............so....
Comment posted by chintu on Wednesday, November 24, 2010 5:39 AM
This is a good code for save the image in data base and display on the web page but we can not select the multiple image and not show the multiple image on the web form
if you have any code for  select the multiple image and show on the web page the send me on my email id
Comment posted by saad on Monday, November 29, 2010 1:42 AM
Excellent article and wonderful
But I had problems with the connection to the database

How to communicate with the database
Comment posted by somil on Tuesday, December 28, 2010 11:28 PM
it's really helpful...thanx a lot
Comment posted by somil on Thursday, January 6, 2011 1:34 AM
its not working.pls help me....
Comment posted by hareram kumar on Saturday, January 29, 2011 6:01 AM
your coding is excellent and solved my  problems thanks
Comment posted by krupal Reddy on Wednesday, February 2, 2011 12:13 AM
it's reallu helpfull....thanks a lot
for single image per page it is working fine,but if i want to retrieve multiple images per single ,please suggest me the changes.....
Comment posted by krupal Reddy on Wednesday, February 2, 2011 12:17 AM
it's reallu helpfull....thanks a lot
for single image per page it is working fine,but if i want to retrieve multiple images per single ,please suggest me the changes.....
Comment posted by krupal Reddy on Wednesday, February 2, 2011 12:17 AM
it's reallu helpfull....thanks a lot
for single image per page it is working fine,but if i want to retrieve multiple images per single ,please suggest me the changes.....
Comment posted by krupal Reddy on Wednesday, February 2, 2011 12:18 AM
it's reallu helpfull....thanks a lot
for single image per page it is working fine,but if i want to retrieve multiple images per single ,please suggest me the changes.....
Comment posted by krupal Reddy on Wednesday, February 2, 2011 12:18 AM
it's reallu helpfull....thanks a lot
for single image per page it is working fine,but if i want to retrieve multiple images per single ,please suggest me the changes.....
Comment posted by somil on Saturday, February 26, 2011 12:57 AM
i m not getting multiple images at a time...pls help
Comment posted by SYSTEN on Saturday, February 26, 2011 1:21 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 sunil kumar on Sunday, March 6, 2011 10:29 AM
excellent job. thanks a lot. it really works .
Comment posted by JAMES on Tuesday, March 8, 2011 12:24 AM
Great. It works. I need to know that how is the code generally for linking picture from list of gridview datas. Hope you check and mail me soon. Thank you.
Comment posted by JAMES on Tuesday, March 8, 2011 12:27 AM
omshresthas@gmail.com
Comment posted by amer on Wednesday, March 9, 2011 2:13 AM
hi 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 hari on Wednesday, March 9, 2011 11:10 AM
nice.........
Comment posted by Coert Dorrepaal on Wednesday, March 16, 2011 9:51 AM
So easy to use and thanks for sharing, u saved me a whole lot of time!!!!!!!!!!
Comment posted by martini on Sunday, March 27, 2011 8:40 AM
molto bello
Comment posted by Mounika on Tuesday, March 29, 2011 12:17 AM
hai can someone help me sending group sms by picking the data from database.i want d code of dat
Comment posted by Carla on Friday, April 1, 2011 10:52 AM
hi, when i trying to use more than one parameter i get the error:  "Object reference not set to an instance of an object."

@ This line : "Dim byteSeq As Integer = strm.Read(buffer, 0, 4096)"

btw...it added to the database just fine. I saw in one these comments about changing the webconfig?...how would i do that? am i missing sumthing?
I would appreciate any help. Thanx
Comment posted by Carla on Friday, April 1, 2011 11:09 AM
after further investigation, it seems this line :" Dim img As Object = cmd.ExecuteScalar()" is returning NOTHING.
I checked my db and the bytes are there....unsure about wat to do to fix this.
Comment posted by Suprotim Agarwal on Saturday, April 2, 2011 6:26 AM
Carla: Did you try the source code attached with this article. There are no changes required. Should work without any changes
Comment posted by aida on Sunday, April 3, 2011 7:27 AM
great work! i have a table in sqlserver 2008 with field name C_Image with datatype image. i am working in vs2008. i am new to .net .  please explain what does id stands for in code:if (context.Request.QueryString["id"] != null)
            empno = Convert.ToInt32(context.Request.QueryString["id"]);.  
Also what does ID stands for in code:string sql = "SELECT photo FROM Employees WHERE EmployeeID = @ID";
        SqlCommand cmd = new SqlCommand(sql, connection);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@ID", empno);
Since i am using field C_ID for the condition  so shouldn't it be "SELECT C_Image FROM Category WHERE C_ID=@C_ID";
Please help me out..... :(
Comment posted by aida on Sunday, April 3, 2011 11:25 AM
I also want to add collapsible panels in the accordion pane dynamically . I have a product table where i want to display the product category in accordion and display all the sub category in collapsible panels.please help...
Comment posted by Shewink on Tuesday, April 5, 2011 1:49 AM
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
-----------------------------------------------------

Solution:  string conn = System.Configuration.ConfigurationManager.AppSettings["EmployeeConnString"];

Webconfig:
<configuration>
   <appSettings>
      <add key="EmployeeConnString" value="server = servername;uid=user;pwd=sa;database=Employee;"/>
   </appSettings>
   <connectionStrings/>
   <system.web>
Comment posted by Shewink on Tuesday, April 5, 2011 2:00 AM
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
-----------------------------------------------------

Solution:  string conn = System.Configuration.ConfigurationManager.AppSettings["EmployeeConnString"];

Webconfig:
<configuration>
   <appSettings>
      <add key="EmployeeConnString" value="server = servername;uid=user;pwd=sa;database=Employee;"/>
   </appSettings>
   <connectionStrings/>
   <system.web>
Comment posted by Antony on Tuesday, April 5, 2011 4:13 PM
Its very nice article. Its very helpful.Thanks authour.
Comment posted by Neha Pateriya on Saturday, April 9, 2011 10:25 PM
hey i'm getting this error can u pls help me..i'm using visual web developer2008

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.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 = "image/jpeg";
Comment posted by Neha Pateriya on Saturday, April 9, 2011 10:54 PM
plz help..i'v checked my database as well.empid is int identity,empname varchar(50)and empimg image.
Comment posted by J on Monday, April 18, 2011 9:22 AM
I have tried the source code and it all runs fine and inserts into the database. However i am unable to see the image.
Comment posted by J on Tuesday, April 19, 2011 4:01 AM
I have tried the source code and it all runs fine and inserts into the database. However i am unable to see the image.
Comment posted by Emad on Monday, May 30, 2011 5:45 AM
Every think Fine, but when i try last step (Image1.ImageUrl = "~/ShowImage.ashx?id=" & id)
the image is not showing
I am use "update" method insteade of "insert" and i remove the @@IDENTITY
From "INSERT INTO EmpDetails(empname,empimg) VALUES(@enm, @eimg) SELECT @@IDENTITY"
is that effect! and what the use of "@@IDENTITY" anywhy
Comment posted by Jegadeeshwaran on Wednesday, June 1, 2011 5:12 AM
Thanks a lot... Its working charm
Comment posted by Vipin on Saturday, July 9, 2011 2:12 PM
Thanks
Comment posted by Eiad on Monday, July 11, 2011 5:40 AM
Hi
The code works fine. But I want to display according to name listed in DDL. So how do I call and select image regarding name in DDl?
Thanks
Comment posted by Ramesh kumar on Tuesday, July 12, 2011 1:47 AM
Hi
thanks a lot?
this code is very helpful.
Comment posted by Thanda on Sunday, August 14, 2011 2:24 AM
Friend,I do as your code but it show me an error at this place, "int id = Convert.ToInt32(cmd.ExecuteScalar());" and point out the error message there from handler "object img = cmd.ExecuteScalar();".Please tell me, why it is like that.Thanks for all.

Comment posted by venu on Wednesday, September 14, 2011 7:08 AM
Image is not uploading to database.....plz...send the code.....

Comment posted by maria sathiyaraj on Wednesday, September 28, 2011 12:08 AM
hi thanks very very good.
Comment posted by noah sibanda on Monday, October 3, 2011 9:50 AM
i just need money for fees @university
Comment posted by Piyush mishra on Monday, October 24, 2011 8:57 AM
the code is the one of the coolest code i have seen in the life
Comment posted by Bijay Baniya on Tuesday, October 25, 2011 3:08 AM
Thanks a lot for this Code. It helped me a lot!!!
Comment posted by ashok on Thursday, October 27, 2011 2:55 AM
hi thanks for helping us . I have a problem with displaying images in asp.net while I run pages no images displayed please help me .
thanks
Comment posted by Munish Singla on Tuesday, November 8, 2011 2:31 AM
Thank you. It really works.

Regards
Comment posted by Pramodh on Sunday, November 20, 2011 9:30 AM
Excellent work
Comment posted by Pramodh on Sunday, November 20, 2011 9:30 AM
Excellent work
Comment posted by charlie on Tuesday, November 22, 2011 2:50 PM
thanks :o) you explained it very well. keep walking... ;)
Comment posted by MANISH KUMAR on Thursday, December 1, 2011 10:25 AM
I do not understand where we have to write the code of 5th step of "Save and Retrieve Images from the Database using ASP.NET 2.0 and ASP.NET 3.5". So please help me as soon as possible.......

Comment posted by Vinoth on Wednesday, December 7, 2011 5:28 AM
hi this is very useful for me.... but the code is failed to display tiff format images...  can u guide me what changes need to taken in the code to display tiff format images.....
Comment posted by Reynaldo G. Ocumen on Tuesday, January 3, 2012 9:23 PM
Thank you very much Mr. Author.

Excellect 10 Stars for you.
Comment posted by ambika on Sunday, January 8, 2012 11:48 PM
hi, really its very good, but Please tell me that how can i display the same image in popup window.
Thank u
Comment posted by Thank you on Wednesday, January 18, 2012 5:08 AM
It does not work at all and gives error in "Connection.close" statement please modify the same.
Comment posted by Abisha on Wednesday, January 18, 2012 8:36 PM
It's  useful for all and very effective and helpful.Thanks a lot
Comment posted by Atul Rungta on Friday, January 20, 2012 2:12 AM
Thanks a Lot....
Your code helped Me a Lot.
Keep Posting :-)
Comment posted by s.jeyan on Wednesday, February 29, 2012 11:29 AM
i need to set password while downloading image from gmail within two days can suggest please
Comment posted by zakir on Wednesday, February 29, 2012 11:59 AM
gr8 post.. saved 8 hours :)
Comment posted by yin on Saturday, March 10, 2012 2:01 AM
Object reference not set to an instance of an object.  Error may be at your select query you select all such as *. You edit with select only image field
Comment posted by Chaitanya on Thursday, March 15, 2012 6:40 AM
Thanks a lot..
Code working fine for me.
Comment posted by Ajitabh Mahalkari on Friday, March 23, 2012 2:35 PM
Thanxx for the post dude !! its working for me...I wanted to get rid of this image retrieval task.
Comment posted by sachin on Thursday, April 5, 2012 7:11 AM
Cuold me pls tel me how to retieve the image on a selection of a value from the drop down binded to the database
Comment posted by amr ghanem on Tuesday, April 10, 2012 5:48 AM
so what if i want to save the picture from picture box not from fileuploder control
!!
Comment posted by Gbenga on Friday, May 4, 2012 8:18 PM
Thanks for this very helpful article. I was just thinking  is there a possibility of passing the image bytes to the file handler directly instead of retrieving it from the database inside the file handler class?
Comment posted by Manoj Maurya on Friday, May 11, 2012 12:10 AM
Thanks it's very useful.
Comment posted by faizan ameen on Friday, May 18, 2012 7:12 AM
awsome work helped me a lot i really appreciate your work keep it up.my problem solved thx again
Comment posted by ochaya gerald on Wednesday, May 23, 2012 5:06 AM
i created an SQL database with the aim of uploading image from computer so that when i click the insert button the image will be in the database but i couldn't find it in the database.
how can i make it ?
Comment posted by yash on Friday, June 29, 2012 2:29 PM
Gud..
Appriciated
Comment posted by Abdullah on Wednesday, July 11, 2012 8:08 AM
Very helpfull article.
may i know that how can i show more than one image from this embdetail table?
Comment posted by ankit on Wednesday, July 25, 2012 1:28 AM
excellent article i have used it in my website
Comment posted by dhiraj on Wednesday, July 25, 2012 2:43 AM
int id = Convert.ToInt32(cmd.ExecuteScalar());
nos not store in id type converstion problem or any other pls help
Comment posted by selva on Wednesday, August 8, 2012 7:06 AM
Hello sir, it help me more! but i have one error! like thrown exception in

///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";///

i got exception like "No parameter specified" . plz help me! thank advance.
Comment posted by singaraj on Wednesday, August 8, 2012 7:06 AM
Hello sir, it help me more! but i have one error! like thrown exception in

///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";///

i got exception like "No parameter specified" . plz help me! thank advance.
Comment posted by Mohammed Essa on Thursday, August 16, 2012 12:58 AM
Thanks a lot, this is a great article and it helped me a lot
Comment posted by adawngi on Friday, September 7, 2012 10:11 AM
Thanks for the code. i can save my image in sql database. but while displaying, the image is displayed but not from the database. but from some other folder. please anyone can you tell me the reason.
Comment posted by Archana on Sunday, September 9, 2012 8:56 PM
Thanks soo much your solution worked like a charm. its Perfect!
Comment posted by stephane on Tuesday, September 18, 2012 9:08 AM
Very very usefull article, simple and complete.

Thank you!
Comment posted by Eng. Ahmed on Monday, October 29, 2012 12:02 PM
Thanks a lot very useful.
Comment posted by Ratin on Monday, December 24, 2012 7:49 AM
Very useful article, thanks a lot.
Comment posted by sdfsfsfsf on Tuesday, January 29, 2013 5:15 AM
gsdfgdsfgdfg
Comment posted by Poonam on Tuesday, January 29, 2013 6:48 AM
after I click sumit button, i can't  see anydesign and no error line. kindly send me the solution. thanks
Comment posted by Poonam on Tuesday, January 29, 2013 6:56 AM
Plz plz tell me solution ...same code is used but no image is displayed.....
Comment posted by Poonam on Tuesday, January 29, 2013 6:56 AM
Plz plz tell me solution ...same code is used but no image is displayed.....
Comment posted by Poonam on Tuesday, January 29, 2013 6:57 AM
Plz plz tell me solution ...same code is used but no image is displayed.....
Comment posted by Holly on Monday, February 25, 2013 9:34 AM
What is the name of the file that contains the code for this project?
Comment posted by Holly on Monday, February 25, 2013 9:54 AM
What is the name of the file that contains the code for this project?
Comment posted by Mr.Nilesh N Mitaliya on Friday, March 8, 2013 10:40 PM
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.....hopes ....waiting your reply.....
plzzzzz...send me solution in my Email ID..A lots of thanx...xx
Comment posted by sam on Tuesday, March 19, 2013 6:02 AM
hi please send your email
Comment posted by amol on Monday, April 1, 2013 5:23 AM
thank you
Comment posted by Vikramraj Patil on Friday, April 19, 2013 2:42 AM
thank you Sir,You Provides valuable Information
Comment posted by bhargav on Thursday, April 25, 2013 6:44 AM
Thanks for the solution brother......worked perfectly ....
Comment posted by Jim on Tuesday, April 30, 2013 6:55 AM
Hi
it help me more but when i save my photo i cant see that .it save photo & i can view id but i cant see photo . i copy codes in asp.net 2010 .
Comment posted by Jim on Tuesday, April 30, 2013 7:14 AM
Hi
it help me more but when i save my photo i cant see that .it save photo & i can view id but i cant see photo . i copy codes in asp.net 2010 .
Comment posted by kavita pandey on Tuesday, May 7, 2013 6:15 AM
Hello sir,
kindly tell me the code "if we want to insert image from one page & wanna to display another page"
Comment posted by Md.Nazrul Islam on Sunday, May 26, 2013 3:02 AM
Thanks for providing useful code  
Comment posted by asjed on Wednesday, June 19, 2013 8:01 AM
thanks for this i take 2 months for stroing and retreiving images from databse it wwll solve my biggggggg problem thanks uuuuuuuuuuuuuuu
Comment posted by jagan on Saturday, July 6, 2013 8:01 AM
Can you explain breifly use of
object img = cmd.ExecuteScalar();
Comment posted by mamir on Sunday, July 14, 2013 10:49 AM
your article was very usefull for methanks alot.
Comment posted by jill on Wednesday, July 17, 2013 3:46 AM
great codes. work well for me.and what's more ,I got a C#.net solution via searching google.share it with you all.http://www.rasteredge.com/how-to/csharp-imaging/imaging-saving-printing/
Comment posted by preeti on Wednesday, July 17, 2013 4:56 AM
as u said in the last point to write a code before catch block then itgives error to me that catch is expected and also the handler would not be called
Comment posted by Justin on Tuesday, July 30, 2013 12:46 AM
You should actually use SCOPE_IDENTITY() instead of @@IDENTITY
Comment posted by sanjaya on Wednesday, August 7, 2013 4:33 AM
good work. it is worked for me. thanks
Comment posted by Bahare on Wednesday, December 25, 2013 1:48 PM
It's very good. thanks very much.
Comment posted by mohan on Friday, January 3, 2014 5:54 AM
it doesn't display image instead it shows corrupted image symbol
Comment posted by mohan on Friday, January 3, 2014 5:54 AM
it doesn't display image instead it shows corrupted image symbol
Comment posted by tha Bunsath on Tuesday, February 11, 2014 1:58 AM
please you demo too
Comment posted by rajesh on Wednesday, March 19, 2014 4:05 AM
this code  not worked correctly
Comment posted by shakeel on Tuesday, April 8, 2014 1:19 AM
I saved the image name in database and image in a folder. how can I get the image from folder using image handler
Comment posted by shithead on Friday, May 9, 2014 3:23 AM
didn't worked right... it can't retrieve image... and post it in a image handler... using asp.net using visual studio 2012 and sqlserver 2010...
Comment posted by hghg on Wednesday, May 21, 2014 1:43 PM
A7A
Comment posted by sasikumar on Thursday, June 19, 2014 5:10 AM
Thanks a lot
Comment posted by emana on Sunday, August 24, 2014 6:38 AM
didn't worked right... it can't retrieve image... and post it in a image handler... using asp.net using visual studio 2012 and sqlserver 2010..

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