Display Image From Database
In my previous article, I had mention how to insert image into Database. Here I will show how to display image from database.This article is regarding how to display image from database. I am using Http Handler to display image. I will pass user id from text box and on click of search button I will display image into Image control.
Download source code from here.
Http Handler code look like this :-
<%@ WebHandler Language="C#" Class="DisplayImage" %> using System; using System.Web; using System.Data.SqlClient; using System.Web.Configuration; public class DisplayImage : IHttpHandler { string conString = WebConfigurationManager.ConnectionStrings["MyBlogConnectionString"].ConnectionString; public void ProcessRequest(HttpContext context) { SqlConnection con = new SqlConnection(conString); SqlCommand cmd = new SqlCommand("SELECT UserImage FROM UserData WHERE UserID=@UserID", con); cmd.Parameters.AddWithValue("@UserID", context.Request["UserID"]); using (con) { con.Open(); Byte[] bytes = (Byte[])cmd.ExecuteScalar(); context.Response.ContentType = "image/gif"; context.Response.BinaryWrite(bytes); } } public bool IsReusable { get { return false; } } } |
HTML mark up look like this
<div> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:Label ID="Label1" runat="server" Text="Enter User ID" /> <asp:TextBox ID="txtUserID" runat="server" /><br /> <asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" /> <br /> <br /> <asp:Image ID="imgUser" Visible="false" runat="server" /> </ContentTemplate> </asp:UpdatePanel> </div> |
Button click event of search look like below :-
protected void btnSearch_Click(object sender, EventArgs e) { imgUser.ImageUrl = string.Format("DisplayImage.ashx?UserID={0}", txtUserID.Text); imgUser.Visible = true; } |
I will be passing userid as query string into httphandler file and display image.
output look like below when click on search button
Just a simple and small article, hope you like it. Download source code has been attached.