Search code examples
vb.netimagevalidationfile-type

Filetype check in VB.NET?


I have an image resized program and it works. The problem is when a user selects a non-image file in the file select dialog, it crashes. How can I check for image files?


Solution

  • UPDATE: 2022-04-05

    Since it may not be feasible to validate the binary structure of every supported image, the fastest way to check if a file contains an image is to actually load it. If it loads successfully, then it is valid. If it doesn't then it is not.

    The code below can be used to check if a file contains a valid image or not. This code is updated to prevent locking the file while the method is called. It also handles resource disposal after the tests (thanks for pointing out this issue user1931470).

    Public Function IsValidImage(fileName As String) As Boolean
        Dim img As Drawing.Image = Nothing
        Dim isValid = False
    
        Try
            ' Image.FromFile locks the file until the image is disposed.
            ' This might not be the wanted behaviour so it is preferable to
            ' open the file stream and read the image from it.
            Using stream = New System.IO.FileStream(fileName, IO.FileMode.Open)
                img = Drawing.Image.FromStream(stream)
                isValid = True
            End Using
    
        Catch oome As OutOfMemoryException
            ' Image.FromStream throws an OutOfMemoryException
            ' if the file does not have a valid image format.
            isValid = False
    
        Finally
            ' clean up resources
            If img IsNot Nothing Then img.Dispose()
        End Try
    
        Return isValid
    End Function
    

    ORIGINAL ANSWER


    ⚠️⚠️ WARNING ⚠️⚠️

    This code has a bug that causes a high memory consumption when called several times in a program's lifetime.

    DO NOT USE THIS CODE!!

    Here's the VB.NET equivalent of 0xA3's answer since the OP insisted on a VB version.

    Function IsValidImage(filename As String) As Boolean
        Try
            Dim img As System.Drawing.Image = System.Drawing.Image.FromFile(filename)
        Catch generatedExceptionName As OutOfMemoryException
            ' Image.FromFile throws an OutOfMemoryException  
            ' if the file does not have a valid image format or 
            ' GDI+ does not support the pixel format of the file. 
            ' 
            Return False
        End Try
        Return True
    End Function
    

    You use it as follows:

    If IsValidImage("c:\path\to\your\file.ext") Then
        'do something
        '
    Else
        'do something else
        '
    End If
    

    Edit:
    I don't recommend you check file extensions. Anyone can save a different file (text document for instance) with a .jpg extension and trick you app into beleiving it is an image.

    The best way is to load the image using the function above or to open the first few bytes and check for the JPEG signature.



    You can find more information about JPEG files and their headers here: