asp.net - 使用 HTTP 处理程序 ASP.Net 调整图像大小,一些图像未显示

标签 asp.net ihttphandler

我在我的智慧在这里结束。

我有一个 HTTP 处理程序 (ImageHandler.ashx),它发送图像(调整大小),它是一个标准 HTTP 处理程序(使用可重用的 true 和 false 进行尝试),它使用 Image.GetThumbnailImage 来调整大小并返回缩略图。

我有一个带有 html 图像控件的表的 asp Datalist 控件。

     <asp:DataList ID="listImg" runat="server" RepeatColumns="4" RepeatDirection="Horizontal"
        ShowFooter="false" ShowHeader="false">
        <ItemTemplate>
            <table width="220px">
                <tr width="100%">
                    <td>
                        <img src="Scripts/ImageHandler.ashx?width=125&image=Upload/<%# DataBinder.Eval(Container.DataItem, "photo") %>"                              
                    </td>
                </tr>
            </table>
        </ItemTemplate>
    </asp:DataList>

如您所见,处理程序需要的参数是宽度和图像路径。

此 Datalist 绑定(bind)到提供要显示的图像列表的数据表 (ImageData)。

到目前为止一切都说得通,现在是问题所在 - 假设我正在加载 5 张图像,即我的 ImageData DataTable 有 5 行,假设只显示 3-4 张图像,其余的只是想出一个红色的 X,就像你没有图像时一样。现在,如果您查看代码并导航到图像 src,例如 -
    http://localhost:3540/Scripts/ImageHandler.ashx?width=150&image=Upload/Test123.jpg

你会看到图像,它们都没有丢失的图像。重新加载,他们回来了。

我在 Firefox 中运行它并打开 Firebug,当我查看图像选项卡时,所有图像都根据 Firebug 返回(状态 200 OK,我在响应选项卡中看到图像),就像 Web 服务器不显示一些其中。请注意,处理/加载时间最长的图像并不总是丢失,而是一些随机图像。

这里会发生什么?

谢谢你。

编辑 1 - 添加处理程序代码(原始),我们继承了此代码。我已经从这里的代码中删除了缓存,但仅供引用的缩略图一旦生成就会被缓存。
    public class ImageHandler : IHttpHandler{
public int _width;
public int _height;
public int _percent;
public string imageURL;


public void ProcessRequest(HttpContext context)
{
    try
    {
        Bitmap bitOutput;

        string appPath = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["ImagePath"]);

        String strArquivo = appPath + context.Request.QueryString["image"].Replace("/", "\\");

        if (!(String.IsNullOrEmpty(context.Request["width"])))
        {
            Bitmap bitInput = GetImage(context);

           if (SetHeightWidth(context, bitInput))
            { bitOutput = ResizeImage(bitInput, _width, _height, _percent); }
            else { bitOutput = bitInput; }

            context.Response.ContentType = "image/jpeg";
            bitOutput.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        }

        return;

    }
    catch (Exception ex) { /*HttpContext.Current.Response.Write(ex.Message);*/ }
}


/// <summary>
/// Get the image requested via the query string. 
/// </summary>
public Bitmap GetImage(HttpContext context)
{
    try
    {
        if (context.Cache[("ImagePath-" + context.Request.QueryString["image"])] == null)
        {
            string appPath = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["ImagePath"]);

            appPath = appPath + context.Request.QueryString["image"].Replace("/", "\\");
            Bitmap bitOutput;
            imageURL = appPath;


            bitOutput = new Bitmap(appPath);
            return bitOutput;
        }
        else
        {
            return (Bitmap)context.Cache[("ImagePath-" + context.Request.QueryString["image"])];
        }

    }
    catch (Exception ex) { throw ex; }
}    


