在VB.NET中检查文件类型?

Mos*_*she 3 vb.net validation file-type image

我有一个图像调整大小的程序,它的工作原理.问题是当用户在文件选择对话框中选择非图像文件时,它会崩溃.如何查看图像文件?

Ale*_*fie 7

这是VB.NET相当于0xA3的答案,因为OP坚持使用VB版本.

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
Run Code Online (Sandbox Code Playgroud)

您可以按如下方式使用它:

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

编辑:
我不建议您检查文件扩展名.任何人都可以使用.jpg扩展名保存不同的文件(例如文本文档),并诱骗您使应用程序成为一个图像.

最好的方法是使用上面的函数加载图像或打开前几个字节并检查JPEG签名.



您可以在此处找到有关JPEG文件及其标题的更多信息:


Dir*_*mar 5

一个非常原始的检查是简单地尝试加载图像.如果它无效,OutOfMemoryException将抛出:

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;
}
Run Code Online (Sandbox Code Playgroud)

如果我正确地理解了你的问题你的应用程序无论如何都会加载图像.因此,简单地将加载操作包装在try/catch块中并不意味着任何额外的开销.对于这种方法的VB.NET解决方案,请查看@Alex Essilfie的答案.

那些想知道为什么Image.FromFile在无效文件上抛出OOM的人应该阅读Hans Passant对以下问题的回答:

是否有一个原因Image.FromFile为无效的图像格式抛出OutOfMemoryException?