Search code examples
vb.netlistviewmemory-managementimagelist

VB.NET Out of Memory Issue on ImageList


EDITED: I'm getting an "Out of Memory" error by loading images to an ImageList even when I put dispose() or End Using after adding bitmap to ImageList.

Here's my code.

Function loadImage()
    Dim item As New ListViewItem

    imageList.ImageSize = New Size(45, 70)

    For Each value In arr
        If System.IO.File.Exists(value) Then
            Using img As New Bitmap(value)
                imageList.Images.Add(Image.FromHbitmap(img.GetHbitmap))
            End Using
            newListView.LargeImageList = imageList
            item = New ListViewItem(value)
            newListView.Items.Add(item)
            item.Name = value
            item.Tag = System.IO.Path.GetDirectoryName(value)
            newListView.Items(item.Index).ImageIndex = item.Index
        End If
    Next

    newListView.View = View.LargeIcon
    Return Nothing
End Function

I have 96 values on arr consists of image path and only 82 of them gets to be displayed then the OOM error occured.

Maybe I misused the Using statement or anything. I hope you can help me with this. Thanks!


Solution

  • [SOLVED] Creating a copy of the image and resizing the copied image to a bitmap thumbnail size then adding it to the ImageList(). After adding, dispose the original image and the bitmap copy.

    I will post the code to help others who have the same issue.

        Dim item As New ListViewItem
    
        imageList.ImageSize = New Size(80, 100)
    
        For Each value In arr
            If System.IO.File.Exists(value) Then
                Dim buffer As Byte() = File.ReadAllBytes(value)
                Dim stream As MemoryStream = New MemoryStream(buffer)
    
                Dim myBitmap As Bitmap = CType(Bitmap.FromStream(stream), Bitmap)
                Dim pixelColor As Color = myBitmap.GetPixel(50, 80)
                Dim newColor As Color = Color.FromArgb(pixelColor.R, pixelColor.G, pixelColor.B)
    
                myBitmap.SetPixel(0, 0, newColor)
                myBitmap = myBitmap.GetThumbnailImage(80, 100, Nothing, IntPtr.Zero)
    
                imageList.Images.Add(Image.FromHbitmap(myBitmap.GetHbitmap))
    
                myBitmap.Dispose()
                stream.Dispose()
    
                newListView.LargeImageList = imageList
                item = New ListViewItem(value)
                newListView.Items.Add(item)
    
                newListView.Items(item.Index).ImageIndex = item.Index
            End If
        Next
    
        newListView.View = View.LargeIcon
    

    Where arr is the list of the image path directories.