Friday, 27 April 2012

Showing Image from DB in ASP.NET

Using the Employees table within Northwind database, we are trying to get the image from the Photo column. Here are the source code: ImageHandler.ashx
using System;
using System.Web;
using System.Data.Sql;
using System.Data.SqlClient;

public class ImageHandler: IHttpHandler 
{
    public void ProcessRequest (HttpContext context) 
    {
        string _cnnString = System.Configuration.ConfigurationManager.ConnectionStrings["cnxstring"].ToString();
        SqlConnection myConnection = new SqlConnection(_cnnString); 
       
        string sql = "SELECT Photo FROM [Employees] WHERE [EmployeeID] = @ID"; 
        SqlCommand cmd = new SqlCommand(sql, myConnection);
        cmd.Parameters.Add("@ID", System.Data.SqlDbType.Int).Value = context.Request.QueryString["id"];
         
        myConnection.Open();
        byte[] pict = (byte[])cmd.ExecuteScalar();
        myConnection.Close();

        context.Response.ContentType = "image/jpg";
        context.Response.OutputStream.Write(pict, 78, pict.Length - 78); 
          
    } 
}


Default.aspx

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
           
        <asp:Label ID="lblResult" runat="server" ForeColor="#0066FF"></asp:Label>
    <br />
    <hr />

   <asp:Image ID="Image1" style="width:200px" Runat="server" />
       ID: <asp:TextBox ID="tbxID" runat="server"></asp:TextBox>
        <asp:Button ID="btnShow" runat="server" Text="Show" onclick="btnShow_Click" />
    </div>
    </form>
</body>
</html>

Default.aspx.cs
public partial class _Default : System.Web.UI.Page 
{
    public string _cnnString = ConfigurationManager.ConnectionStrings["NwConnectionString"].ToString();
    protected void Page_Load(object sender, EventArgs e)
    {
       
    }
    protected void btnShow_Click(object sender, EventArgs e)
    {
        Image1.ImageUrl = "~/ImageHandler.ashx?id=" + tbxID.Text;
        
    }

    
}
How it looks

No comments:

Post a Comment