Bitmap Resize help please
I run this code on all upload images to make them fit right, and keep file size down. It resizes an image down to a width of 500px and the correct height(aspect ratio), if the image has a width > 500px. It works 90% of the time. In fact it worked 100% for data migration, but has discovered problems live. For instance an image 1024x768 will not shrink because the height comes out 0. My original method to find the new height is commented out at the top.
anbody know a fool proof method?
Code:
public static System.Drawing.Bitmap WebOptimize(System.Drawing.Bitmap bmp)
{
if(bmp.Width > 500)
{ //((int)( 100 * (int)System.Math.Round(((decimal)500)/((decimal)bmp.Width)) * bmp.Height) / 100);
double iWidth = 0; //500 / bmp.Width;
double iRatioPercent = 0; //100 * iWidth
double iHeight = 0; //iRatioPercent * bmp.Height
int nHeight = 0; //iHeight / 100
iWidth = 500 / bmp.Width;
//if(iWidth <= 0){iWidth = 1;}
iRatioPercent = 100 * iWidth;
//if(iRatioPercent <= 0){iRatioPercent = 1;}
iHeight = iRatioPercent * bmp.Height;
//if(iHeight < 0){iHeight = System.Math.Round(iHeight);}
iHeight = iHeight / 100;
nHeight =(int)System.Math.Round(iHeight);
if(nHeight > 0)
{
System.Drawing.Bitmap nBmp = new System.Drawing.Bitmap(500, nHeight);
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(nBmp);
g.DrawImage(bmp, new System.Drawing.Rectangle(0, 0, 500, nHeight), 0, 0, bmp.Width, bmp.Height, System.Drawing.GraphicsUnit.Pixel);
return nBmp;
}
}
return bmp;
}