获取上传图像的宽高比(宽度和高度)

Pas*_*ann 3 c# asp.net-core-webapi asp.net-core-2.0

我想在我的API中验证我的图片上传。我只允许使用横向模式的照片。我还想检查宽高比。这是我检查iFormFile是否为图像的代码:

    [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
        });
    }
Run Code Online (Sandbox Code Playgroud)

由于System.Drawing.Image不再可用,因此我找不到将iFormFile转换为Image类型的对象,检查宽度和高度以计算其纵横比的方法。如何在ASP.NET Core API 2.0中获取iFormFile类型的图像的宽度和高度?

Chr*_*att 5

由于System.Drawing.Image不再可用,因此我找不到将iFormFile转换为Image类型的对象,检查宽度和高度以计算其纵横比的方法。

这实际上是不正确的。微软已经发布System.Drawing.CommonNuGet,它提供了跨平台的GDI +图形功能。该API应该是任何旧System.Drawing代码的就地替代:

using (var image = Image.FromStream(file.OpenReadStream()))
{
    // use image.Width and image.Height
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,我不知道它被移到了 NuGet 包中。有用! (2认同)