C # Get the image suffix,
This is also a very simple function, so it is not necessary to open a blog. For a photo that knows the full path, if its path contains a suffix, you only need a line of code to get the Suffix:
1 |
var ext = System.IO.Path.GetExtension( "C:\\soar.jpg" ); |
However, what if the file name does not contain a suffix? In C #, there is no way to directly obtain the Image format. If you want to obtain the Image format based on the Image (that is, the Image object), you need to find another way. First, we can see a 'rawformat' attribute of the 'imageformat' type in the 'image' object. However, with this attribute, we can only get the Guid in the image format, but cannot get the specific name. However, the 'imageformat' class uses static attributes to list several common image formats, we can get the specific Suffix of an image through "one-to-one comparison. First, we need to get the image format listed in 'imageformat. Hard coding is a silly idea, so we use reflection values.
123456789101112 |
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; } |
Through the above code, we can get the correspondence between the "image suffix" and the ImageFormat instance. Note that for jpg format, jpeg is obtained here. Reflection efficiency is very low, so we need to cache the generated results.
1234567891011 |
private static Dictionary<String, ImageFormat> _imageFormats; /// <summary> /// Obtain all supported image format dictionaries /// </summary> public static Dictionary<String, ImageFormat> ImageFormats { get { return _imageFormats ?? (_imageFormats = GetImageFormats()); } } |
Load as needed to reduce the startup time. However, if you are in a multi-threaded environment, you 'd better apply a lock. The rest is easy. loop through this dictionary and compare the Guid of the dictionary value to return the dictionary key.
12345678910111213141516 |
/// <summary> /// Obtain the image extension based on the Image /// </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(); } |
Usage:
1234 |
using ( var img = Image.FromFile( @"C:\soar" )) { var ext = GetExtension(img); } |