Resize Image Size or Compress Image File Using C#

Kailash Chandra Behera | Tuesday, July 04, 2023

If you are working on a project where you are dealing with image files, then you must have come to the situation to resize image size (compress image) to run the image functionalities smoothly. Here in this blog post, shares some code examples that can expose same functionalities as image resizer adobe photoshop.

Using these codes, you can build an effective photo compressor application like image compressor adobe photoshop. You can even use this code in web based project to build an effective image compressor online application. These codes shrink image without losing quality of images even you can increase image size in kb without changing pixels.

The following things can be done using this code:

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

Image Size Reducer Code

  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;  
       }  
     }  

Resize Image Illustrator Code

You may want to modify the parameters of an image when you save the image to disk to reduce image 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 you save a JPEG image, you must create an EncoderParameters object and pass it to the Save method of the Image class. Initialize the EncoderParameters object so that it has an array that consists of one EncoderParameter. When you create the EncoderParameter, specify the Quality encoder, and 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.

Photo Size 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);   
     }   
   }  

Photo resizer Code

 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


No comments: