Image Saving, Cropping, and Resizing in C#

By FoxLearn 1/16/2025 6:27:49 AM   44
When working with image editing in C#, particularly using GDI+, some tasks can feel cumbersome and repetitive.

However, with a little creativity and some helpful code snippets, you can easily streamline common image manipulation functions such as saving JPEGs, cropping, and resizing images.

Saving a JPEG Image with Custom Quality

One of the most frequently needed operations is saving an image as a JPEG.

In this method, we provide flexibility by setting the image quality parameter.

private void saveJpeg(string path, Bitmap img, long quality)
{
   // Encoder parameter for image quality
   EncoderParameter qualityParam = new EncoderParameter(Encoder.Quality, quality);

   // Get JPEG codec
   ImageCodecInfo jpegCodec = this.getEncoderInfo("image/jpeg");

   if (jpegCodec == null)
      return;

   EncoderParameters encoderParams = new EncoderParameters(1);
   encoderParams.Param[0] = qualityParam;

   // Save the image using the codec and encoder parameters
   img.Save(path, jpegCodec, encoderParams);
}

The function below retrieves the encoder info for the JPEG format from the system, ensuring the correct codec is used.

private ImageCodecInfo getEncoderInfo(string mimeType)
{
   // Retrieve all available image codecs
   ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

   // Find and return the appropriate codec based on mimeType
   foreach (var codec in codecs)
      if (codec.MimeType == mimeType)
         return codec;
   return null;
}

In this example, we ensure that the JPEG codec is available on the system before proceeding with the save operation.

Cropping an Image

Cropping an image is another fundamental operation in image processing.

private static Image cropImage(Image img, Rectangle cropArea)
{
   Bitmap bmpImage = new Bitmap(img);
   Bitmap bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat);
   return (Image)(bmpCrop);
}

This method uses the Clone function to extract a specific region defined by the Rectangle object from the original image.

Resizing an Image While Maintaining Aspect Ratio

Resizing images is common, but keeping the aspect ratio intact can be tricky.

private static Image resizeImage(Image imgToResize, Size size)
{
   int sourceWidth = imgToResize.Width;
   int sourceHeight = imgToResize.Height;

   float nPercentW = (float)size.Width / sourceWidth;
   float nPercentH = (float)size.Height / sourceHeight;

   float nPercent = (nPercentH < nPercentW) ? nPercentH : nPercentW;

   int destWidth = (int)(sourceWidth * nPercent);
   int destHeight = (int)(sourceHeight * nPercent);
   
   Bitmap b = new Bitmap(destWidth, destHeight);
   Graphics g = Graphics.FromImage((Image)b);
   g.InterpolationMode = InterpolationMode.HighQualityBicubic;

   // Draw the resized image onto the new bitmap
   g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
   g.Dispose();

   return (Image)b;
}

After determining the appropriate scaling factor, we create a new bitmap with the calculated dimensions and use the Graphics object to draw the resized image.

By using the HighQualityBicubic interpolation mode, we ensure that the resized image maintains high quality, particularly when scaling down.

With the methods described above, you can handle common image editing tasks in C# with ease. Whether you’re saving a JPEG with a specific quality, cropping an image, or resizing it proportionally, these functions can save you time and effort.