OutOfMemoryException C#上传图像文件时

时间:2010-06-20 23:11:11

标签: c# asp.net-mvc

我一直在研究图像。当用户上传图像时,我现在检查文件的大小。如果它小于1MB我检查文件实际上是图像类型。最后,我将图像调整为适当的计数大小,并创建图像的小缩略图。但是,因为添加代码来检查我一直在尝试的类型和OutOfMemoryException。

这是我的控制器方法:

        [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Upload(Image image, HttpPostedFileBase ImageFile)
    {

        if (ImageFile.ContentLength > 0)
        {
            // Get the size in bytes of the file to upload.
            int fileSize = ImageFile.ContentLength;

            // Allow only files less than 1,048,576 bytes (approximately 1 MB) to be uploaded.
            if (fileSize < 1048576)
            {
                string fileclass = "";

                using (BinaryReader r = new BinaryReader(ImageFile.InputStream))
                {
                    byte buffer = r.ReadByte();
                    fileclass = buffer.ToString();
                    buffer = r.ReadByte();
                    fileclass += buffer.ToString();
                    r.Close();
                }

                switch (fileclass)
                {
                    case "7137":
                    case "255216":
                    case "13780":
                        try
                        {
                            string path = Server.MapPath("~/Uploads/");

                            ImageFile.SaveAs(path + ImageFile.FileName);

                            ResizeImageHelper resizeImageHelper = new ResizeImageHelper();
                            resizeImageHelper.ResizeImage(path + ImageFile.FileName, path + ImageFile.FileName, 640, 480, false);
                            resizeImageHelper.ResizeImage(path + ImageFile.FileName, path + "thumb" + ImageFile.FileName, 74, 74, false);

                            image.imageLocation = ImageFile.FileName;
                            image.imageThumb = "thumb" + ImageFile.FileName;

                            imageRepository.Add(image);
                            imageRepository.Save();

                            return RedirectToAction("Index", "Home");
                        }
                        catch (Exception ex)
                        {
                            return View("Error");
                        }
                }

            }
            else
            {
                //If file over 1MB
                return View("Error");
            }
        }
        else
        {
            //If file not uploaded
            return View("Error");
        }

        return View("Error");
    }

这是我使用的Resize方法:

public void ResizeImage(string OriginalFile, string NewFile, int NewWidth, int MaxHeight, bool OnlyResizeIfWider)
    {
        System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(OriginalFile);

        // Prevent using images internal thumbnail
        FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
        FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

        if (OnlyResizeIfWider)
        {
            if (FullsizeImage.Width <= NewWidth)
            {
                NewWidth = FullsizeImage.Width;
            }
        }

        int NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width;
        if (NewHeight > MaxHeight)
        {
            // Resize with height instead
            NewWidth = FullsizeImage.Width * MaxHeight / FullsizeImage.Height;
            NewHeight = MaxHeight;
        }

        System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero);

        // Clear handle to original file so that we can overwrite it if necessary
        FullsizeImage.Dispose();

        // Save resized picture
        NewImage.Save(NewFile);
    }

有人可以提出这方面的建议吗?我目前正在努力学习新事物: - )

谢谢,

乔恩

进展我已经将它缩小到这个块,当注释掉事情正常时:

using (BinaryReader r = new BinaryReader(ImageFile.InputStream))
                {
                    byte buffer = r.ReadByte();
                    fileclass = buffer.ToString();
                    buffer = r.ReadByte();
                    fileclass += buffer.ToString();
                    r.Close();

                }

2 个答案:

答案 0 :(得分:2)

我假设这不会在第一次运行时发生,但过了一段时间。这是对的吗?

修改删除了错误的假设,但IDisposable仍然存在问题


您没有处置NewImage,这会导致生产中出现问题。

我通常会说'只是使用',但尝试/最后是同样的事情。根据自己的判断,重构我们的使用。

System.Drawing.Image NewImage = null;
System.Drawing.Image FullsizeImage = null;

try
{
    FullsizeImage = System.Drawing.Image.FromFile(OriginalFile);

     [... snip ... ]

    NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero);

    // Clear handle to original file so that we can overwrite it if necessary
    FullsizeImage.Dispose();

    // Save resized picture
    NewImage.Save(NewFile);
}
finally
{
    if (FullsizeImage != null)
        FullsizeImage.Dispose();
    if (NewImage != null)
        NewImage.Dispose();
}

答案 1 :(得分:0)

Ok Guys发现这部分代码后就出现了问题:

using (BinaryReader r = new BinaryReader(ImageFile.InputStream))
            {
                byte buffer = r.ReadByte();
                fileclass = buffer.ToString();
                buffer = r.ReadByte();
                fileclass += buffer.ToString();
                r.Close();

            }

我把它更改为:

string fileclass = ImageFile.ContentType.ToString();

并将我的switch语句改为:

switch (fileclass)
                {
                    case "image/jpg":
                    case "image/jpeg":
                    case "image/png":
                    case "image/gif":
                        try

我也实施了罗伯特的建议。但是,我不确定是否是.NET的新手,这种检查文件类型的方法是否与之前一样准确?我的研究似乎表明,即使上载器改变了扩展,前者也可以发现文件类型,例如将example.exe重命名为example.jpg。我不确定是否仍然使用提供的.NET功能?

相关问题