Friday, December 24, 2010

Image Scaling without cutting image.

Some time we need to scale images in our Web or Desktop Apps. requirement could be different. but mostly we want to reduce size of image keeping the quality almost same. In my case we had collection of huge dimension images which are not need. I scaled the dimensions to 17*11 or 11*17 depending upon type of image (Portrait or Landscape.)

The main function will be like this.

string localpath = @"C:\Images\9ee5887.jpg";
Image sourceImage = Image.FromFile(localpath);

Image temp = ScalImage(sourceImage, new Size(1200, 800));

temp.Save("D:\\Images\\9ee5887-Scaled.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

sourceImage.Dispose();
temp.Dispose();


And the scale image funcion will be like this.


public Image ScalImage(Image imgToResize, Size size)
{

int sourceWidth = imgToResize.Width;
int sourceHeight = imgToResize.Height;

float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;

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

if (nPercentH < nPercentW)
nPercent = nPercentH;
else
nPercent = nPercentW;

int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);

Bitmap b = new Bitmap(destWidth, destHeight);

using (Graphics g = Graphics.FromImage((Image)b))

{
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);

}


return (Image)b;

}


I have tested both Landscap and portrait images with this. Works perfectly. :) Any Suggestion Improvement will be appreciated greatly..