ImageResizer - 进程无法访问该文件,因为它正由另一个进程使用

时间:2013-03-20 21:49:30

标签: asp.net imageresizer

此行引发错误:ImageBuilder.Current.Build(imgURL, imgURL, resizeImg);

知道为什么吗?

public void setImgSize(string controlId, string filename)
{
    decimal currentWidth = 0;
    decimal currentHeight = 0;
    int maxFileWidth = 600;
    int maxFileHeight = 600;
    bool imageExists = false;
    string imgURL = "~/SODocs/" + SONum + "/" + filename;
    string imgPath = Server.MapPath(imgURL);
    if (File.Exists(imgPath))
    {
        imageExists = true;
        System.Drawing.Image imgFile = System.Drawing.Image.FromFile(imgPath);
        Image imgControl = FindControl(controlId) as Image;
        int maxDisplayWidth = 273;
        int maxDisplayHeight = 200;
        currentWidth = Convert.ToDecimal(imgFile.Width);
        currentHeight = Convert.ToDecimal(imgFile.Height);
        int newDisplayWidth = 0;
        int newDisplayHeight = 0;
        int paddingHeight = 0;

        if (currentHeight > currentWidth)
        {
            imgControl.Height = maxDisplayHeight;
            newDisplayWidth = Convert.ToInt32((maxDisplayHeight / currentHeight) * currentWidth);
            imgControl.Width = newDisplayWidth;
            imgControl.Style.Add("margin", "0 auto");
        }
        else if (currentWidth > currentHeight)
        {
            newDisplayHeight = Convert.ToInt32((maxDisplayWidth / currentWidth) * currentHeight);

            if (newDisplayHeight > maxDisplayHeight)
            {
                // set newWidth based on maxHeight
                newDisplayWidth = Convert.ToInt32((maxDisplayHeight / currentHeight) * currentWidth);
                imgControl.Width = newDisplayWidth;
                imgControl.Style.Add("margin", "0 auto");
            }
            else
            {
                imgControl.Width = maxDisplayWidth;
            }

            paddingHeight = maxDisplayHeight - newDisplayHeight;
            imgControl.Style.Add("padding-top", paddingHeight.ToString() + "px");
        }

        imgControl.ImageUrl = imgURL;
        imgFile.Dispose();
        imgFile = null;

        if (imageExists)
        {
            // resize the image file
            if (currentWidth > maxFileWidth | currentHeight > maxFileHeight)
            {
                var resizeImg = new ResizeSettings();
                resizeImg.MaxWidth = maxFileWidth;
                resizeImg.MaxHeight = maxFileHeight;

                ImageBuilder.Current.Build(imgURL, imgURL, resizeImg);

            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您打开文件以便自己单独阅读,但希望ImageResizer能够稍后写入。 System.Drawing无法正确处理文件锁定,并且.Dispose()不足以处理内存泄漏以及您遇到的文件访问问题。

我建议使用ImageResizer审核the best practicies guide

使用URL API in a much simpler and less crash-prone manner可以实现您在此处尝试完成的任务。