【问题标题】:Out Of Memory using Process使用进程内存不足
【发布时间】:2015-01-23 16:39:15
【问题描述】:

好的,所以我知道我应该使用 ImageMagick DLL...我正在学习、测试并努力做到这一点。但与此同时,我正在使用通过进程调用 Imagemagick 的 convert.exe 的低效方法。

当我在测试时,它可以很好地处理数百张图片。但后来我将我的 WindowsForms 程序移到一台速度更快的机器上,它每次都在同一点崩溃。

这是一个两步流程调用。第一次遍历所有文件并生成 PNG。然后我遍历所有 PNG 并将其与背景合成并输出 JPG。但每次恰好有 22 张图像时,它都会出错“System.OutOfMemoryException:内存不足”。有什么东西在填满我需要杀掉吗?

    foreach (string file in files)
            {
                try
                {
                    string captureImg = Path.GetFileName(file);
                    string maskImg = file.Replace("X.JPG", "Y.JPG");
                    string OutputImage = string.Format("{0}.png", Path.GetFileNameWithoutExtension(captureImg));
                    string output = Path.Combine(destFolder, OutputImage);
                    //MessageBox.Show(output);
                    progressBarImage.Value = progressBarImage.Value + 1;
                    lblStatus.Text = string.Format("Image {0} of {1}", progressBarImage.Value, maxFiles);
                    makePNG(file, maskImg, output);
                    Application.DoEvents();

                }
                catch (Exception)
                {
                }
            }

            if (chkBG.Checked)
            {
                //try
                //{
                    string JPGdir = Path.Combine(destFolder, "JPGs");
                    string[] PNGfiles = Directory.GetFiles(destFolder, "*C.PNG");

                    lblProgress.Text = "Generating JPGs with Background";
                    progressBarImage.Value = 0;
                    progressBarImage.Maximum = files.Length;
                    message = "PNG and JPG Export Complete";
                    if (!Directory.Exists(JPGdir))
                    {
                        Directory.CreateDirectory(JPGdir);
                    }
                    foreach (string PNGfile in PNGfiles)
                    {
                        Application.DoEvents();
                        string outputJPG = string.Format("{0}.jpg", Path.GetFileNameWithoutExtension(PNGfile));
                        string result = Path.Combine(JPGdir, outputJPG);
                        progressBarImage.Value += 1;
                        lblStatus.Text = string.Format("Image {0} of {1}", progressBarImage.Value, files.Length);
                        makeJPG(PNGfile, txtBackground.Text, result);
                        //MessageBox.Show(PNGfile);

                    }

private void makePNG(string source, string mask, string output)
        {
            if (!source.EndsWith("Y.JPG"))
            {
                Process proc = new Process();
                string appPath = Path.GetDirectoryName(Application.ExecutablePath);
                proc.EnableRaisingEvents = false;
                proc.StartInfo.FileName = @"""C:\Program Files\ImageMagick-6.9.0-Q16\convert.exe""";
                proc.StartInfo.Arguments = string.Format(@"{0} {1} -alpha off -compose  copy-opacity -level 5%  -composite {2}", source, mask, output);
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.CreateNoWindow = true;
                proc.Start();
                proc.WaitForExit();

            }
        }

        private void makeJPG(string source, string background, string output)
        {
            float BGimg = Image.FromFile(background).Height;
            float SubjectImg = Image.FromFile(source).Height;
            float ResultHeight = 100 * (BGimg / SubjectImg);
            int Height = Convert.ToInt32(ResultHeight);


            Process procJPG = new Process();
            string appPath = Path.GetDirectoryName(Application.ExecutablePath);
            procJPG.EnableRaisingEvents = false;
            procJPG.StartInfo.FileName = @"""C:\Program Files\ImageMagick-6.9.0-Q16\convert.exe""";
            procJPG.StartInfo.Arguments = string.Format(@"{1} ( {0} -resize {3}% ) -gravity South -composite {2}", source, background, output, Height);
            procJPG.StartInfo.UseShellExecute = false;
            procJPG.StartInfo.RedirectStandardOutput = true;
            procJPG.StartInfo.CreateNoWindow = true;
            procJPG.Start();
            procJPG.WaitForExit();
        }

【问题讨论】:

  • 你为什么要重定向标准输出?
  • Application.DoEvents(); 尽量不要使用它.. 这不是一个好习惯
  • @MethodMan 我不同意。 Application.DoEvents() 非常好如果适当使用(尽管适当使用它是困难的部分;-))
  • @MethodMan 我已经阅读了很多关于它的内容(包括那些说“它是邪恶的,从不使用它”),但是在我多年做 Windows.Forms 的过程中,我已经成功地在很多情况下,特别是在直接处理消息队列以处理 WinForms 中不存在的复杂功能时。它基本上等同于我们在直接 Win32 C++ 中使用的旧 PeekMessage 循环,如果您了解使用它的含义,它没有任何问题。是“DoEvents() 的错误用法”使它变得邪恶,而不是函数本身

标签: c# process imagemagick-convert


【解决方案1】:

乍一看,您在makeJPG() 中使用了两次Image.FromFile,而不是处理对象。 Image.FromFile 通常会创建需要释放的非托管 GDI+ 句柄。

来自documentation

文件保持锁定状态,直到图像被释放。

所以乍一看,我会假设您只是在内存中加载了太多图像,我会尝试:

private void makeJPG(string source, string background, string output)
{
  using(var backgroundImg = Image.FromFile(background))
  using(var sourceImg = Image.FromFile(source))
  {
    float BGimg = backgroundImg.Height;
    float SubjectImg = sourceImg.Height;
    float ResultHeight = 100 * (BGimg / SubjectImg);
    int Height = Convert.ToInt32(ResultHeight);


    Process procJPG = new Process();
    string appPath = Path.GetDirectoryName(Application.ExecutablePath);
    procJPG.EnableRaisingEvents = false;
    procJPG.StartInfo.FileName = @"""C:\Program Files\ImageMagick-6.9.0-Q16\convert.exe""";
    procJPG.StartInfo.Arguments = string.Format(@"{1} ( {0} -resize {3}% ) -gravity South -composite {2}", source, background, output, Height);
    procJPG.StartInfo.UseShellExecute = false;
    procJPG.StartInfo.RedirectStandardOutput = true;
    procJPG.StartInfo.CreateNoWindow = true;
    procJPG.Start();
    procJPG.WaitForExit();
  }
}

由于您实际上并没有使用图像(只是获取它们的高度),因此您可以将这些 using 块变小,但我将把它留给您。

...但是...

关于 OutOfMemoryException

另外,你说它恰好发生在 22 张图像上(这对于内存不足来说会很奇怪,除非图像一直很大),但是阅读相同的文档:

如果文件没有有效的图像格式,或者如果 GDI+ 不支持文件的像素格式,此方法将抛出 OutOfMemoryException 异常。

所以请确保第 22 张图片(“源”或“背景”,取决于它抛出的位置)具有正确的格式

【讨论】:

  • 太棒了……就是这样。只是阅读太多而没有正确处理它。谢谢!
猜你喜欢
  • 2021-09-07
  • 1970-01-01
  • 2011-05-16
  • 2020-04-09
  • 1970-01-01
  • 2016-09-27
  • 2018-02-05
  • 2018-06-11
  • 2021-07-01
相关资源
最近更新 更多