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

使用HTTP处理程序ASP.Net调整图像大小,某些图像未显示,asp.net,ihttphandler,Asp.net,Ihttphandler,我在这里束手无策 我有一个HTTP处理程序(ImageHandler.ashx)可以发送图像(调整大小),它是一个标准的HTTP处理程序(使用可重用的true和false进行了尝试),使用Image.GetThumbnailImage来调整大小并返回缩略图 我有一个asp数据列表控件,它有一个带有html图像控件的表 <asp:DataList ID="listImg" runat="server" RepeatColumns="4" RepeatDirection="Horiz

我在这里束手无策

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

我有一个asp数据列表控件,它有一个带有html图像控件的表

     <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>
你会看到图像,它们都在那里,没有丢失的图像。重新装弹,他们回来了

我在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;
    }
}}
公共类ImageHandler:IHttpHandler{
公共内部宽度;
公共内部高度;
公共国际百分比;
公共字符串imageURL;
公共void ProcessRequest(HttpContext上下文)
{
尝试
{
位图位输出;
字符串appPath=Convert.ToString(System.Configuration.ConfigurationManager.AppSettings[“ImagePath]”);
字符串strArquivo=appPath+context.Request.QueryString[“image”]。替换(“/”,“\\”;
if(!(String.IsNullOrEmpty(context.Request[“width”]))
{
位图bitInput=GetImage(上下文);
if(设置高度宽度(上下文,输入位))
{bitOutput=ResizeImage(bitInput,_width,_height,_percent);}
else{bitOutput=bitInput;}
context.Response.ContentType=“image/jpeg”;
保存(context.Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);
}
返回;
}
catch(异常ex){/*HttpContext.Current.Response.Write(ex.Message);*/}
}
/// 
///通过查询字符串获取请求的图像。
/// 
公共位图GetImage(HttpContext上下文)
{
尝试
{
if(context.Cache[((“ImagePath-”+context.Request.QueryString[“image”])]]==null)
{
字符串appPath=Convert.ToString(System.Configuration.ConfigurationManager.AppSettings[“ImagePath]”);
appPath=appPath+context.Request.QueryString[“image”]。替换(“/”,“\\”);
位图位输出;
imageURL=appPath;
bitOutput=新位图(appPath);
返回位输出;
}
其他的
{
返回(位图)context.Cache[(“ImagePath-”+context.Request.QueryString[“image”]);
}
}
catch(异常ex){throw ex;}
}    
/// 
///设置处理程序类的高度和宽度。
/// 
公共bool设置高度宽度(HttpContext上下文,位图输入)
{
尝试
{
双输入=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”]);
返回true;
}
else if(!(String.IsNullOrEmpty(context.Request[“width”]))
{
_width=Int32.Parse(context.Request[“width”]);
_高度=转换为32((_宽度/输入));
如果(_-width==400&&u-height>500)
{
_高度=500;
_宽度=转换为32(500*输入);
}
如果(_宽度==125&&u高度>200)为其他情况
{
_高度=200;
_宽度=转换为32(200*输入);
}
返回true;
}
else if(!(String.IsNullOrEmpty(context.Request[“height”]))
{
_height=Int32.Parse(context.Request[“height”]);
_宽度=转换为32((_高度*输入));
返回true;
}
else if(!(String.IsNullOrEmpty(context.Request[“percent”]))
{
_高度=输入高度;
_宽度=输入口宽度;
_percent=Int32.Parse(context.Request[“percent”]);
返回true;
}
其他的
{
_高度=输入高度;
_宽度=输入口宽度;
返回false;
}
}
catch(异常ex){throw ex;}
}
/// 
///使用高质量算法调整位图大小。
/// 
公共静态位图大小图像(位图原始位图、int-newWidth、int-newHeight、int-newPercent)
{
尝试
{
如果(新百分比!=0)
{
newWidth=Convert.ToInt32(originalBitmap.Width*(newPercent*.01));
newHeight=转换为32(原始albitmap.Height*(newPercent*.01));
}
位图输入位图=原始位图;
位图resizedBitmap=新位图(newWidth、newHeight、PixelFormat.Format64bppPArgb);
Graphics g=Graphics.FromImage(resizedBitmap);
g、 合成质量=System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g、 CompositingMode=System.Drawing.Drawing2D.CompositingMode.SourceCopy;
g、 插值模式=System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
矩形矩形=新矩形(0,0,newWidth,newHeight);
g、 DrawImage(inputBitmap,矩形,0,0,inputBitmap.Width,inputBitmap.Height,GraphicsUnit.Pixel);
g、 处置();
返回resizedBitmap;
}
catch(异常ex){throw ex;}
}
公共布尔可重用
{
得到
{
返回true;
}
}}
edit2如果有人想测试这整件事,下面是从预定义文件夹中随机选取图像以创建
    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;
    }
}}
        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();
http://localhost:3540/Scripts/ImageHandler.ashx?width=150&image=Upload/Test123.jpg
http://localhost:3540/Scripts/ImageHandler.ashx?width%3D150%26image%3DUpload%2FTest123.jpg