Introduction
If you work on a project that involves some image processing then you might come across where you need to do image resizing, converting etc..
This article will give you C# code snippet on how to resize an image to desired height and width without affecting the aspect ratio and save the image in JPEG format
with the specified quality. Below given code handles the following
- Resize a image to specified width and height
- Maintain the aspect ratio While resizing
- Convert to RGB pixel format if image data is in any other format like YCCK, CMYK
- Covert the image to JPEG format
- Save the image in the given file path with the specified quality
Code
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Linq;
public class ImageHandler
{
public void Save(Bitmap image, int maxWidth, int maxHeight, int quality, string filePath)
{
int originalWidth = image.Width;
int originalHeight = image.Height;
float ratioX = (float)maxWidth / (float)originalWidth;
float ratioY = (float)maxHeight / (float)originalHeight;
float ratio = Math.Min(ratioX, ratioY);
int newWidth = (int)(originalWidth * ratio);
int newHeight = (int)(originalHeight * ratio);
Bitmap newImage = new Bitmap(newWidth, newHeight, PixelFormat.Format24bppRgb);
using (Graphics graphics = Graphics.FromImage(newImage))
{
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.DrawImage(image, 0, 0, newWidth, newHeight);
}
ImageCodecInfo imageCodecInfo = this.GetEncoderInfo(ImageFormat.Jpeg);
Encoder encoder = Encoder.Quality;
EncoderParameters encoderParameters = new EncoderParameters(1);
EncoderParameter encoderParameter = new EncoderParameter(encoder, quality);
encoderParameters.Param[0] = encoderParameter;
newImage.Save(filePath, imageCodecInfo, encoderParameters);
}
private ImageCodecInfo GetEncoderInfo(ImageFormat format)
{
return ImageCodecInfo.GetImageDecoders().SingleOrDefault(c => c.FormatID == format.Guid);
}
}
Hope it helps someone!