In this post I’m sharing this small class I wrote to resize pictures, 3 possible modes are:
1- Set the destination Width and Height (but this can result in skewed images when the aspect ratio is not identical)
>> Call the function and set a fixed FinalWidth and a fixed FinalHeight
2- Maintain aspect ratio, and specify the desired image Width.
>> Call the function with fixed FinalWidth and set FinalHeight to 0
3- Maintain aspect ratio, and specify the desired image Height.
>> Call the function with fixed FinalHeight and set FinalWidth to 0
the
Org parameter is the full original file path on the disk, and
Des is the destination file path, also with
ImageQuality you can specify the quality of the generated image (Jpg), lower quality means smaller file size.
public static void Resize_Picture(string Org, string Des, int FinalWidth, int FinalHeight, int ImageQuality)
{
System.Drawing.Bitmap NewBMP;
System.Drawing.Graphics graphicTemp;
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(Org);
int iWidth;
int iHeight;
if ((FinalHeight == 0) && (FinalWidth != 0))
{
iWidth = FinalWidth;
iHeight = (bmp.Size.Height * iWidth / bmp.Size.Width);
}
else if ((FinalHeight != 0) && (FinalWidth == 0))
{
iHeight = FinalHeight;
iWidth = (bmp.Size.Width * iHeight / bmp.Size.Height);
}
else
{
iWidth = FinalWidth;
iHeight = FinalHeight;
}
NewBMP = new System.Drawing.Bitmap(iWidth, iHeight);
graphicTemp = System.Drawing.Graphics.FromImage(NewBMP);
graphicTemp.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver;
graphicTemp.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphicTemp.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
graphicTemp.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphicTemp.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
graphicTemp.DrawImage(bmp, 0, 0, iWidth, iHeight);
graphicTemp.Dispose();
System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters();
System.Drawing.Imaging.EncoderParameter encoderParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, ImageQuality);
encoderParams.Param[0] = encoderParam;
System.Drawing.Imaging.ImageCodecInfo[] arrayICI = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
for (int fwd = 0; fwd <= arrayICI.Length - 1; fwd++)
{
if (arrayICI[fwd].FormatDescription.Equals("JPEG"))
{
NewBMP.Save(Des, arrayICI[fwd], encoderParams);
}
}
NewBMP.Dispose();
bmp.Dispose();
}
Have fun and don't hesitate to comment or ask questions.