C#获取图片的后缀名
要说,这也是一个很简单的功能,没必要开一篇博客这么大动干戈。 对于一张知道全路径的照片,如果其路径包含后缀名的话,要取得后缀名,只需要一行代码即可:
1 | var ext = System.IO.Path.GetExtension( "C:\\soar.jpg" ); |
可是,如果这个文件的文件名不包含后缀怎么办? 在C#中并没有提供直接获取图片格式的方法,如果想根据图片(也就是Image对象)获取图片格式,那么就需要另辟蹊径了。 首先,我们可以在`Image`对象中看到一个类型为`ImageFormat`的`RawFormat`属性。但是,通过这个属性,我们只能取到这个图片格式的Guid,而无法取到具体的名称。不过,在`ImageFormat`类中采用静态属性的方式罗列了几个常用的图片格式,有了这些,我们就可以通过“一一对照”的方式来拿到一张图片具体的后缀名了。 首先,我们需要得到在`ImageFormat`中罗列出来的图片格式。硬编码是一个很蠢的主意,所以,我们采用反射取值。
1 2 3 4 5 6 7 8 9 10 11 12 | private static Dictionary<String, ImageFormat> GetImageFormats() { var dic = new Dictionary<String, ImageFormat>(); var properties = typeof (ImageFormat).GetProperties(BindingFlags.Static | BindingFlags.Public); foreach ( var property in properties) { var format = property.GetValue( null , null ) as ImageFormat; if (format == null ) continue ; dic.Add(( "." + property.Name).ToLower(), format); } return dic; } |
通过上面的代码,我们就能取到“图片后缀”和ImageFormat实例的对应关系。需要注意的是,对于jpg格式,这里取到的是jpeg。反射的效率很低,所以我们需要将产生的结果缓存起来。
1 2 3 4 5 6 7 8 9 10 11 | private static Dictionary<String, ImageFormat> _imageFormats; /// <summary> /// 获取 所有支持的图片格式字典 /// </summary> public static Dictionary<String, ImageFormat> ImageFormats { get { return _imageFormats ?? (_imageFormats = GetImageFormats()); } } |
采用按需加载,减少启动时间。不过,如果你是多线程环境,最好能够加个锁。剩下的事情就好办了,循环这个字典,对比字典值的Guid,返回字典的键就可以。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | /// <summary> /// 根据图像获取图像的扩展名 /// </summary> /// <param name="image"></param> /// <returns></returns> public static String GetExtension(Image image) { foreach ( var pair in ImageFormats) { if (pair.Value.Guid == image.RawFormat.Guid) { return pair.Key; } } throw new BadImageFormatException(); } |
使用方法:
1 2 3 4 | using ( var img = Image.FromFile( @"C:\soar" )) { var ext = GetExtension(img); } |
本文来自 16℃·夏 原文地址 : http://www.sum16.com/desinger/c-sharp-get-image-file-extension.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?