Click here to Skip to main content
15,434,147 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello i have this problem saving the image to the folder first i resize the image before saving to folder using ASP.NET Core then image successfully saved , but the problem is the image is 0kb ?

This is my code:

ASP.NET
[HttpPost]
  public IActionResult OnPostMyUploader(IFormFile MyUploader)
  {
      var image = System.Drawing.Image.FromStream(MyUploader.OpenReadStream());
      var resized = new Bitmap(image, new System.Drawing.Size(150, 150));
      using var imageStream = new MemoryStream();
      resized.Save(imageStream, ImageFormat.Jpeg);
      var imageBytes = imageStream;

      if (MyUploader != null)
      {
          string uploadsFolder = @"\\10.10.10.67\AQSImages\IdPictures\";
          string filePath = Path.Combine(uploadsFolder, MyUploader.FileName);
          using (var fileStream = new FileStream(filePath, FileMode.Create))
          {
             imageBytes.CopyTo(fileStream);
          }
          return new ObjectResult(new { status = "success" });
      }
      return new ObjectResult(new { status = "fail" });

      ////Better use extension method
      //string customRoot = @"\\10.10.10.67\AQSImages\IdPictures\";
      //if (!Directory.Exists(customRoot))
      //{
      //    Directory.CreateDirectory(customRoot);
      //}

  }


What I have tried:

asp.net mvc 4 - How to resize and save an image which uploaded using file upload control in c# - Stack Overflow[^]
Posted
Updated 15-Jun-22 22:02pm

1 solution

The resized.Save method advances the current position of the imageStream by the number of bytes written.

The imageBytes.CopyTo method copies the bytes from the current position to the end of the stream.

Since the current position is already at the end of the stream, there is nothing to copy. You need to reset the current position before copying:
C#
// No point loading and resizing the image if we're not going to use it:
if (MyUploader is null) return new ObjectResult(new { status = "fail" });

using var image = System.Drawing.Image.FromStream(MyUploader.OpenReadStream());
using var resized = new Bitmap(image, new System.Drawing.Size(150, 150));
using var imageStream = new MemoryStream();
resized.Save(imageStream, ImageFormat.Jpeg);

string uploadsFolder = @"\\10.10.10.67\AQSImages\IdPictures\";
string filePath = Path.Combine(uploadsFolder, MyUploader.FileName);
using var fileStream = new FileStream(filePath, FileMode.Create);

// Reset the current position of the stream:
imageStream.Seek(0L, SeekOrigin.Begin);
imageStream.CopyTo(fileStream);

return new ObjectResult(new { status = "success" });
 
Share this answer
 
Comments
Ramon Ortega Jr 19-Jun-22 16:53pm    
thank you so much my code works!!!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900