c# - 在 Asp Core 中将 IFormFile 转换为图像

标签 c# asp.net-core

如果文件是图像,我需要调整文件上传的大小。

我写了调整大小的扩展:

 public static Image ResizeImage(this Image image, int width, int height)
    {
        var res = new Bitmap(width, height);
        using (var graphic = Graphics.FromImage(res))
        {
            graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphic.SmoothingMode = SmoothingMode.HighQuality;
            graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
            graphic.CompositingQuality = CompositingQuality.HighQuality;
            graphic.DrawImage(image, 0, 0, width, height);
        }
        return res;
    }

这是 Upload Action :
 [HttpPost("UploadNewsPic"), DisableRequestSizeLimit]
    public IActionResult UploadNewsPic(IFormFile file)
    {
        if (file.IsImage())
        {

        }
        try
        {
            if (file.Length > 0)
            {
                string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                string fullPath = Path.Combine(_applicationRoot.UploadNewPath(), file.Name);
                using (var stream = new FileStream(fullPath, FileMode.Create))
                {
                    file.CopyTo(stream);
                }
            }
            return Ok();
        }
        catch (Exception e)
        {
            return BadRequest();
        }
    }

现在我的问题在这里 => 我的扩展只适用于 Image 的类型文件,但此文件的类型是 IFormFile .我如何转换 IFormFileImage类型 ?

最佳答案

您应该使用 Image.FromStream()将流作为图像读取的方法:

public async Task<IActionResult> FileUpload(IFormFile file)
        {
            if (file == null || file.Length == 0)
            {
                return BadRequest();
            }

            using (var memoryStream = new MemoryStream())
            {
                await file.CopyToAsync(memoryStream);
                using (var img = Image.FromStream(memoryStream))
                {
                  // TODO: ResizeImage(img, 100, 100);
                }
            }
        }

关于c# - 在 Asp Core 中将 IFormFile 转换为图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56161001/

相关文章:

c# - ReCaptcha V3 - 验证失败怎么办?

linux - 在 Linux 上的 AWS Elastic Beanstalk 中部署多个 ASP.NET Core 应用程序(使用 Kestrel 服务器)

c# - 存在异常的继承异常

c# - 使用 MVVM 在 UWP 应用程序中导航时通过 shell 传递参数

forms - 使用参数提交表单到操作,Asp.Net.Core Mvc

.net - 如何获取上次迁移的数据库更新脚本?

c# - .NET Core 中的自定义 "CoreLib"?

c# - 如何使用 Entity Framework 关联来自多个上下文的对象

c# - 带有前导零的 int.Parse()

asp.net-core - ASP.NET Core ViewData、BindProperty 还是 TempData?