Preventing Image.FromFile exception in VB 2022 when the file does not have a valid image format

Ron Sipherd 276 Reputation points
2025-04-23T16:47:11.57+00:00
The Visual Basic 2022 Image.FromFile method throws an​ OutOfMemoryException if the file does not have a valid image format. 
Is there a way to determine in advance whether the candidate file​ has a "valid image format"?
At present I'm using a Try...Catch block, but would prefer an​ alternative. 
The help file says "This type of OutOfMemoryException exception represents a catastrophic failure. If you choose to handle the exception, you should include a catch block that calls the Environment.FailFast method to terminate your app"
That's pretty drastic, would like to forestall it.
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,837 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Castorix31 88,871 Reputation points
    2025-04-24T18:11:38.5333333+00:00

    You can check image formats with "Magic Numbers"

    I did this test, with the help of ChatGPT =>

      Class ByteArrayComparer
            Implements IEqualityComparer(Of Byte())
    
            Public Shadows Function Equals(x() As Byte, y() As Byte) As Boolean Implements IEqualityComparer(Of Byte()).Equals
                Return x.SequenceEqual(y)
            End Function
    
            Public Shadows Function GetHashCode(obj() As Byte) As Integer Implements IEqualityComparer(Of Byte()).GetHashCode
                Dim hash As Long = 17
                For Each b In obj
                    hash = hash * 31 + b
                Next
                Return hash And &H7FFFFFFF ' truncate safely to positive 32-bit integer
            End Function
    
        End Class
    
        Function IsSupportedImageFormat(path As String, ByRef format As String) As Boolean
            format = Nothing
    
            Dim signatures As New Dictionary(Of Byte(), String)(New ByteArrayComparer) From {
            {New Byte() {&HFF, &HD8, &HFF}, "JPEG"},
            {New Byte() {&H89, &H50, &H4E, &H47, &HD, &HA, &H1A, &HA}, "PNG"},
            {System.Text.Encoding.ASCII.GetBytes("GIF87a"), "GIF"},
            {System.Text.Encoding.ASCII.GetBytes("GIF89a"), "GIF"},
            {System.Text.Encoding.ASCII.GetBytes("BM"), "BMP"},
            {New Byte() {&H49, &H49, &H2A, &H0}, "TIFF (LE)"},
            {New Byte() {&H4D, &H4D, &H0, &H2A}, "TIFF (BE)"},
            {New Byte() {&H0, &H0, &H1, &H0}, "ICO"},
            {New Byte() {&HD7, &HCD, &HC6, &H9A}, "WMF"}
        }
    
            Try
                Using fs As New FileStream(path, FileMode.Open, FileAccess.Read)
                    Dim buffer(255) As Byte
                    fs.Read(buffer, 0, buffer.Length)
    
                    ' Detect standard formats
                    For Each kvp In signatures
                        Dim sig = kvp.Key
                        Dim name = kvp.Value
    
                        If buffer.Take(sig.Length).SequenceEqual(sig) Then
                            format = name
                            Return True
                        End If
                    Next
                   
                    ' Detect EMF (look for EMR_HEADER at the beginning and optional " EMF" string at offset 40)
                    If buffer.Length >= 44 AndAlso buffer(0) = &H1 AndAlso buffer(1) = 0 AndAlso buffer(2) = 0 AndAlso buffer(3) = 0 Then
                        ' Optional check for " EMF" at offset 40
                        If buffer(40) = Asc(" ") AndAlso buffer(41) = Asc("E") AndAlso buffer(42) = Asc("M") AndAlso buffer(43) = Asc("F") Then
                            format = "EMF"
                            Return True
                        Else
                            ' Still likely EMF without " EMF" string
                            format = "EMF"
                            Return True
                        End If
                    End If
                End Using
            Catch
                format = Nothing
                Return False
            End Try
    
            Return False
        End Function
    
    
    0 comments No comments

  2. Ron Sipherd 276 Reputation points
    2025-04-24T19:07:55.15+00:00

    Thanks for your response.

    I have learned a good deal since I posted the question.

    Other apps (IrfanView, Photoshop) are able to open and display the image files that Image.FromFile and MS Photo Viewer cannot.

    I opened one file in PS Elements and saved it with a new name; VB and Photo Viewer can read and display it.

    I will take a good look at your code and may incorporate it in my app, but it looks as if the Microsoft software is falsely reporting corruption in good files.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.