c# Detect Image type and height and width

Often, I need this code, because you never can assume mimetype (which is, image/jpeg image/png etc) because the extension says so.

This piece of code might help you too. It uses the well known SixLabors library.


using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats;
using SixLabors.ImageSharp.Formats.Gif;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp.Formats.Png;
using SixLabors.ImageSharp.Formats.Tga;
using System;
using System.IO;
using System.Threading.Tasks;

namespace ADCCure
{
     public static class ImageHelper
     {
         /// <summary>
         /// detects image type from binary data
         /// </summary>
         /// <param name="blob">must be supplied</param>
         public async static Task<(int width, int height, string mimeType)> DetectImageType(this byte[] blob)
         {
             if (blob == null)
             {
                 throw new ArgumentNullException(nameof(blob));
             }
             var config = new Configuration();

            var formatsDetectionsWanted = new IImageFormatDetector[] { new JpegImageFormatDetector(), new PngImageFormatDetector(), new SixLabors.ImageSharp.Formats.Gif.GifImageFormatDetector(), new SixLabors.ImageSharp.Formats.Tga.TgaImageFormatDetector()};
             var decodersWanted = new (IImageDecoder decoder, IImageFormat format)[] {
                 (new JpegDecoder(), JpegFormat.Instance),
                 (new PngDecoder(), PngFormat.Instance),
                 (new GifDecoder(), GifFormat.Instance),
                 (new TgaDecoder(), TgaFormat.Instance) };

            IImageFormat detected = default;
             foreach (var fmt in formatsDetectionsWanted)
             {
                 config.ImageFormatsManager.AddImageFormatDetector(fmt);
                 if (detected == null)
                 {
                     detected = fmt.DetectFormat(blob);
                 }
             }
             foreach (var (decoder, format) in decodersWanted)
             {
                 config.ImageFormatsManager.SetDecoder(format, decoder);
             }
             if (detected != null)
             {
                 var image = await Image.LoadAsync(config, new MemoryStream(blob));

                return (image.Width, image.Height, detected.DefaultMimeType);
             }
             return default;
         }
     }
}

blog comments powered by Disqus