如果没有在asp.net 3.5中找到的项目,如何从图像文件夹传递默认图像

时间:2014-04-09 12:56:44

标签: c# asp.net

我有一个ASHX处理程序,可以在从服务器端请求后显示图像。

这是我的处理程序代码:

<%@ 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;
        }
    }

}

这里是if(item!=null)的其他部分我只是想从服务器端的images文件夹中传递默认图像。

请帮帮我......

2 个答案:

答案 0 :(得分:1)

你可以这样做:

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);
            }

答案 1 :(得分:0)

您可以使用完整路径从文件中获取字节

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;
    }