Featured

Upload and resize an image in ASP.NET 5

Last modified: June 17, 2021

In my previous blog, I talked about how to upload files to the Microsoft SQL Server database. It is commmon for a web application to resize an image before uploading to the system. We need to reduce the file size for storage purpose and faster download/displaying images to the web pages. In this tutorial, we will extend upload files to the database by watermarking the images.

Step 1

Download the project "upload files to the Microsoft SQL Server database" source code from here. We are going to re-use the code from it. Open the solution.

Step 2

We need to install SixLabors.ImageSharp NuGet library for us to allow resizing the image. Right-click the solution name and click "Manage Nuget Packages" and search for SixLabors.ImageSharp

resize-image

Step 3

we first open a file, read its stream, and output the IImageFormat for saving purposes. In this demo, we set the maximum width equals 400 but you set any positive integer value as per your need. We need to calculate the new newImageHeight so that we can keep the width to height ratio otherwise the images might be squeezed. Image file is saved to memorystream which then add to the database.

[HttpPost] public async Task UploadFile(IFormFile file) { if (file.Length > 0) { IImageFormat format; using (var image = Image.Load(file.OpenReadStream(), out format)) { int maxImageWidth = 400; if (image.Width > maxImageWidth) { int newImageHeight = (int)(image.Height * ((float)maxImageWidth / (float)image.Width)); image.Mutate(x => x.Resize(maxImageWidth, newImageHeight)); } using (MemoryStream m = new MemoryStream()) { image.Save(m, format); var newFile = new Models.File(); newFile.MimeType = file.ContentType; newFile.FileName = Path.GetFileName(file.FileName); newFile.Content = m.ToArray(); await _fileService.AddFile(newFile); } } } Response.Redirect("/File"); }