计算并随机显示给定目录中的图像

时间:2016-04-20 14:57:05

标签: c# image directory

我有传递路径(本地目录)的C#处理程序文件。此路径有时包含一个图像,有时包含100个图像。处理程序的目的是随机选择其中一个图像,并将其返回到调用处理程序的slideshow.aspx文件中。除了在某些情况下我得到'500'错误以及在仅存在一个图像的实例中的以下堆栈跟踪 - 有时不是全部:

[ArgumentException: Parameter is not valid.]
System.Drawing.Bitmap..ctor(String filename) +685715
SafetyMonitors.GetImage.ProcessRequest(HttpContext context) +213
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +913
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +165

这是我的处理程序代码:

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web;

namespace SafetyMonitors
{
/// <summary>
/// Grab images in shared public directory, based on incoming querystring path variable. randomize. stream new image back to request.
/// </summary>
public class GetImageUpdated : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        var SharePath = context.Request["SharePath"];
        Random rnd = new Random(); //randomize image
        string[] images = Directory.GetFiles(@"E:\inetpub\wwwroot\service center monitors\Shares\" + SharePath, "*.*", SearchOption.TopDirectoryOnly);

        if(images.Length == 1)
        {
            string imgToDisplay = images[images.Length];
            Image img = new Bitmap(imgToDisplay);
            using (MemoryStream ms = new MemoryStream())
            {
                img.Save(ms, ImageFormat.Png);
                ms.WriteTo(context.Response.OutputStream);
            }
        }
        else
        {
            string imgToDisplay = images[rnd.Next(images.Length - 1)];
            Image img = new Bitmap(imgToDisplay);
            using (MemoryStream ms = new MemoryStream())
            {
                img.Save(ms, ImageFormat.Png);
                ms.WriteTo(context.Response.OutputStream);
            }
        }

        context.Response.ContentType = "image/jpeg";
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
  }
}

我已经尝试添加IF语句来处理目录中只有1个图像的情况,认为它必须与计数和random()有关。

有什么想法吗?谢谢!

1 个答案:

答案 0 :(得分:0)

您的代码:

   if(images.Length == 1)
    {
        string imgToDisplay = images[images.Length];
        Image img = new Bitmap(imgToDisplay);
        using (MemoryStream ms = new MemoryStream())
        {
            img.Save(ms, ImageFormat.Png);
            ms.WriteTo(context.Response.OutputStream);
        }
    }

正在寻找数组第二个存储位置的值......记住它们是零基础。

您应该使用:

string imgToDisplay = images[images.Length-1];