ArgumentException:从FileStream复制到MemoryStream时参数无效

问题描述 投票:0回答:1

我正在尝试使用Memorystream中的位图调整图像大小并保存到目录。它在第一次运行时有效,但是如果我第二次尝试更新图像,则会收到ArgumentException。

      public IActionResult UpdatePhoto(int id, IFormFile file)
         {
            var company = _context.Companies.FirstOrDefault(x => x.Id == id);
            var image = company.Logo;
            var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/companies", image);
            if (System.IO.File.Exists(path))
            {
                System.IO.File.Delete(path);
            }
             ResizeImage(file, file.FileName);
            company.Logo = file.FileName;
            _context.Companies.Update(company);
            _context.SaveChanges();
            return RedirectToAction(nameof(Index));
        }

我在调整大小方法时出错

   public void ResizeImage(IFormFile  file, string FileName)
     { 
        using (var memoryStream = new MemoryStream())
         {
          file.CopyToAsync(memoryStream);
          Bitmap original = (Bitmap)Image.FromStream(memoryStream); 
          Bitmap processed = new Bitmap(original,new Size(300,300));
          var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/companies", FileName  );
          processed.Save(path);
      }
c# model-view-controller bitmap filestream memorystream
1个回答
0
投票

您不应该在不是async的方法中使用任何awaitable方法。将代码更新为以下代码应该可以解决此问题。

public void ResizeImage(IFormFile  file, string FileName)
{ 
using (var memoryStream = new MemoryStream())
    {
        file.CopyTo(memoryStream);
        Bitmap original = (Bitmap)Image.FromStream(memoryStream); 
        Bitmap processed = new Bitmap(original,new Size(300,300));
        var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/companies", FileName  );
        processed.Save(path);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.