This project discusses how ASP.NET Core web API compresses an uploaded image and saves the compressed image into ./wwwroot/images folder.
Introduction
In this project, we can find the ASP.NET Core web API to compress the uploaded image and save the compressed image into ./wwwroot/images folder.
Guidelines to Create .NET 7 Project
Open Visual Studio 2022, and create a new project. Search the template for ASP.NET Core Web API and select Next.
and then give the name of the project below:
Now, as in the given screenshot below. Choose the .NET Framework which is .NET 7 and keep the rest of the things the same and click Next button.
Now, create the controller with name ImageCompressController.cs and create HttpPost
method with name as UploadImage()
.
[HttpPost]
[RequestFormLimits(MultipartBodyLengthLimit = 104857600)]
[RequestSizeLimit(104857600)]
public IActionResult UploadImage([FromForm] FileUploadModel model)
{
try
{
var uploadFolder = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/images");
if (!Directory.Exists(uploadFolder))
{
Directory.CreateDirectory(uploadFolder);
}
string fileUrl = Path.Combine(uploadFolder,
$"{Guid.NewGuid()}_{model.file.FileName}");
Stream strm = model.file.OpenReadStream();
CompressImage.Compressimage(strm, fileUrl);
return Ok(new { message = "Compressed successfully" });
}
catch (Exception ex)
{
_logger.LogError
(ex, "An error occured while trying to compress the uploaded image.");
return BadRequest(new { message = ex.Message });
}
}
Create a class for FileUploadModel
which is the request model of post API. This class contains IFormFile
property.
public class FileUploadModel
{
public IFormFile file { get; set; }
}
Create the class CompressImage.cs in the util folder which is the helper class in which function to compress image is created.
public class CompressImage
{
public static void Compressimage(Stream srcImgStream, string targetPath)
{
try
{
using var image = Image.FromStream(srcImgStream);
float maxHeight = 900.0f;
float maxWidth = 900.0f;
int newWidth;
int newHeight;
var originalBMP = new Bitmap(srcImgStream);
int originalWidth = originalBMP.Width;
int originalHeight = originalBMP.Height;
if (originalWidth > maxWidth || originalHeight > maxHeight)
{
float ratioX = (float)maxWidth / (float)originalWidth;
float ratioY = (float)maxHeight / (float)originalHeight;
float ratio = Math.Min(ratioX, ratioY);
newWidth = (int)(originalWidth * ratio);
newHeight = (int)(originalHeight * ratio);
}
else
{
newWidth = (int)originalWidth;
newHeight = (int)originalHeight;
}
var bitmap = new Bitmap(originalBMP, newWidth, newHeight);
var imgGraph = Graphics.FromImage(bitmap);
imgGraph.SmoothingMode = SmoothingMode.Default;
imgGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
imgGraph.DrawImage(originalBMP, 0, 0, newWidth, newHeight);
var extension = Path.GetExtension(targetPath).ToLower();
if (extension == ".png" || extension == ".gif")
{
bitmap.Save(targetPath, image.RawFormat);
}
else if (extension == ".jpg" || extension == ".jpeg")
{
ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);
Encoder myEncoder = Encoder.Quality;
var encoderParameters = new EncoderParameters(1);
var parameter = new EncoderParameter(myEncoder, 50L);
encoderParameters.Param[0] = parameter;
bitmap.Save(targetPath, jpgEncoder, encoderParameters);
}
bitmap.Dispose();
imgGraph.Dispose();
originalBMP.Dispose();
}
catch (Exception ex)
{
throw ex;
}
}
public static ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
}
In the above function, the below section is used to crop the image in the aspect ratio. If the original image height and width are greater than the aspect ratio, then it is cropped into desired ratio, else there is no change in the original image ratio.
if (originalWidth > maxWidth || originalHeight > maxHeight)
{
float ratioX = (float)maxWidth / (float)originalWidth;
float ratioY = (float)maxHeight / (float)originalHeight;
float ratio = Math.Min(ratioX, ratioY);
newWidth = (int)(originalWidth * ratio);
newHeight = (int)(originalHeight * ratio);
}
else
{
newWidth = (int)originalWidth;
newHeight = (int)originalHeight;
}
var bitmap = new Bitmap(originalBMP, newWidth, newHeight);
var imgGraph = Graphics.FromImage(bitmap);
.jpg or .jpeg images are encoded with 50% quality. 50L represents the quality of the compressed image.
if (extension == ".png" || extension == ".gif")
{
bitmap.Save(targetPath, image.RawFormat);
}
else if (extension == ".jpg" || extension == ".jpeg")
{
ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);
Encoder myEncoder = Encoder.Quality;
var encoderParameters = new EncoderParameters(1);
var parameter = new EncoderParameter(myEncoder, 50L);
encoderParameters.Param[0] = parameter;
bitmap.Save(targetPath, jpgEncoder, encoderParameters);
}
bitmap.Save()
is used to save the compressed image in the target path.
This is how the image can be compressed and saved into a desired file path using ASP.NET Core 7 web API.
Run Command
dotnet watch run
Swagger
History
- 25th January, 2023: Initial version