How to resize the image by passing the parameter of width and height of image

Amatya
Posted by Amatya under C# category on | Points: 40 | Views : 1008
public System.Drawing.Image resizeImage(int nWidth, int nHeight, string photoPath)
{
System.Drawing.Image imgPhoto = System.Drawing.Image.FromFile(photoPath);
int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height;
if (sourceWidth < sourceHeight)
{
int buff = nWidth;
nWidth = nHeight;
nHeight = buff;
}
int sourceX = 0, sourceY = 0, destX = 0, destY = 0;
float nPercent = 0, nPercentW = 0, nPercentH = 0;
nPercentW = ((float)nWidth / (float)sourceWidth);
nPercentH = ((float)nHeight / (float)sourceHeight);
if (nPercentH < nPercentW)
{
nPercent = nPercentH;
destX = System.Convert.ToInt16((nWidth -
(sourceWidth * nPercent)) / 2);
}
else
{
nPercent = nPercentW;
destY = System.Convert.ToInt16((nHeight -
(sourceHeight * nPercent)) / 2);
}
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
Bitmap bmPhoto = new Bitmap(nWidth, nHeight,
PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
imgPhoto.VerticalResolution);
Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.Clear(Color.White);
grPhoto.InterpolationMode =
System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
grPhoto.DrawImage(imgPhoto,
new Rectangle(destX, destY, destWidth, destHeight),
new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
GraphicsUnit.Pixel);
grPhoto.Dispose();
imgPhoto.Dispose();
return bmPhoto;
}


Hope it will help you guys

Comments or Responses

Login to post response