简体   繁体   English

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

[英]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? 如何查看图像文件?

Here's the VB.NET equivalent of 0xA3's answer since the OP insisted on a VB version. 这是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

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. 任何人都可以使用.jpg扩展名保存不同的文件(例如文本文档),并诱骗你的应用程序获得它是一个图像。

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. 最好的方法是使用上面的函数加载图像或打开前几个字节并检查JPEG签名。



You can find more information about JPEG files and their headers here: 您可以在此处找到有关JPEG文件及其标题的更多信息:

A very primitive check is to simply try to load the image. 一个非常原始的检查是简单地尝试加载图像。 If it is not valid an OutOfMemoryException will be thrown: 如果它无效,则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;
}

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. 因此,简单地将加载操作包装在try / catch块中并不意味着任何额外的开销。 For the VB.NET solution of this approach check the answer by @Alex Essilfie. 对于这种方法的VB.NET解决方案,请查看@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: 那些想知道为什么Image.FromFile在无效文件上抛出OOM的人应该阅读Hans Passant对以下问题的回答:

Is there a reason Image.FromFile throws an OutOfMemoryException for an invalid image format? 是否有一个原因Image.FromFile为无效的图像格式抛出OutOfMemoryException?

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: 更好的是,正如SLC在评论中建议的那样,设置对话框的Filter属性:

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. 这不是一个保证 - 理想情况下你想检查文件本身以验证它是一个图像,理论上你也应该能够加载具有异常扩展的文件,如果它们实际上是图像文件(可能只是要求用户首先确认) - 但这是一个简单的开始。

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. 如果您打算更改或移动文件,VB和C#的答案很棒,但也包含“陷阱”:创建的'img'对象将锁定图像文件,除非调用dispose()方法释放它。 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;
}

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. 例如,JPEG具有特定的标题格式。

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. 163的回答应该可以帮助你完成这些方面的大部分工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM