Question

I have the following code which I am using to populate a ImageList from a SQLite database with images stored as blobs.

Public Sub populateImagesStyles()

    ShoeImages1.Images.Clear()
    StyleImagesLView.Items.Clear()

    Dim s As SQLiteDataReader
    Dim rcount As Integer = 0
    dbLocalQuery = New SQLiteCommand("SELECT id, image FROM tblImages", dbLocal)
    s = dbLocalQuery.ExecuteReader()

    While s.Read()
        rcount += 1
        ShoeImages1.Images.Add(CStr(s("id")), byte2img(s("image")))
        StyleImagesLView.Items.Add(CStr(s("id")), CStr(s("id")))

    End While
    s.Close()

Here is the byte2img function...

Public Function byte2img(ByVal imgByte As Byte()) As Image
    Dim imgMemoryStream As System.IO.MemoryStream = New System.IO.MemoryStream(imgByte)
    byte2img = Drawing.Image.FromStream(imgMemoryStream)
End Function

The database contains over 250 images and this process is completed twice on load to populate two different ImageList, because I need the images displayed at two different sizes.

When the process runs on loading the form, it causes the process to consume between 800MB and 1GB of system memory, unless I manually run the process again from an form control, which seems to trigger garbage collection.

Stepping through the loading process, it is clear that it is the byte2img process that is causing the memory usage to escalate - what is the best way to mitigate this?

Also, if anyone can think of a more efficient process to execute this, i'm all ears. The images have to be stored in the database file because I need to be able to just package the .db file and send it to a remote location at a moments notice, so I can't mess with folders with images.

All help appreciated.

Was it helpful?

Solution 2

Ok, I've found a solution/workaround that seems to work - call the PopulateImageStyles sub when a user visits the specific TabPage the ImageList resides on.

For some arbitrary reason, when run this way (as above, when called on the form), the process never proceeds to consume more than 50-60 MB of working memory.

I'll add a Background Worker so that the process can execute without hanging the form.

OTHER TIPS

You are creating a lot of memory streams without disposing of them. Try this:

Public Function byte2img(ByVal imgByte As Byte()) As Image
   Dim img As Image

   Try
        Using ms As New MemoryStream(imgbyte)
            img = Drawing.Image.FromStream(ms)
        End Using      ' auto dispose of the MS
    Catch ex As Exception
         ' report possibly bad/missing imgByte()
         ' resulting in an error in either place
    End Try

    Return img
End Function

An imprecise way to detect this kind of thing is to watch the HANDLES count in TaskManager.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top