Filetype check in VB.NET?

2020-07-22 18:09发布

问题:

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?

回答1:

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:

  • http://www.fastgraph.com/help/jpeg_header_format.html
  • http://en.wikipedia.org/wiki/JPEG


回答2:

A very primitive check is to simply try to load the image. If it is not valid an OutOfMemoryException will be thrown:

static bool IsImageValid(string filename)
{
    try
    {
        System.Drawing.Image img = System.Drawing.Image.FromFile(filename);
    }
    catch (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;
    }
    return true;
}

If I understood your question correctly your application it going to load the image anyway. Therefore simply wrapping the load operation in a try/catch block does not mean any additional overhead. For the VB.NET solution of this approach check the answer by @Alex Essilfie.

The ones wondering why Image.FromFile is throwing an OOM on invalid files should read the answer of Hans Passant to the following question:

Is there a reason Image.FromFile throws an OutOfMemoryException for an invalid image format?



回答3:

Your first line of defense, of course, would be simply to check the file's extension:

Function IsImageFile(ByVal filename As String) As Boolean
    Dim ext As String = Path.GetExtension(filename).ToLowerInvariant()

    ' This supposes your program can deal only with JPG files; '
    ' you could add other extensions here as necessary. '
    Return ext = ".jpg" OrElse ext = ".jpeg"
End Function

Better yet, as SLC suggests in a comment, set your dialog's Filter property:

dialog.Filter = "Image files|*.jpg;*.jpeg"

This isn't a guarantee -- ideally you'd want to check the file itself to verify it's an image, and theoretically you should also be able to load files with anomalous extensions if they are in fact image files (maybe just ask for the user's acknowledgement first) -- but it's an easy start.



回答4:

The VB and C# answers are great but also contain a "gotcha" if you plan to alter or move the file: the created 'img' object will lock the image file unless the dispose() method is invoked to release it. See below:

VB
    Function IsValidImage(filename As String) As Boolean
    Try
        Dim img As System.Drawing.Image = System.Drawing.Image.FromFile(filename)
        img.dispose()  ' Removes file-lock of IIS
    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

C#
static bool IsImageValid(string filename)
{
    try
    {
        System.Drawing.Image img = System.Drawing.Image.FromFile(filename);
        img.dispose();   // Removes file-lock of IIS
    }
    catch (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;
    }
    return true;
}


回答5:

The most robust way would be to understand the signatures of the files you need to load.

JPEG has a particular header format, for example.

This way your code won't be as easily fooled if you just look at the extension.

163's answer should get you most of the way along these lines.