使用.Net框架判断文件是否是图像,而不是通过检查幻数
由于实际加载图像的所有智能都是由 .net 框架完成的,似乎我不必在代码中通过检查幻数或使用这样的黑客来重复这一切:
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)
?
With all the smarts of actually loading images being done by the .net framework, seems like I shouldn't have to repeat it all in my code by checking for magic numbers, or using a hack like this:
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
Am I missing something obvious, like System.Drawing.IsImage(stream)
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要打开文件并读取您想要支持的文件类型的相关标头,如下所述:
确定文件是否是图像
我认为 .NET 框架中除了将其加载到图像中并查询图像格式之外,没有任何东西可以为您执行此操作:
在 C# 中使用 Bitmap 对象查找图像格式
另一种理论 (没有实际事实来支持这一点):也许 Windows 中的文件包含将其标记为图像的元数据 - 与属性对话框似乎显示音频文件的艺术家信息的方式相同。这可能是避免打开文件的一个可爱的方法。
由 FastAl 2020 年 6 月编辑。更多有用链接:
使用.NET,如何根据文件签名而不是扩展名找到文件的 mime 类型
不是我要求的,但这里有神奇的 # s:
https://en.wikipedia.org/wiki/List_of_file_signatures
https://www.garykessler.net/library/file_sigs.html
You will need to open up the file and read the relevant headers for the file types you want to support, as mentioned here:
determine if file is an image
I don't think there is anything already in the .NET framework that can do this for you, other than loading it into an image and querying the image format:
Find image format using Bitmap object in C#
An alternative theory (no actual facts to back this one up): perhaps the file in Windows holds meta-data that flags it as an image - in the same manner than the properties dialog seems to show artist information for audio files. This could be a cute way to avoid opening the file.
Edit by FastAl Jun 2020. More useful links:
Using .NET, how can you find the mime type of a file based on the file signature not the extension
Not what I asked for, but here are the magic #s:
https://en.wikipedia.org/wiki/List_of_file_signatures
https://www.garykessler.net/library/file_sigs.html