asp.net-coreasp.net-4.6

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?
    }
}

Solution

  • 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.