c# - 使用 .Net 框架判断文件是否为图像,而不是通过检查魔数(Magic Number)

标签 c# .net vb.net gdi+ magic-numbers

通过 .net 框架完成实际加载图像的所有智能,似乎我不应该通过检查魔数(Magic Number)或使用像这样的 hack 在我的代码中重复这一切:

Private Function IsImage(FileName as String) As Boolean
    Try
        Using img As New Bitmap(FileName)
        End Using
    Catch ex as System.ArgumentException
        Return False
    End Try
    Return True
End Function

我是否遗漏了一些明显的东西,例如 System.Drawing.IsImage(stream)

最佳答案

您需要打开文件并阅读您想要支持的文件类型的相关标题,如下所述:

determine if file is an image

我认为 .NET 框架中没有任何东西可以为您做这件事,除了将它加载到图像中并查询图像格式:

Find image format using Bitmap object in C#

另一种理论(没有实际事实支持这一理论):Windows 中的文件可能包含将其标记为图像的元数据 - 其方式与属性对话框似乎显示音频文件的艺术家信息的方式相同。这可能是一种避免打开文件的好方法。

由 FastAl 编辑,2020 年 6 月。更有用的链接:

Using .NET, how can you find the mime type of a file based on the file signature not the extension

不是我要求的,但这是神奇的#s:

https://en.wikipedia.org/wiki/List_of_file_signatures

https://www.garykessler.net/library/file_sigs.html

关于c# - 使用 .Net 框架判断文件是否为图像,而不是通过检查魔数(Magic Number),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5732177/

相关文章:

vb.net - 我如何检查vb.net中的datagridview列中的复选框是否被选中

c# - 系统.IO.IOException : The handshake failed due to an unexpected > packet format?

c# 改变用户文化,相当于来自 powershell 的 Set-Culture

vb.net - 获取 vb.net 中对象引用的字符串表示形式

.net - 使用 excel 和 Visual Studio 2010 时出现 "Class not registered"错误

.net - 如何从资源字典继承/扩展样式?

c# - 快速文本阅读(替代 File.ReadAllText() 和/或 StreamReader.ReadToEnd())

c# - 用于管理 SQL 表中位置的算法

c# 检查列表是否包含现有元素(不为空)

c# - 从内存位置复制字节时是否需要固定结构