将HttpPostedFileWrapper变量传递给函数会破坏另一个函数。 C#中的图像验证和转换

时间:2015-06-19 16:53:30

标签: c# asp.net asp.net-mvc asp.net-mvc-4 filestream

所以基本上该程序的这一部分是编辑/上传新的个人资料图片到用户的帐户。以前,它运作良好。然后我决定添加一些图片验证(图片必须有一定的尺寸等)。所以我为它创建了一个单独的Helper类,它接受了在控制器中初始化的HttpPostedFileWrapper变量。

因此,在这个控制器函数中,我初始化了ValidateImage类的一个新实例,该实例包含两个函数(DoValidationResize)。

Resize函数工作正常,直到我添加了DoValidation函数,我觉得它与内存流有关。

我现在得到一个"无效参数" ResizeImage函数中的错误(见下文),即使我从未更改过该代码并且之前工作正常。是否与文件流没有正确关闭或其他什么有关?

以下是代码:

 //Controller.cs

public virtual ActionResult EditMyProfilePicture(bool? ignore)
{
    var loggedInEmployee = this.EmployeeRepos.GetEmployeeByUserName(User.Identity.Name);
    int tgtWidth = 250, tgtHeight = 250;

    try
    {
        // get a reference to the posted file
        var file = Request.Files["FileContent"] as HttpPostedFileWrapper;
        ValidateImage img = new ValidateImage();

        if (file != null && file.ContentLength > 0)
        {
            // isolate the filename - IE returns full local path, other browsers: just the file name.
            int index = file.FileName.LastIndexOf("\\");
            // if not IE, index will be -1, but -1 + 1 = 0 so we are okay.  
            string fileName = file.FileName.Substring(index + 1);

            // Validate the image
            img.DoValidation(file, tgtWidth, tgtHeight);
            if (!img.IsValidated)
            {
                throw new ArgumentException(img.Message);
            }
            else
            {
                byte[] resizedImg = img.Resize(file, tgtWidth, tgtHeight);
                this.EmployeeRepos.SaveProfileImage(loggedInEmployee.EmployeeCode, resizedImg);
            }

            return RedirectToAction(MVC.Employees.EditMyProfile());
        }
        else
        {
            throw new ArgumentException("Please select a file to upload.");
        }
    }
    catch (Exception ex)
    {
        ModelState.AddModelError(string.Empty, ex.Message);
    }

    return View(Views.EditMyProfilePicture, loggedInEmployee);
}

// ValidateImage.cs

public class ValidateImage
{
    public string Message { get; private set; }
    public bool IsValidated { get; private set; }

    public void DoValidation(HttpPostedFileWrapper file, int tgtWidth, int tgtHeight)
    {
        try
        {
            Image img = Image.FromStream(file.InputStream);

            int curHeight = img.Height, curWidth = img.Width;

            // check for image too small
            if (curHeight < tgtHeight || curWidth < tgtWidth)
            {
                Message = "image is too small. please upload a picture at least 250x250.";
                IsValidated = false;
                return;
            }
            // check for image is square
            else if (curHeight != curWidth)
            {
                Message = "image is not a square.";
                IsValidated = false;
                return;
            }
            else
            {
                IsValidated = true;
            }
        }
        catch
        {

        }

    }

    public byte[] Resize(HttpPostedFileWrapper file, int tgtWidth, int tgtHeight)
    {
        byte[] bytes = new byte[file.ContentLength];
        file.InputStream.Read(bytes, 0, file.ContentLength);
        file.InputStream.Close(); // close the file stream.


        // Down-sample if needed from current byte array to max 250x250 Jpeg
        byte[] resized = Helpers.ImageResizer.ResizeImage(bytes, tgtWidth, tgtHeight, ResizeOptions.MaxWidthAndHeight, ImageFormat.Jpeg);
        return resized;
    }
}

// Resize Image function

public static byte[] ResizeImage(byte[] bytes, int width, int height, ResizeOptions resizeOptions, ImageFormat imageFormat)
{
    using (MemoryStream ms = new MemoryStream(bytes))
    {
        Image img = Image.FromStream(ms);
        Bitmap bmp = new Bitmap(img);
        bmp = ResizeImage(bmp, width, height, resizeOptions);
        bmp.SetResolution(72, 72);
        bmp.Save(ms, imageFormat);

        return ms.ToArray();
    }
}

0 个答案:

没有答案