Compress image with best quality using C#/Dotnet.

Hello Guys..

This post we will see how to reduce the size of image file with quality levels using C#...

Firstly we should have file path where file exists and we will reasign that new image with new name,

var old_filename=" FILE PATH ";

var new_name=" PATHE TO SAVE ";

After declare both above just create the function or can place in any function as show below


var old_filename=" FILE PATH ";
var  new_name=" PATHE TO SAVE ";             
using (Bitmap bmp1 = new Bitmap(new_name)  
            {  
                ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);
               // Create an Encoder object based on the GUID  
                // for the Quality parameter category.  
                System.Drawing.Imaging.Encoder myEncoder =  System.Drawing.Imaging.Encoder.Quality;  
                 // Create an EncoderParameters object.  
                // An EncoderParameters object has an array of EncoderParameter  
                // objects. In this case, there is only one  
                // EncoderParameter object in the array.  
                EncoderParameters myEncoderParameters = new EncoderParameters(1);  
                EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 100L);  
                // myEncoderParameters.Param[0] = myEncoderParameter;  
                // bmp1.Save(@"Files/QrCodes/TestPhotoQualityFifty.jpg", jpgEncoder, myEncoderParameters);  
    
                // myEncoderParameter = new EncoderParameter(myEncoder, 100L);  
                // myEncoderParameters.Param[0] = myEncoderParameter;   
               // Is for full quality image...
                // Save the bitmap as a JPG file with zero quality level compression.  
                myEncoderParameter = new EncoderParameter(myEncoder, 20L);  
               //This will maintain 20 image quality.
                myEncoderParameters.Param[0] = myEncoderParameter;  
                bmp1.Save(new_name, jpgEncoder, myEncoderParameters);  
            } 

Thank you...

Sign In or Register to comment.