Find image format using Bitmap object in C#

后端 未结 11 2523
半阙折子戏
半阙折子戏 2020-11-29 19:50

I am loading the binary bytes of the image file hard drive and loading it into a Bitmap object. How do i find the image type[JPEG, PNG, BMP etc] from the Bitmap object?

11条回答
  •  盖世英雄少女心
    2020-11-29 20:06

    The simplest method was offered by Cesare Imperiali as this:

    var format = new ImageFormat(Image.FromFile(myFile).RawFormat.Guid);
    

    However, the .ToString() for a .jpg returns "[ImageFormat: b96b3cae-0728-11d3-9d7b-0000f81ef32e]" instead of "Jpeg". If that matters to you, here is my solution:

    public static class ImageFilesHelper
    {
        public static List ImageFormats =>
            typeof(ImageFormat).GetProperties(BindingFlags.Static | BindingFlags.Public)
              .Select(p => (ImageFormat)p.GetValue(null, null)).ToList();
    
        public static ImageFormat ImageFormatFromRawFormat(ImageFormat raw) =>
            ImageFormats.FirstOrDefault(f => raw.Equals(f)) ?? ImageFormat.Bmp;
    
    }
    // usage:
    var format = ImageFilesHelper.ImageFormatFromRawFormat(Image.FromFile(myFile).RawFormat);
    

提交回复
热议问题