Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core Image Upload and Resize

How do you get the file stream of an uploaded image (IFormFile) and resize it?

public ActionResult Upload(IFormFile file)
{
    using (var reader = new StreamReader(file.OpenReadStream()))
    {
        var fileContent = reader.ReadToEnd();
        var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);

        //scale image here?
    }
}
like image 556
Nick De Beer Avatar asked Jan 27 '16 02:01

Nick De Beer


2 Answers

You can use IFormFile.OpenReadStream() to get the stream, and then just insert the stream into an Image. For this instance I scaled it to 1024x768.

Image image = Image.FromStream(file.OpenReadStream(), true, true);
var newImage = new Bitmap(1024, 768);
using (var g = Graphics.FromImage(newImage))
{
    g.DrawImage(image , 0, 0, 1024, 768); 
}

You can then use newImage to save or do whatever you want with.

like image 172
Nick De Beer Avatar answered Nov 11 '22 01:11

Nick De Beer


Install from nuget : Install-Package SixLabors.ImageSharp

[HttpPost]
public IActionResult Upload(IFormFile file)
{
 //Better use extension method
 string fileName;
 string customRoot = "wwwroot\\Upload\\";
 if (!Directory.Exists(customRoot))
    {
       Directory.CreateDirectory(customRoot);
    }
    var path = Path.Combine(Directory.GetCurrentDirectory(), customRoot,fileName);
    using var image = Image.Load(file.OpenReadStream());
    //100: height
    //100: width
    image.Mutate(x => x.Resize(100, 100));
    image.Save(path); 
    return Ok();
}

for more information : https://blog.elmah.io/upload-and-resize-an-image-with-asp-net-core-and-imagesharp/

like image 36
Omid Soleiman Avatar answered Nov 11 '22 00:11

Omid Soleiman