在asp.net中绘制图像时内存不足异常

时间:2018-02-20 18:33:17

标签: c# asp.net image filestream

我们正在使用以下代码绘制和编辑pdf,但是当我们使用11mb大小的文件时,我们会遇到内存异常,我们可以解决问题吗,我使用了System.Drawing.Image.FromFile而不是FromStream但是没有运气..

 public static string ImageCar()
    {

        string FileName = HttpContext.Current.Session["filename"].ToString();
        Document doc = new Document(FileName);

        ArrayList arrFiles = new ArrayList();
        string strFileName = "";
        for (int pageCount = 1; pageCount <= TotalPages; pageCount++)
        {
            using (FileStream imageStream = new FileStream(HttpContext.Current.Server.MapPath("Input/image_" + strDateTime + "_" + pageCount + ".png"), FileMode.Create, FileAccess.ReadWrite))
            {
                strFileName = HttpContext.Current.Server.MapPath("Path" + strDateTime + "_" + pageCount + ".png");
                arrFiles.Add(strFileName);

                PngDevice pngDevice = new PngDevice();
                //Convert a particular page and save the image to stream
                pngDevice.Process(doc.Pages[pageCount], imageStream);
                using (System.Drawing.Image image = System.Drawing.Image.FromStream(imageStream))
                {
                    ScaleImage(image, 1189, 835, HttpContext.Current.Server.MapPath("Input/image1_" + strDateTime + "_" + pageCount + ".png"), out height, out Aratio);
                    image.Dispose();
                    imageStream.Close();
                    if (pageCount == 1)
                        fields = CheckFields(doc, pageCount, "image1_" + strDateTime + "_" + pageCount + ".png", fields, Convert.ToDouble(Aratio), licensed);

                    pages = pages + "," + "image1_" + strDateTime + "_" + pageCount + ".png";
                    Ratios = Ratios + "," + Aratio;
                    Allheights = Allheights + "," + height;

                    // Delete file from image folder
                    try
                    {
                        if (File.Exists(strFileName))
                        {
                            File.Delete(strFileName);
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
        }

        Ratios = Ratios.Substring(1, Ratios.Length - 1);
        pages = pages.Substring(1, pages.Length - 1);
        Allheights = Allheights.Substring(1, Allheights.Length - 1);
        if (fields != "")
        {
            fields = fields.Substring(3, fields.Length - 3);
        }

        return pages + "%#" + Ratios + "%#" + Allheights + "%#" + fields;
    }

1 个答案:

答案 0 :(得分:1)

System.Drawing已知ASP站点中的内存泄漏,绝不应使用。 它最终会出现OOM错误,虽然您可以通过每隔一段时间重新启动服务器来避免它,或者在其上投入更多内存,但是没有真正的长期修复。使用一些其他库来处理图像处理部分,你应该没有什么问题。

请参阅本页底部: https://msdn.microsoft.com/en-us/library/system.drawing(v=vs.110).aspx

  

不支持在Windows或ASP.NET服务中使用System.Drawing命名空间中的类。尝试在其中一种应用程序类型中使用这些类可能会产生意外问题,例如服务性能下降和运行时异常。有关支持的替代方法,请参阅Windows Imaging Components。