drawing PNG images with GDI+ causes out of memory exception

JosP
JosP used Ask the Experts™
on
I'm trying to draw PNG images in the OnPaint event of a usercontrol I created.
The files are loaded from disk into an ArrayList using Image.FromFile.
I get very unexpected results, sometimes loading the ArrayList produces an error, other times the application crashes in the OnPaint event. The files are quite small: 5MB at the most, in total no more than 50MB is loaded. The error is always OutOfMemoryException.

When I convert the PNG's beforehand to Bitmaps, the size of course increases dramatically, to several hundred MB. This however works brilliantly, no errors and even acceptable performance. But I can't the bitmaps because I need the transparency of the PNG format. And for other reasons too I have to use the PNG's.

What's wrong with PNG and GDI+?
Any pointers appreciated.

VB.NET, Visual Studio 2005, .NET 2.0
Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)
        Try
            If Not mImageList Is Nothing Then
                e.Graphics.TranslateTransform(AutoScrollPosition.X, AutoScrollPosition.Y)
                e.Graphics.MultiplyTransform(Transform)
                For i As Integer = 0 To mImageList.Count - 1
                    e.Graphics.DrawImage(CType(mImageList.Item(i), Image), 0, 0)
                Next
            End If
        Catch ex As Exception
            Windows.Forms.MessageBox.Show(ex.ToString)
        End Try
    End Sub

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
Turned out I wasn't freeing resources correctly. Between the consecutive calls to Drawimage the Image object has to be disposed.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial