首页 > 解决方案 > 获取上传图片的纵横比(宽高)

问题描述

我想在我的 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
        });
    }

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

标签: c#asp.net-core-2.0asp.net-core-webapi

解决方案


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

这实际上是不正确的。Microsoft 已System.Drawing.Common作为NuGet发布,它提供跨平台 GDI+ 图形功能。System.DrawingAPI 应该是任何旧代码的就地替换:

using (var image = Image.FromStream(file.OpenReadStream()))
{
    // use image.Width and image.Height
}

推荐阅读