Link to home
Start Free TrialLog in
Avatar of GIANTOCR

asked on

Windows Mobile Picturebox OutOfMemoryException - How can I check image file size before loading

I am building an application in VS 2008 using Visual Basic. It is for a windows mobile device. The application allows the user to load an image file into a picturebox. The code below works well for image files (tested using jpeg) up to about 150 kB. When I try to load some image files that are about 500 kB in size I receive an "OutOfMemoryException" that crashes the application.

Is there any way to check the image file size before I attempt to load it into the PictureBox? I would like to check the image file size before loading, and if it is above a certain size not try to load it.


Private Sub LoadImageFile(ByVal ImageFileName As String)

        Dim imagename As String = Module1.ImageFileLocation & ImageFileName

            If ImageFileName <> String.Empty Then

                If System.IO.File.Exists(imagename) = True Then
                    Dim fs As New System.IO.FileStream(imagename, IO.FileMode.Open)
                    Dim img As Image = New Bitmap(fs)
                    MyControl1.PictureBox1.Image = img
                    MyControl1.PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
                    MsgBox("Image File Not Found")
                End If

            End If
        Catch ex As IOException
            MessageBox.Show("Failed to open image file. File may be in use by another application or corrupted.")
        End Try

    End Sub

Open in new window

Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of GIANTOCR


Thanks, that got me in the right direction. The following code worked:

Dim fi As FileInfo = New FileInfo(imagename)
If fi.Length < 150000 Then
End If