How to use C # to get image format without system. Drawing. Common

I wrote a blog to get the correct format of the picture. The code shown in the blog has been working well. Until today, when deploying the program to alicloud function computing, the following error occurred:

System.Drawing is not supported on this platform.

This shows that we can’t use GDI + related functions on the alicloud function computing server. Even so, we can still get the image format by reading the file header

   public static class ImageHelper
    {
        public enum ImageFormat
        {
            Bmp,
            Jpeg,
            Gif,
            Tiff,
            Png,
            Unknown
        }


        public static ImageFormat GetImageFormat(byte[] bytes)
        {
            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;
        }
    }

new  ImageHelper   You need a binary array as a parameter, but that doesn’t mean you need to read all the contents of the file into memory. Using the following code can get better running effect:

    var fn = @"D:\1.jpg";
    using (var fs = File.OpenRead(fn))
    {
        var header = new byte[10];
        await fs.ReadAsync(header, 0, 10);
        var ext = ImageHelper.GetImageFormat(header);
        ext.Dump();
    }


Read More: