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

时间:2018-11-05 18:44:56

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

我想验证我在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类型的图像的宽度和高度?

2 个答案:

答案 0 :(得分:3)

  

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

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

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

答案 1 :(得分:0)

.net核心中存在类似的问题,并且通过客户端解决方案解决了该问题。根据您的项目条件,您可能会信任客户端处理并让他们执行一些工作。您可以通过几行js代码来获得长宽比,这些代码是supported on all browsers,然后将那些(widthheight)传递给API:

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);
}

API如下所示:

//POST : api/samples?width=100&height=500
[HttpPost]
public JsonResult Post(IFormFile file, int width, int height) {}

我已经测试了此解决方案用于多个文件上传,并且效果很好。

相关问题