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
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With