Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get aspect ratio (width and height) of an uploaded image

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?

like image 334
Pascal Avatar asked Nov 05 '18 18:11

Pascal


Video Answer


1 Answers

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
}
like image 139
Chris Pratt Avatar answered Nov 09 '22 07:11

Chris Pratt