Find image format using Bitmap object in C#

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

    Not to bother to on old topic, but to complete this discussion, I want to share my way to query all image formats, known by windows.

    using System.Diagnostics;
    using System.Drawing;
    using System.Drawing.Imaging;
    
    public static class ImageExtentions
    {
        public static ImageCodecInfo GetCodecInfo(this System.Drawing.Image img)
        {
            ImageCodecInfo[] decoders = ImageCodecInfo.GetImageDecoders();
            foreach (ImageCodecInfo decoder in decoders)
                if (img.RawFormat.Guid == decoder.FormatID)
                    return decoder;
            return null;
        }
    }
    

    Now you can use it as an an image extension as shown below:

    public void Test(Image img)
    {
        ImageCodecInfo info = img.GetCodecInfo();
        if (info == null)
            Trace.TraceError("Image format is unkown");
        else
            Trace.TraceInformation("Image format is " + info.FormatDescription);
    }
    

提交回复
热议问题