【问题标题】:Tell if file is an image using .Net framework, not by checking magic numbers判断文件是否是使用 .Net 框架的图像,而不是通过检查幻数
【发布时间】:2011-08-09 14:01:51
【问题描述】:

由于实际加载图像的所有智能都由 .net 框架完成,我似乎不必通过检查幻数或使用这样的 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)

【问题讨论】:

  • 至于框架为什么不这样做,请查看这篇文章,了解所有功能如何从 -100 点开始,并且与其他功能相比,人们必须证明他们的需求。 blogs.msdn.com/b/ericgu/archive/2004/01/12/57985.aspx
  • 我不认为这是一个特别的“黑客”。它使用了框架的所有智能,要完全复制会很棘手。
  • @jgauffin - 感谢您的评论 - 但在该帖子的答案中引用,“检查文件是否有已知的标题” - 这就是我所说的“神奇”数字。我不想编写代码和测试新的东西(答案的链接没有成熟/经过测试的 .net 示例)。
  • @Chris Haas - 你能不能只发布一个回答“不”的答案?我可能会继续使用我的“hack”,我不在乎类型。谢谢。

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2010-10-03
    • 2011-02-16
    • 2018-03-09
    • 2015-08-18
    • 2013-10-11
    • 1970-01-01
    • 1970-01-01
    • 2014-04-20
    • 1970-01-01
    相关资源
    最近更新 更多