Find image format using Bitmap object in C#

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

    here is my code for this. You have to load the complete image or the header (first 4 bytes) to a byte array first.

    public enum ImageFormat
    {
        Bmp,
        Jpeg,
        Gif,
        Tiff,
        Png,
        Unknown
    }
    
    public static ImageFormat GetImageFormat(byte[] bytes)
    {
        // see http://www.mikekunz.com/image_file_header.html  
        var bmp    = Encoding.ASCII.GetBytes("BM");     // BMP
        var gif    = Encoding.ASCII.GetBytes("GIF");    // GIF
        var png    = new byte[] { 137, 80, 78, 71 };    // PNG
        var tiff   = new byte[] { 73, 73, 42 };         // TIFF
        var tiff2  = new byte[] { 77, 77, 42 };         // TIFF
        var jpeg   = new byte[] { 255, 216, 255, 224 }; // jpeg
        var jpeg2  = new byte[] { 255, 216, 255, 225 }; // jpeg canon
    
        if (bmp.SequenceEqual(bytes.Take(bmp.Length)))
            return ImageFormat.Bmp;
    
        if (gif.SequenceEqual(bytes.Take(gif.Length)))
            return ImageFormat.Gif;
    
        if (png.SequenceEqual(bytes.Take(png.Length)))
            return ImageFormat.Png;
    
        if (tiff.SequenceEqual(bytes.Take(tiff.Length)))
            return ImageFormat.Tiff;
    
        if (tiff2.SequenceEqual(bytes.Take(tiff2.Length)))
            return ImageFormat.Tiff;
    
        if (jpeg.SequenceEqual(bytes.Take(jpeg.Length)))
            return ImageFormat.Jpeg;
    
        if (jpeg2.SequenceEqual(bytes.Take(jpeg2.Length)))
            return ImageFormat.Jpeg;
    
        return ImageFormat.Unknown;
    }
    

提交回复
热议问题