In this article I will tell you how to resize an image to a desired size.
To resize an image in ASP.Net/C# we will use the following procedure:
1. Get an image that you want to resize:
string path = Server.MapPath("~/Images");
System.Drawing.Image img = System.Drawing.Image.FromFile(string.Concat(path,"/3904.jpg"));
In the attached sample I stored the image in the image folder.
2. Bitmap b = new Bitmap(img);
The Bitmap object is declared to get the image in pixel data.
3. To resize the image to the desired format I used the method given below:
private static System.Drawing.Image resizeImage(System.Drawing.Image imgToResize, Size size)
{
//Get the image current width
int sourceWidth = imgToResize.Width;
//Get the image current height
int sourceHeight = imgToResize.Height;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
//Calulate width with new desired size
nPercentW = ((float)size.Width / (float)sourceWidth);
//Calculate height with new desired size
nPercentH = ((float)size.Height / (float)sourceHeight);
if (nPercentH < nPercentW)
nPercent = nPercentH;
else
nPercent = nPercentW;
//New Width
int destWidth = (int)(sourceWidth * nPercent);
//New Height
int destHeight = (int)(sourceHeight * nPercent);
Bitmap b = new Bitmap(destWidth, destHeight);
Graphics g = Graphics.FromImage((System.Drawing.Image)b);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
// Draw image with new width and height
g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
g.Dispose();
return (System.Drawing.Image)b;
}
In the method above we get the bitmap image and draw the new image with new width and height. (The image will be drawn in the specified aspect ratio.)
4. Pass the bitmap image in the method above with the desired width and height:
System.Drawing.Image i = resizeImage(b, new Size(100, 100));
The method given above will return the image with the new width and height.
Result