Search code examples
c#imageimage-formats

How can I know what image format I get from a stream?


I get a byte stream from some web service. This byte stream contains the binary data of an image and I'm using the method in C# below to convert it to an Image instance.

I need to know what kind of image I've got. Is it a simple bitmap (*.bmp) or a JPEG image (*.jpg) or a png image?

How can I find it out?

    public static Image byteArrayToImage( byte[] bmpBytes )
    {
        Image image = null;
        using( MemoryStream stream = new MemoryStream( bmpBytes ) )
        {
            image = Image.FromStream( stream );
        }

        return image;
    }

Solution

  • You may checkout the Image.RawFormat property. So once you load the image from the stream you could test:

    if (ImageFormat.Jpeg.Equals(image.RawFormat))
    {
        // JPEG
    }
    else if (ImageFormat.Png.Equals(image.RawFormat))
    {
        // PNG
    }
    else if (ImageFormat.Gif.Equals(image.RawFormat))
    {
        // GIF
    }
    ... etc