将IFormFile转换为ASP Core中的图像

时间:2019-05-16 04:46:09

标签: c# asp.net-core

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

我写出调整大小的范围:

 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。如何将IFormFile转换为Image类型?

2 个答案:

答案 0 :(得分:2)

您应该使用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);
                }
            }
        }

答案 1 :(得分:0)

您需要使用OpenReadStream打开文件并将其转换为图像格式。并将其传递给您的扩展方法。

FileDetails fileDetails;
                using (var reader = new StreamReader(file.OpenReadStream()))
                {
                   var fileContent = reader.ReadToEnd();
                   var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
                   fileDetails = new FileDetails
                      {
                          Filename = parsedContentDisposition.FileName,
                          Content = fileContent,
                          ContentType=file.ContentType
                       };
                 }