星空网 > 软件开发 > 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 (#换成@)。

Youtube营销:https://www.goluckyvip.com/tag/10846.html
纵腾集团:https://www.goluckyvip.com/tag/10847.html
海关查验:https://www.goluckyvip.com/tag/10848.html
货值低:https://www.goluckyvip.com/tag/1085.html
出口美国:https://www.goluckyvip.com/tag/10850.html
EORI:https://www.goluckyvip.com/tag/10852.html
深圳有没有比较好玩的景点 深圳有没有比较好玩的景点推荐一下:https://www.vstour.cn/a/366175.html
长治婚庆女司仪和主持人:https://www.vstour.cn/a/366176.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流