Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate Image type for IFormFile in ASP.Net Core

I have an ASP.NET Core application and I need to validate that the uploaded file is an image and not a non-image file which has an image extension.... All solutions that I found and makes sense use System.Drawing.Image or similar classes that aren't available in ASP.NET Core. Can you kindly suggest an alternative? *Please note that I'm not trying to check the extension but the contents.

Thank you

like image 803
Techy Avatar asked Oct 30 '22 11:10

Techy


1 Answers

Now "System.Drawing.Common" NuGet is available for .NET Core.

You can do the following to validate the "possible" images:

using System.Drawing;
// ...
public bool IsImage(byte[] data)
{
  var dataIsImage = false;
  using (var imageReadStream = new MemoryStream(data))
  {
    try
    {
      using (var possibleImage = Image.FromStream(imageReadStream))
      {
      }
      dataIsImage = true;
    }
    // Here you'd figure specific exception to catch. Do not leave like that.
    catch
    {
      dataIsImage = false;
    }
  }

  return dataIsImage;
}
like image 188
Anatolyevich Avatar answered Nov 15 '22 05:11

Anatolyevich