通过 .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)
?
最佳答案
您需要打开文件并阅读您想要支持的文件类型的相关标题,如下所述:
我认为 .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:
关于c# - 使用 .Net 框架判断文件是否为图像,而不是通过检查魔数(Magic Number),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5732177/