0

我正在尝试通过处理程序在网格视图中显示图像。但是当数据库中没有路径时,它会显示脏的无图像徽标。我需要在没有图像的地方显示“NOImage”图像。

 <asp:TemplateField HeaderText="Path_Image">
                            <ItemTemplate>
                                <asp:Image ID="Image1" runat="server" ImageUrl='<%# "LargeImage.ashx?p=" + Eval("Name") + "&q=" + Eval("Vertual_Path") %>' />
                            </ItemTemplate>
</asp:TemplateField>

///大图像.ashx..

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;

public class LargeImage : IHttpHandler
{
    private Regex _nameValidationExpression = new Regex(@"[^\w/]");
    private int _thumbnailSize = 250;

    public void ProcessRequest(HttpContext context)
    {
        string photoName = context.Request.QueryString["p"];
        string P_Path = context.Request.QueryString["Q"];
        if (photoName == "" )
        {
            //file = (byte[])reader["Image"];
           // FileStream fs = File.OpenRead(HttpContext.Current.Server.MapPath("~/Article/NoImage.png"));
            //File = new byte[fs.Length];
            //fs.Read(File, 0, File.Length);
            context.Server.MapPath("~/Article/NoImage.jpg");
        }
        else
        {
            if (_nameValidationExpression.IsMatch(photoName))
            {

                throw new HttpException(404, "Invalid photo name.");
            }
            string cachePath = Path.Combine(HttpRuntime.CodegenDir, photoName + ".Large.png");
            if (File.Exists(cachePath))
            {
                OutputCacheResponse(context, File.GetLastWriteTime(cachePath));
                context.Response.WriteFile(cachePath);
                return;
            }
            else
            {

            }
            //string photoPath = context.Server.MapPath("~/Photo/" + photoName + ".jpg");
            // string photoPath = context.Server.MapPath("~/Photo/" + photoName + ".jpg");
            string photoPath = context.Server.MapPath(P_Path + "\\" + photoName + ".jpg");

            Bitmap photo;
            try
            {
                photo = new Bitmap(photoPath);
            }
            catch (ArgumentException)
            {

                throw new HttpException(404, "Photo not found.");
            }
            context.Response.ContentType = "image/pjpeg";
            int width, height;

            if (photo.Width > photo.Height)
            {
                width = _thumbnailSize;
                height = photo.Height * _thumbnailSize / photo.Width;
            }
            else
            {
                width = photo.Width * _thumbnailSize / photo.Height;
                height = _thumbnailSize;
            }
            Bitmap target = new Bitmap(width, height);
            using (Graphics graphics = Graphics.FromImage(target))
            {
                graphics.CompositingQuality = CompositingQuality.HighSpeed;
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.CompositingMode = CompositingMode.SourceCopy;
                graphics.DrawImage(photo, 0, 0, width, height);
                using (MemoryStream memoryStream = new MemoryStream())
                {

                    //context.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + photoName  + "\"");
                    context.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + DateTime.UtcNow.ToString() + "\"");
                    target.Save(memoryStream, ImageFormat.Jpeg);
                   // OutputCacheResponse(context, File.GetLastWriteTime(photoPath));
                    // OutputCacheResponse(context, File.GetLastWriteTime(photoPath));
                    using (FileStream diskCacheStream = new FileStream(cachePath, FileMode.CreateNew))
                    {
                        memoryStream.WriteTo(diskCacheStream);
                    }
                    memoryStream.WriteTo(context.Response.OutputStream);
                    context.Response.Flush();
                }
            }
        }
    }
4

3 回答 3

0

在 LargeImage.ashx 页面中,如果没有要呈现的记录/图像,请重定向到您本地拥有的静态图像(例如在您的图像文件夹中)。

这样,您就不会依赖浏览器特定的“损坏”图像。

例如

 Response.ContentType = "image/jpeg"  
 Try
    photo = GetPhoto(param)
      IF photo is Nothing then
            Response.Redirect("images/unknown.jpg", True)
      Else  
          Response.Binarywrite(photo)
      End if 
  Catch
            Response.Redirect("images/unknown.gif", True)
  Finally
      photo.Dispose() 
  End Try
于 2012-09-13T18:09:56.947 回答
0

在阅读您的代码时,您的问题似乎是您抛出的 HttpException(404, "Invalid photo name.") 。

浏览器会将其解释为损坏的图像。

用重定向到已知的本地图像替换那些。

于 2012-09-13T18:17:12.863 回答
0

您可以尝试使用此代码 - 基于 ProcessRequest

public class ImageHandler : IHttpHandler 
{
 public void ProcessRequest(System.Web.HttpContext ctx) 
 {
      if(condition) // Adjust your condition
      {     
         var path = ctx.Server.MapPath("~/images/NoImage.gif");
         var contentType = "image/gif";
         ctx.Response.ContentType = contentType;
         ctx.Response.WriteFile (path);
      }

}

public bool IsReusable { get {return true; } }        


}
于 2012-09-13T18:12:34.207 回答