Detecting image type code snip

I need this type of code often, since you don’t want to asume that a file extension, e.g. .jpeg really is jpeg. It just as well could be a malware file. Also, in combination with getting height and width, this tool does more than the other snips. Enjoy!

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)
                 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