5

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

Techy
  • 1,786
  • 3
  • 17
  • 36

2 Answers2

2

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;
}
Anatolyevich
  • 600
  • 4
  • 13
0

if you have privileges to run executables on the server you can use imagemagick's identify command. it's a lot of work.you'd need to install imagemagick on the server and need to have permissions to run executables.

https://www.imagemagick.org/script/identify.php

you'd need to call the program and give the image file to it

how to call exe files in c#: https://msdn.microsoft.com/en-us/library/0w4h05yb(v=vs.110).aspx

how to read process output: https://msdn.microsoft.com/en-us/library/system.diagnostics.process.beginoutputreadline(v=vs.110).aspx

Uğur Gümüşhan
  • 2,277
  • 4
  • 29
  • 59