Code2night
  • Home
  • Guest Posts
  • Tutorial
  • Languages
  • Post Blog
  • Tools
    • JSON Beautifier
    • HTML Beautifier
    • XML Beautifier
    • CSS Beautifier
    • JS Beautifier
    • PDF Editor
    • Word Counter
    • Base64 Encode/Decode
    • Diff Checker
    • JSON to CSV
    • Password Generator
  • Register
  • Login
  1. Home
  2. Blogpost

Image Compression in Asp.net MVC

Date- Jul 16,2022

10706

Free Download Pay & Download
AspNet MVC C#


Image Compression

So, we can perform image compression in asp.net mvc without any specific third party library or nugget package. We will be using Bitmap images to compress the images uploaded by user. So you have to follow these steps.

First of all we will take one new Asp.Net mvc web project and add one new view in that and add one input type file and one button for uploading the file to server. So, copy this code in the view


@{
    ViewBag.Title = "Home Page";
}

@using (Html.BeginForm("Compression", "Home", FormMethod.Post, new {@enctype="multipart/form-data" }))
{
<input  type="file" id="file" name="file"/>
<input type="submit" value="Save"/>
}

After adding this code in the view now we will go to controller and add few namespaces

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

Now after we have done adding the required namespace we will add one method in the controller for compression So our method will be like this . You have to add these method in the controller. Later we will use them in HTTPPost Action.

  public static void Compressimage(string targetPath, String filename, Byte[] byteArrayIn)
        {
            try
            {
                System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
                using (MemoryStream memstr = new MemoryStream(byteArrayIn))
                {
                    using (var image = Image.FromStream(memstr))
                    {
                        float maxHeight = 900.0f;
                        float maxWidth = 900.0f;
                        int newWidth;
                        int newHeight;
                        string extension;
                        Bitmap originalBMP = new Bitmap(memstr);
                        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;

                        }
                        Bitmap bitMAP1 = new Bitmap(originalBMP, newWidth, newHeight);
                        Graphics imgGraph = Graphics.FromImage(bitMAP1);
                        extension = Path.GetExtension(targetPath);
                        if (extension.ToLower() == ".png" || extension.ToLower() == ".gif" || extension.ToLower() == ".jpeg")
                        {
                            imgGraph.SmoothingMode = SmoothingMode.AntiAlias;
                            imgGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
                            imgGraph.DrawImage(originalBMP, 0, 0, newWidth, newHeight);
                            bitMAP1.Save(targetPath, image.RawFormat);
                            bitMAP1.Dispose();
                            imgGraph.Dispose();
                            originalBMP.Dispose();
                        }
                        else if (extension.ToLower() == ".jpg")
                        {
                            imgGraph.SmoothingMode = SmoothingMode.AntiAlias;
                            imgGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
                            imgGraph.DrawImage(originalBMP, 0, 0, newWidth, newHeight);
                            ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);
                            System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
                            EncoderParameters myEncoderParameters = new EncoderParameters(1);
                            EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 50L);
                            myEncoderParameters.Param[0] = myEncoderParameter;
                            bitMAP1.Save(targetPath, jpgEncoder, myEncoderParameters);

                            bitMAP1.Dispose();
                            imgGraph.Dispose();
                            originalBMP.Dispose();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string exc = ex.Message;
                throw;

            }
        }

        public static ImageCodecInfo GetEncoder(ImageFormat format)
        {

            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();

            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                {
                    return codec;
                }
            }
            return null;
        }

So, now we are ready to create an action for compression image file and saving optimized image.

        [HttpPost]
        public ActionResult Compression(HttpPostedFileBase file)
        {
            using (var ms = new MemoryStream())
            {
                var targetImagepath = Server.MapPath("/Content/Compressed/" + Path.GetFileNameWithoutExtension(file.FileName) + "_Compressed" + DateTime.Now.ToString("ddMMyyyyhhmmss") + Path.GetExtension(file.FileName));
                byte[] image = new byte[file.ContentLength];
                file.InputStream.Read(image, 0, image.Length);
                Compressimage(targetImagepath, "",image);
            }
            return RedirectToAction("Index");
        }

   

Here, you can see we have passed HttpPostedFileBase as parameter which will have the file. And we need byte[] for our compress method so first of all we have to convert the image file to byte[] and pass to the method. After that you can pass your location in the targetImagepath variable where you want to save your compressed image.Now run the application





So, you can see the uploaded image size in first image and the compressed image size in the screenshots. So this is how you can compress image in asp.net mvc. You can also download the attached code.







S
Shubham Batra
Programming author at Code2Night โ€” sharing tutorials on ASP.NET, C#, and more.
View all posts โ†’

Related Articles

Maximum request length exceeded
Jul 18, 2022
Import Excel in Asp.net MVC using OLE DB
Jun 23, 2022
Excel Export in Asp.Net MVC using XlWorkbook
Jun 11, 2022
Understanding Memory Management and Garbage Collection in .NET
Mar 16, 2026

Comments

Tags

AspNet
C#
programming
AspNet MVC
c programming
AspNet Core
C
software development
tutorial
MVC
memory management
Paypal
coding
coding best practices
data structures
programming tutorial
tutorials
object oriented programming
Slick Slider
StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1760
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp Join Us On Facebook
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blogs
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
Free Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Diff Checker
  • Base64 Encode/Decode
  • Word Counter
By Language
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ยท  Terms
Translate Page