Saturday 26 January 2013

Setting default profile image if there is no database image available

.aspx page

<asp:Image ID="imb_ProfilePhoto" runat="server" Width="100px" Height="100px"  ImageUrl="~/images/user_profile.gif" />

// if you want to use html img tag instead of asp:image control then put this


<html>
    <body>
        <img src="<dynamic handler url>" alt="My Username" onError="this.src='../../images/user_profile.gif';" />
    </body>
</html>


Make ShowImage.ashx file and write this code


<%@ WebHandler Language="C#" Class="ShowImage" %>

using System;
using System.Web;
using System.IO;

public class ShowImage : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        Int32 empno = 0;

        if (context.Request.QueryString["id"] != null )
            empno = Convert.ToInt32(context.Request.QueryString["id"]);

     
        context.Response.ContentType = "image/jpeg";
        Stream strm = ShowEmpImage(empno);
        byte[] buffer = new byte[4096];

        if (strm != null)
        {

            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)
    {
        Class1 obj = new Class1();
        object objImg = obj.FetchPhoto(empno);

       // Here fetch your image from database, i used my class method for the same...

        try
        {
            return new MemoryStream((byte[])objImg);
        }
        catch
        {
            return null;
        }
        finally
        {
            obj = null;
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}


To assign default value if there is no database image value available.


imb_ProfilePhoto.ImageUrl = "ShowImage.ashx?id=" + id ;

imb_ProfilePhoto.Attributes["onError"] = "this.onerror=null;this.src='../../images/user_profile.gif';";

in src set your default image url to display.


Enjoy................

No comments:

Post a Comment