/// <summary>
/// Set the height and width of the handler class.
/// </summary>
public bool SetHeightWidth(HttpContext context, Bitmap bitInput)
{
    try
    {
        double inputRatio = Convert.ToDouble(bitInput.Width) / Convert.ToDouble(bitInput.Height);

        if (!(String.IsNullOrEmpty(context.Request["width"])) && !(String.IsNullOrEmpty(context.Request["height"])))
        {
            _width = Int32.Parse(context.Request["width"]);
            _height = Int32.Parse(context.Request["height"]);
            return true;
        }
        else if (!(String.IsNullOrEmpty(context.Request["width"])))
        {
            _width = Int32.Parse(context.Request["width"]);
            _height = Convert.ToInt32((_width / inputRatio));
            if (_width == 400 &&_height > 500)
            {
                _height = 500;
                _width = Convert.ToInt32(500 * inputRatio);
            }
            else if (_width == 125 && _height > 200)
            {
                _height = 200;
                _width = Convert.ToInt32(200 * inputRatio);
            }
            return true;
        }
        else if (!(String.IsNullOrEmpty(context.Request["height"])))
        {
            _height = Int32.Parse(context.Request["height"]);
            _width = Convert.ToInt32((_height * inputRatio));
            return true;
        }
        else if (!(String.IsNullOrEmpty(context.Request["percent"])))
        {
            _height = bitInput.Height;
            _width = bitInput.Width;
            _percent = Int32.Parse(context.Request["percent"]);
            return true;
        }
        else
        {
            _height = bitInput.Height;
            _width = bitInput.Width;
            return false;
        }

    }
    catch (Exception ex) { throw ex; }
}

/// <summary>
/// Resizes bitmap using high quality algorithms.
/// </summary>
public static Bitmap ResizeImage(Bitmap originalBitmap, int newWidth, int newHeight, int newPercent)
{
    try
    {
        if (newPercent != 0)
        {
            newWidth = Convert.ToInt32(originalBitmap.Width * (newPercent * .01));
            newHeight = Convert.ToInt32(originalBitmap.Height * (newPercent * .01));
        }

        Bitmap inputBitmap = originalBitmap;
        Bitmap resizedBitmap = new Bitmap(newWidth, newHeight, PixelFormat.Format64bppPArgb);

        Graphics g = Graphics.FromImage(resizedBitmap);
        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
        g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
        Rectangle rectangle = new Rectangle(0, 0, newWidth, newHeight);
        g.DrawImage(inputBitmap, rectangle, 0, 0, inputBitmap.Width, inputBitmap.Height, GraphicsUnit.Pixel);
        g.Dispose();

        return resizedBitmap;

    }
    catch (Exception ex) { throw ex; }
}


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

编辑 2 如果有人希望测试整个事情,这里是从预定义文件夹中随机选取图像以创建 aspDataList (listImg) 绑定(bind)到的 DataTable (ImageData) 的代码 -
        System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(Server.MapPath("Upload"));
        System.IO.FileInfo[] files = dirInfo.GetFiles();

        int fileCount = files.Length;

        System.Data.DataTable ImageData = new System.Data.DataTable();
        System.Data.DataColumn dCol = new System.Data.DataColumn("photo");
        ImageData.Columns.Add(dCol);


        System.Random rnd = new Random();
        int nxtNumber = 0;

        System.Data.DataRow dRow = null;

        string fileName = string.Empty;

        for (int i = 0; i < 20; i++)
        {
            dRow = ImageData.NewRow();
            nxtNumber = rnd.Next(fileCount);
            while (!files[nxtNumber].Extension.Equals(".jpg"))
            {
                nxtNumber = rnd.Next(fileCount);
            }
            fileName = files[nxtNumber].Name;

            dRow["photo"] = fileName;

            ImageData.Rows.Add(dRow);
        }
        listImg.DataSource = ImageData;
        listImg.DataBind();

最佳答案

尝试编码 url 的查询字符串,例如:

http://localhost:3540/Scripts/ImageHandler.ashx?width=150&image=Upload/Test123.jpg

网址编码为
http://localhost:3540/Scripts/ImageHandler.ashx?width%3D150%26image%3DUpload%2FTest123.jpg

关于asp.net - 使用 HTTP 处理程序 ASP.Net 调整图像大小,一些图像未显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16024612/

相关文章:

asp.net - httpModules 不适用于 iis 7.5 的 url 重写/扩展少 url(给出错误 500.0)

c# - IHTTPHandler 的无缓冲输出

c# - ASP.net 中的静态文件和身份验证

asp.net - 从数据库加载时,是否有更可靠的方式在网页上显示图像?

asp.net - 如何在 Entity Framework 中禁用每个查询的查询执行计划缓存?

c# - 上传 ashx 文件 Context.Session 为空

c# - 执行 IHttpHandler 到 MemoryStream

c# - CSS 中的 JavaScript 在回发时丢失 (ASP.NET)

asp.net - 将页面添加到母版页给我 javascript 错误

c# - 使用 System.Web.Optimization 时如何将类型 ="text/javascript"添加到脚本标记