Find image format using Bitmap object in C#

后端 未结 11 2508
半阙折子戏
半阙折子戏 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:10

    Agent CK, I liked your extension method and added a string overload, plus I reduced the code for your method:

    public static class ImageExtentions
    {
        public static ImageCodecInfo GetCodecInfo(this Image img) =>
            ImageCodecInfo.GetImageDecoders().FirstOrDefault(decoder => decoder.FormatID == img.RawFormat.Guid);
    
        // Note: this will throw an exception if "file" is not an Image file
        // quick fix is a try/catch, but there are more sophisticated methods
        public static ImageCodecInfo GetCodecInfo(this string file)
        {
            using (var img = Image.FromFile(file))
                return img.GetCodecInfo();
        }
    }
    
    // Usage:
    string file = @"C:\MyImage.tif";
    string description = $"Image format is {file.GetCodecInfo()?.FormatDescription ?? "unknown"}.";
    Console.WriteLine(description);
    

提交回复
热议问题