Click here to Skip to main content
15,886,199 members
Articles / Web Development / ASP.NET / ASP.NET Core
Tip/Trick

Compress Uploaded Image in ASP.NET Core 7 Web API

Rate me:
Please Sign up or sign in to vote.
5.00/5 (5 votes)
24 Jan 2023CPOL1 min read 10.9K   19   4
This is the project of ASP.NET Core 7 web API in which we can compress the image.
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.

Image 1

and then give the name of the project below:

Image 2

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.

Image 3

Now, create the controller with name ImageCompressController.cs and create HttpPost method with name as UploadImage().

C#
 [HttpPost]
 [RequestFormLimits(MultipartBodyLengthLimit = 104857600)]
 [RequestSizeLimit(104857600)]
public IActionResult UploadImage([FromForm] FileUploadModel model) 
{
  try
   {
    // this is the directory where file is upload
    var uploadFolder = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/images");
    if (!Directory.Exists(uploadFolder))
    {
     Directory.CreateDirectory(uploadFolder);
    }
    // this is the place where file is uploaded
    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.

C#
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.

C#
public class CompressImage
{ 
    public static void Compressimage(Stream srcImgStream, string targetPath)
    {
      try
      {
            // Convert stream to image
            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)
            {
                // To preserve the aspect ratio  
                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();
            // for file extension having png and gif
            if (extension == ".png" || extension == ".gif")
            {
                // Save image to targetPath
                bitmap.Save(targetPath, image.RawFormat);
            }

            // for file extension having .jpg or .jpeg
            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;

                // Save image to targetPath
                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.

C#
if (originalWidth > maxWidth || originalHeight > maxHeight)
{
  // To preserve the aspect ratio
  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.

C#
 // for file extension having png and gif
 if (extension == ".png" || extension == ".gif")
 {
     // Save image to targetPath
     bitmap.Save(targetPath, image.RawFormat);
 }

 // for file extension having .jpg or .jpeg
 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;

     // Save image to targetPath
     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

Image 4

History

  • 25th January, 2023: Initial version

License

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


Written By
Software Developer (Senior)
Nepal Nepal
I am a highly skilled and motivated ASP.NET Core developer with experience in developing and maintaining web applications. I am experienced in C#, ASP.NET Core, and with some sort of experience with html, css and jquery, and have a strong understanding of software development best practices and design patterns.

Comments and Discussions

 
QuestionThanks Pin
MSsoft crystal11-Feb-23 19:43
MSsoft crystal11-Feb-23 19:43 
AnswerRe: Thanks Pin
bipulmgr11-Feb-23 19:45
professionalbipulmgr11-Feb-23 19:45 
QuestionThanks Pin
Riti Sharma26-Jan-23 23:02
professionalRiti Sharma26-Jan-23 23:02 
AnswerRe: Thanks Pin
bipulmgr2-Feb-23 20:20
professionalbipulmgr2-Feb-23 20:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.