星空网 > 软件开发 > ASP.net

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);
}






原标题:C#获取图片的后缀名

关键词:C#

C#
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

Chris说侵权:https://www.goluckyvip.com/tag/1130.html
店铺定位:https://www.goluckyvip.com/tag/11300.html
发展趋势:https://www.goluckyvip.com/tag/11301.html
跨境电商形势:https://www.goluckyvip.com/tag/11303.html
跨境外贸人:https://www.goluckyvip.com/tag/11304.html
快速消费品:https://www.goluckyvip.com/tag/11305.html
独家丨B站广告位可跳转美团APP B站为电商平台引流再升级 :https://www.kjdsnews.com/a/1836410.html
百崖大峡谷生态旅游景区(探秘中国西南自然风光):https://www.vstour.cn/a/363176.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流