Resize Image or Compress Image File Using C#

If you are working on a project that involves image files, you may encounter the need to reduce the image size (compress the image) to ensure smooth functionality. This blog post provides code examples that offer similar functionalities to the image resizing feature in Adobe Photoshop.

Resize Image or Compress Image File Using C#

Getting Started

Using these codes, you can build an effective photo compression application similar to Adobe Photoshop's image compressor. You can even use this code in a web-based project to create an efficient online picture compression tool. These codes shrink image sizes without compromising quality, and you can even decrease the image size in KB without altering the pixel dimensions.

The following things can be done using this code:

  1. Compress JPEG File or Compress a jpg.
  2. Compress PNG File.
  3. GIF Compressor.

Code for Compress Image

  private void Photo_compress()  
     {  
       // Path to the source folder  
       string sourceImagePath = @"D:\inputDirectoryPath\";  
       // Path to the destination folder  
       string destinationImagePath = @"D:\outputDirectoryPath\";  
       double scaleFactor = .5;  
       try  
       {  
         using (FileStream fileStream = File.OpenRead(sourceImagePath))  
         {  
           using (var image = System.Drawing.Image.FromStream(fileStream))  
           {  
             // Desired width and height for the resized image  
             var newWidth = (int)(image.Width * scaleFactor);  
             var newHeight = (int)(image.Height * scaleFactor);  
             // Create a new bitmap with the desired size  
             Bitmap compressedImage = new Bitmap(newWidth, newHeight);  
             // Create a graphics object from the resized image  
             using (Graphics graphics = Graphics.FromImage(compressedImage))  
             {  
               // Set High quality, low speed compositing.  
               graphics.CompositingQuality = CompositingQuality.HighQuality;  
               //Specifies antialiased rendering.  
               graphics.SmoothingMode = SmoothingMode.HighQuality;  
               // Set the interpolation mode to high quality  
               graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;  
               // Draw the source image onto the resized image with the desired size  
               graphics.DrawImage(image, 0, 0, newWidth, newHeight);  
             }  
             //Create patch for compressed image  
             string compressedImagePath = System.IO.Path.Combine(destinationImagePath, "compressedfile.jpg");  
             // Save the compressed image to the destination folder  
             compressedImage.Save(compressedImagePath);  
           }  
         }  
       }  
       catch (Exception ex)  
       {  
         throw ex;  
       }  
     }  

Compress Image

You may want to modify the parameters of an image when saving it to disk to reduce its size or improve its quality. You can adjust the quality of a JPEG image by modifying its compression level. To specify the compression level when saving a JPEG image, you need to create an EncoderParameters object and pass it to the Save method of the Image class. Initialize the EncoderParameters object with an array containing a single EncoderParameter. When creating the EncoderParameter, specify the Quality encoder and set the desired compression level.

The following example codes decrease image file size without losing quality, it creates an EncoderParameter object and saves three JPEG images. Each JPEG image is saved with a different quality level, by modifying the long value passed to the EncoderParameter constructor. A quality level of 0 corresponds to the greatest compression, and a quality level of 100 corresponds to the least compression.

Image Compressor Code

 private void VaryQualityLevel()   
   {   
     // Get a bitmap. The using statement ensures objects   
     // are automatically disposed from memory after use.   
     using (Bitmap bmp1 = new Bitmap(@"C:\TestPhoto.jpg"))   
     {   
       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, 50L);   
       myEncoderParameters.Param[0] = myEncoderParameter;   
       bmp1.Save(@"c:\TestPhotoQualityFifty.jpg", jpgEncoder, myEncoderParameters);   
       myEncoderParameter = new EncoderParameter(myEncoder, 100L);   
       myEncoderParameters.Param[0] = myEncoderParameter;   
       bmp1.Save(@"C:\TestPhotoQualityHundred.jpg", jpgEncoder, myEncoderParameters);   
       // Save the bitmap as a JPG file with zero quality level compression.   
       myEncoderParameter = new EncoderParameter(myEncoder, 0L);   
       myEncoderParameters.Param[0] = myEncoderParameter;   
       bmp1.Save(@"C:\TestPhotoQualityZero.jpg", jpgEncoder, myEncoderParameters);   
     }   
   }  

Code for Reduce Image Size

 private ImageCodecInfo GetEncoder(ImageFormat format)   
 {   
   ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();   
   foreach (ImageCodecInfo codec in codecs)   
   {   
     if (codec.FormatID == format.Guid)   
     {   
       return codec;   
     }   
   }   
   return null;   
 }  

Compress Images Bulk

The following codes reduce jpeg size without losing quality, you can use this code directly to your project. you need to just change the source folder and destination folder path.

 private void compress_images_bulk()  
     {  
       // Path to the source folder   
       string sourceFolderPath = @"D:\inputDirectoryPath\";  
       // Path to the destination folder   
       string destinationFolderPath = @"D:\outputDirectoryPath\";  
       double scaleFactor = .5;  
       try  
       {  
         int count = 1;  
         foreach (string sourceImagePath in Directory.EnumerateFiles(sourceFolderPath,"*.jpeg"))  
         {  
           using (FileStream fileStream = File.OpenRead(sourceImagePath))  
           {  
             using (var image = System.Drawing.Image.FromStream(fileStream))  
             {  
               // Desired width and height for the resized image   
               var newWidth = (int)(image.Width * scaleFactor);  
               var newHeight = (int)(image.Height * scaleFactor);  
               // Create a new bitmap with the desired size   
               Bitmap compressedImage = new Bitmap(newWidth, newHeight);  
               // Create a graphics object from the resized image   
               using (Graphics graphics = Graphics.FromImage(compressedImage))  
               {  
                 // Set High quality, low speed compositing.   
                 graphics.CompositingQuality = CompositingQuality.HighQuality;  
                 //Specifies antialiased rendering.   
                 graphics.SmoothingMode = SmoothingMode.HighQuality;  
                 // Set the interpolation mode to high quality   
                 graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;  
                 // Draw the source image onto the resized image with the desired size   
                 graphics.DrawImage(image, 0, 0, newWidth, newHeight);  
               }  
               //Create patch for compressed image   
               string compressedImagePath = System.IO.Path.Combine(destinationFolderPath, "compressedfile"+count+".jpg");  
               // Save the compressed image to the destination folder   
               compressedImage.Save(compressedImagePath);  
             }  
           }  
         }  
         count++;  
       }  
       catch (Exception ex)  
       {  
         throw ex;  
       }  
     }  

Thanks

Kailash Chandra Behera

An IT Professional with 12 years experience in development life cycle in windows, service and Web based application using Microsoft.Net technologies. Proven record of developing all phases of projects in Microsoft.Net technology from initiation to closure aligning with the company's Business objectives to drive process improvements, competitive advantage and bottom-line gains. -> Good exposure of independently working and developing multiple projects ->Committed to efficient and effective development of projects in a fast-paced and deadline driver environment. Skill :- Develop and design projects in various technologies of Microsoft Technology. Total IT Experience- 13+

Previous Post Next Post

نموذج الاتصال