C# 内存不足异常

C# 内存不足异常,c#,pixel,gif,screen-capture,C#,Pixel,Gif,Screen Capture,我有一个创建动画gif的功能,它总是工作得很好,但现在当我所有的gif都是黑白的时候,它会在以下方面出现OutOfMemory异常: e、 AddFrame(Image.FromFile(imagefilepath[i]) 我的职能: public void MakeGif(string sourcefolder, string destinationgif) { IsGifing = true; string path = MainForm.RootDi

我有一个创建动画gif的功能,它总是工作得很好,但现在当我所有的gif都是黑白的时候,它会在以下方面出现OutOfMemory异常:

e、 AddFrame(Image.FromFile(imagefilepath[i])

我的职能:

public void MakeGif(string sourcefolder, string destinationgif)
    {
        IsGifing = true;
        string path = MainForm.RootDirectory;
        String[] imageFilePaths = Directory.GetFiles(path);
        String outputFilePath = MainForm.RootDirectory + @"\Final.gif";
        AnimatedGifEncoder e = new AnimatedGifEncoder();
        e.Start(outputFilePath);
        e.SetDelay(300);
        //-1:no repeat,0:always repeat

        e.SetRepeat(0);
        for (int i = 0, count = imageFilePaths.Length; i < count; i++)
            e.AddFrame(Image.FromFile(imageFilePaths[i]));
        e.Finish();
        IsGifing = false;
    }
public bool AddFrame(Image im) 
    {
        if ((im == null) || !started) 
        {
            return false;
        }
        bool ok = true;
        try 
        {
            if (!sizeSet) 
            {
                // use first frame's size
                SetSize(im.Width, im.Height);
            }
            image = im;
            GetImagePixels(); // convert to correct format if necessary
            AnalyzePixels(); // build color table & map pixels
            if (firstFrame) 
            {
                WriteLSD(); // logical screen descriptior
                WritePalette(); // global color table
                if (repeat >= 0) 
                {
                    // use NS app extension to indicate reps
                    WriteNetscapeExt();
                }
            }
            WriteGraphicCtrlExt(); // write graphic control extension
            WriteImageDesc(); // image descriptor
            if (!firstFrame) 
            {
                WritePalette(); // local color table
            }
            WritePixels(); // encode and write pixel data
            firstFrame = false;
        } 
        catch (IOException e) 
        {
            ok = false;
        }

        return ok;
    }

我不知道细节,但这看起来不像是在写。没有“使用”,因此您可能没有处理资源。

的文档说明,如果文件不包含有效图像,或者图像的格式不受GDI+支持,它将抛出
OutOfMemoryException

如果将代码重写为:

for (int i = 0, count = imageFilePaths.Length; i < count; i++)
{
    var img = Image.FromFile(imageFilePaths[i]);
    e.AddFrame(img);
}
for(int i=0,count=imagefilepath.Length;i

如果调用
Image.FromFile
时出现异常,那是因为无法加载图像。

谢谢,我会找到另一种加载方法。喂,你怎么知道的?你刚刚检查了我所有的函数是否有OOM异常,或者你碰巧知道这个问题吗?@或者贝扎尔:我不必检查你所有的函数。你说它死在那一行,所以只有两种可能性。调试的一个基本规则是将事情分解为最简单的步骤,因此我首先考虑的是
Image.FromFile
是否可以抛出
OutOfMemoryException
。噢,我从来没有想到OutOfMemory异常可以由不受支持的文件格式抛出。谢谢,下次我会记住的谢谢你的回答。注意:这不是因为黑白GIF,我看错了文件夹,试图添加一个.txt文件>\uu>