Or Betzalel
Or Betzalel

Reputation: 2597

Out Of Memory Exception

I have function that creates an animated gif, it always worked perfectly but now when all my gifs are black and white, it gives an OutOfMemory Exception On :

e.AddFrame(Image.FromFile(imageFilePaths[i]));

My Function :

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 Function :

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

Upvotes: 1

Views: 346

Answers (2)

Jim Mischel
Jim Mischel

Reputation: 134035

Documentation for Image.FromFile says that it will throw OutOfMemoryException if the file does not contain a valid image, or if the image is in a format that GDI+ doesn't support.

What happens if you rewrite your code to:

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

If you get the exception on the call to Image.FromFile, it's because your image can't be loaded.

Upvotes: 3

Nick Randell
Nick Randell

Reputation: 18305

I don't know the details, but this doesn't look write. There are no 'usings' so you possibly aren't disposing of resources.

Upvotes: 0

Related Questions