【问题标题】:Get aspect ratio (width and height) of an uploaded image获取上传图片的纵横比(宽高)
【发布时间】:2019-04-09 03:52:38
【问题描述】:

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

【问题讨论】:

  • 你不应该仅仅为了获得它的尺寸而渲染一个文件,使用像 SoftImaging 这样的图像库来从文件中提取尺寸。
  • @DourHighArch 你不应该仅仅为了获取它的尺寸而渲染一个文件——这也许是对的,但是使用第三方库只是为了对图像进行简单的尺寸检查? - 我不认为这是要走的路。

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


【解决方案1】:

由于 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
}

【讨论】:

  • 谢谢,我不知道它被移到了 NuGet 包中。它有效!
  • 嗯,是的,也不是。 System.Drawing 是一个 GDI+ 图形库,因此您显然需要这些组件。该链接解决的问题是针对容器运行的精简操作系统映像,所以是的,您必须在那里安装组件。
【解决方案2】:

我在 .net 核心中遇到了类似的问题,我通过 客户端解决方案解决了它。根据您的项目情况,您可以信任客户端处理并让他们做一些工作。您可以使用一些 js 代码行获得纵横比,即 supported on all browsers,然后将这些代码(width & height)也传递给 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) {}

我已经针对多个文件上传测试了这个解决方案并且工作正常。

【讨论】:

    猜你喜欢
    • 2011-12-24
    • 1970-01-01
    • 1970-01-01
    • 2018-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-26
    • 2019-11-14
    相关资源
    最近更新 更多