Out of memory exception while loading images

12,252

Documentation for Image.FromFile (which is related to your FromStream) says that it will throw OutOfMemoryException if the file is not a valid image format or if GDI+ doesn't support the pixel format. Is it possible you're trying to load an unsupported image type?

Also, documentation for Image.FromStream says that you have to keep the stream open for the lifetime of the image, so even if your code loaded the image you'd probably get an error because you're closing the file while the image is still active. See http://msdn.microsoft.com/en-us/library/93z9ee4x.aspx.

Share:
12,252
OrElse
Author by

OrElse

Updated on June 04, 2022

Comments

  • OrElse
    OrElse almost 2 years

    I am using the following piece of code to load images as thumbnails to a FlowLayoutPanel control. Unfortunately i get an OutOfMemory exception.

    As you already guess the memory leak is found at line

     Pedit.Image = System.Drawing.Image.FromStream(fs)
    

    So how could i optimize the following code?

     Private Sub LoadImagesCommon(ByVal FlowPanel As FlowLayoutPanel, ByVal fi As FileInfo)
            Pedit = New DevExpress.XtraEditors.PictureEdit
            Pedit.Width = txtIconsWidth.EditValue
            Pedit.Height = Pedit.Width / (4 / 3)
            Dim fs As System.IO.FileStream
            fs = New System.IO.FileStream(fi.FullName, IO.FileMode.Open, IO.FileAccess.Read)
            Pedit.Image = System.Drawing.Image.FromStream(fs)
            fs.Close()
            fs.Dispose()
            Pedit.Properties.SizeMode = DevExpress.XtraEditors.Controls.PictureSizeMode.Zoom
    
            If FlowPanel Is flowR Then
                AddHandler Pedit.MouseClick, AddressOf Pedit_MouseClick
                AddHandler Pedit.MouseEnter, AddressOf Pedit_MouseEnter
                AddHandler Pedit.MouseLeave, AddressOf Pedit_MouseLeave
            End If
    
            FlowPanel.Controls.Add(Pedit)
        End Sub
    

    Update: The problem occurs while loading a number of images (3264x2448px at 300dpi - each image is about 3Mb's)