创建动态缩略图时出现OutOfMemoryException

时间:2012-07-26 02:53:21

标签: asp.net-mvc-3

这是交易,当我第一次得到这个画廊并且它运行良好,但在回到项目后我现在得到一个OutOfMemoryException。这是代码(至少其中一些)

ThumbnailActionResult

public override void ExecuteResult(ControllerContext context)
{
    if (string.IsNullOrEmpty(Filename))
        throw new ArgumentNullException("context", "FileName parameter cannot be null or empty");

    var filePath = context.HttpContext.Server.MapPath(context.HttpContext.Request.ApplicationPath) + @"Content\img\mounts\" + Filename;

    if (!File.Exists(filePath))
        throw new FileNotFoundException(string.Format("File {0} could not be found", filePath));
    //error happens here
    var bmp = new Bitmap(filePath);


    try
    {
        if (bmp.Width < Width && bmp.Height < Height)
        {
            context.HttpContext.Response.ContentType = "image/gif";
            bmp.Save(context.HttpContext.Response.OutputStream, ImageFormat.Jpeg);
            return;
        }
    }
    catch (Exception e)
    {
        throw new Exception(e.Message);
    }
    finally
    {
        bmp.Dispose();
    }


    GenerateFinalImage(context, filePath, bmp);

}

private Bitmap GenerateFinalImage(ControllerContext context, string fileName, Bitmap bmp)
{
    Bitmap finalBmp = null;

    try
    {
        //here we make a Bitmap based on the file name sent
        bmp = new Bitmap(fileName);

        //height, width and ratio values
        int w;
        int h;
        decimal ratio;

        //now we're deciding if the image is landscape or portrait
        if (bmp.Width > bmp.Height)
        {
            ratio = (decimal)this.Width / bmp.Height;
            w = this.Width;

            var temp = bmp.Height * ratio;
            h = (int)temp;
        }
        else
        {
            ratio = (decimal)this.Height / bmp.Height;
            h = Height;
            var temp = bmp.Width * ratio;
            w = (int)temp;
        }


        //Now we use the Graphics class to set it's clarity and to draw the final image.
        finalBmp = new Bitmap(w, h);
        var gfx = Graphics.FromImage(finalBmp);
        gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;
        gfx.FillRectangle(Brushes.White, 0, 0, w, h);
        gfx.DrawImage(bmp, 0, 0, w, h);

        context.HttpContext.Response.ContentType = "image/gif";
        finalBmp.Save(context.HttpContext.Response.OutputStream, ImageFormat.Jpeg);

    }
    catch (Exception e)
    {
        throw new Exception(e.Message);
    }
    finally
    {
        if (finalBmp != null) finalBmp.Dispose();
    }
    return finalBmp;
}

我一直试图在过去的几个小时内跟踪此事但无济于事。如果你需要更多代码让我知道,我会添加更多

0 个答案:

没有答案