Reputation: 1305
I want to validate my image upload in my API. I want only allow photos which are in landscape mode. I would also like to check the aspect ratio. This is my code for checking if the iFormFile is an image:
[HttpPost]
public JsonResult Post(IFormFile file)
{
if (file.ContentType.ToLower() != "image/jpeg" &&
file.ContentType.ToLower() != "image/jpg" &&
file.ContentType.ToLower() != "image/png")
{
// not a .jpg or .png file
return new JsonResult(new
{
success = false
});
}
// todo: check aspect ratio for landscape mode
return new JsonResult(new
{
success = true
});
}
Since System.Drawing.Image
is not available anymore, I couldn't find a way to convert the iFormFile into an Image typed object, to check the width and height to calculate the aspect ratio of it. How can I get the width and height of an image with the type iFormFile in ASP.NET Core API 2.0?
Upvotes: 8
Views: 14297
Reputation: 18944
I had similar issue in .net core and I solved it by a client side solution. Based on your project conditions, You may trust in client side processing and let them to do some jobs. You can get the aspect ratio with some lines of js code which is supported on all browsers and then passing those (width
& height
) to API as well:
var file = e.target.files[0];
if (/\.(jpe?g|png|gif)$/i.test(file.name)) {
var reader = new FileReader();
reader.addEventListener("load", function () {
var image = new Image();
image.src = this.result as string;
image.addEventListener('load', function () {
console.log(`height: ${this.height}, width: ${this.width}`);
});
}, false);
reader.readAsDataURL(file);
}
And API will look like:
//POST : api/samples?width=100&height=500
[HttpPost]
public JsonResult Post(IFormFile file, int width, int height) {}
I've tested this solution for multiple file upload and works fine.
Upvotes: 0
Reputation: 239200
Since
System.Drawing.Image
is not available anymore, I couldn't find a way to convert the iFormFile into an Image typed object, to check the width and height to calculate the aspect ratio of it.
That's actually not correct. Microsoft has released System.Drawing.Common
as a NuGet, which provides cross-platform GDI+ graphics functionality. The API should be an in-place replacement for any old System.Drawing
code:
using (var image = Image.FromStream(file.OpenReadStream()))
{
// use image.Width and image.Height
}
Upvotes: 29