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..


3 comments:

  1. I have tried your code but i am getting following error in my ASP.Net 3.5 application."A generic error occurred in GDI+." What to do now..????

    ReplyDelete
  2. Can you specify the line on which you are getting error ?

    ReplyDelete
  3. Issue was at my side. Folder had permission issues so i changed its permissions to Everyone and one thing more. Folder should already be there. Now it is working fine for me.

    ReplyDelete