Saturday, June 26, 2010

Resizing images without loss of quality in .Net

Recently I had faced a problem regarding photos that I had captured using my digicam.
When I capture photo using my cannon digicam, the size of each photo is 2MB or more.
So it is very difficult to upload those photos in web because of their size.
And compress those photos one by one using Microsoft Office Picture Manager is difficult too.
So I wrote some code to resize those photos and to minimize the size without affecting the photo quality.
The code is as follow.........

public void ResizeFromStream(string ImageSrcPath, string ImageSavePath, int MaxSideSize)
{
try
{
int intNewWidth;
int intNewHeight;
Image imgInput = Image.FromFile(ImageSrcPath);

//Determine image format
ImageFormat fmtImageFormat = imgInput.RawFormat;

//get image original width and height
int intOldWidth = imgInput.Width;
int intOldHeight = imgInput.Height;

//determine if landscape or portrait
int intMaxSide;

if (intOldWidth >= intOldHeight)
{
intMaxSide = intOldWidth;
}
else
{
intMaxSide = intOldHeight;
}


if (intMaxSide > MaxSideSize)
{
//set new width and height
double dblCoef = MaxSideSize / (double)intMaxSide;
intNewWidth = Convert.ToInt32(dblCoef * intOldWidth);
intNewHeight = Convert.ToInt32(dblCoef * intOldHeight);
}
else
{
intNewWidth = intOldWidth;
intNewHeight = intOldHeight;
}
//create new bitmap
Bitmap bmpResized = new Bitmap(imgInput, intNewWidth, intNewHeight);

//save bitmap to disk
bmpResized.Save(ImageSavePath, fmtImageFormat);

//release used resources
imgInput.Dispose();
bmpResized.Dispose();
}
catch (Exception ex)
{ }
}