Shalin Gajjar
Shalin Gajjar

Reputation: 239

how to pass default image from images folder if no if no items found in asp.net 3.5

i have one ASHX handler that can display images after request has been made from server side.

here is my handler code :

<%@ WebHandler Language="C#" Class="DisplayImage" %>
using System;
using System.Web;
using System.Linq;
public class DisplayImage : IHttpHandler {

    public void ProcessRequest(HttpContext context)
    {
        int userId;
        if (context.Request.QueryString["userId"] != null)
            userId = Convert.ToInt32(context.Request.QueryString["userId"]);
        else
            throw new ArgumentException("No parameter specified");
        var query = Helper.GetPhotos().Where(p => p.user_id.Equals(userId)).Select(p => p).ToList();
        byte[] imageData = null;
        foreach (var item in query)
        {
            if (item != null)
            {
                imageData = item.Image.ToArray();
                context.Response.ContentType = "image/jpeg";
                context.Response.BinaryWrite(imageData);
            }
            else
            {
                //get images from images named folder and parse it to byte array
            }
        }
    }
    public bool IsReusable {
        get {
            return false;
        }
    }

}

here at else section of if(item!=null) i just want to pass default image from images folder at server side.

please help me...

Upvotes: 0

Views: 584

Answers (2)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

You can do like this:

if (item != null)
            {
                imageData = item.Image.ToArray();
                context.Response.ContentType = "image/jpeg";
                context.Response.BinaryWrite(imageData);
            }
            else
            {
                //get images from images named folder and parse it to byte array
             imageData =System.IO.File.ReadAllBytes(System.Web.HttpContext.Current.Server.MapPath("~/Images/DefaultImage.jpg"));

            context.Response.ContentType = "image/jpeg";
            context.Response.BinaryWrite(imageData);
            }

Upvotes: 1

Purvesh Desai
Purvesh Desai

Reputation: 1805

you can get byte from file with the full path

public static byte[] GetByteFromFile(string FullPath)
    {
        byte[] ImageData = null;
        if (System.IO.File.Exists(FullPath))
        {
            System.IO.FileStream fs = new System.IO.FileStream(FullPath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            ImageData = new byte[fs.Length];
            fs.Read(ImageData, 0, System.Convert.ToInt32(fs.Length));
            fs.Close();
        }
        return ImageData;
    }

Upvotes: 0

Related Questions