'c# BitmapImage to Bitmap converting out of memory error

I'm currently trying to convert a large image from BitmapImage -> Bitmap. On smaller files the conversion works great, the issue stems from trying to convert an image that is <5MB. After doing some reading I think I should be using some sort of buffer to populate the bitmap but not sure. Any point in the right direction would be helpful. Thanks!

Error message thrown:

'outStream.ReadTimeout' threw an exception of type 'System.InvalidOperationException'

/// <summary>
/// Convert a BitmapImage found in a Image.Source to a Bitmap
/// </summary>
/// <param name="bitmapImage"></param>
/// <returns></returns>
public static Bitmap BitmapImageToBitmap(BitmapImage bitmapImage)
{
    // Opens a stream to be used for the image conversion
    using (MemoryStream outStream = new MemoryStream())
    {
        // Grabs the encoder object to be used as a converter
        BitmapEncoder encoder = new BmpBitmapEncoder();

        // Adds the bitmap as a frame of the encoder (this adds the image as a 'page' for the bitmap image)
        BitmapFrame frame = BitmapFrame.Create(bitmapImage);
        encoder.Frames.Add(frame);

        // Saves the current set of frames (single page for now) to the stream
        encoder.Save(outStream);
        encoder.Frames.Clear();
        encoder = null;
        frame = null;
        // Initialize a new Bitmap image using the stream
        return new Bitmap(outStream);         <--- This is where the error is thrown
    }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source