内存异常

时间:2011-05-27 19:09:40

标签: c# pixel gif screen-capture

我有一个创建动画gif的功能,它总是很完美但现在当我的所有GIF都是黑白时,它会给出OutOfMemory异常:

  

e.AddFrame(Image.FromFile(imageFilePaths [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;
    }

AddFrame功能:

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;
    }

2 个答案:

答案 0 :(得分:3)

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

如果您将代码重写为:

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

如果您在调用Image.FromFile时遇到异常,那是因为无法加载您的图片。

答案 1 :(得分:0)

我不知道细节,但这看起来并不像。没有'使用',所以你可能没有处理资源。