Thursday, September 11, 2008

Optimising Images for Web Using c#

Useful function to optimise images for web using c#

public void OptimizeImage(string lcFilename, decimal widthRequired)
{

System.Drawing.Image originalimg = System.Drawing.Image.FromFile(lcFilename);

decimal _percentNeeded;

_percentNeeded = Convert.ToDecimal(widthRequired) / originalimg.Width;

Int32 lnWidth = Convert.ToInt32(widthRequired);

Int32 lnHeight = Convert.ToInt32(originalimg.Height * _percentNeeded);

System.Drawing.Bitmap bmpOut = null;

System.Drawing.Bitmap loBMP = new System.Drawing.Bitmap(lcFilename);

System.Drawing.Imaging.ImageFormat loFormat = loBMP.RawFormat;

decimal lnRatio;

int lnNewWidth = 0;

int lnNewHeight = 0;



if (loBMP.Width > loBMP.Height)
{

lnRatio = (decimal)lnWidth / loBMP.Width;

lnNewWidth = lnWidth;

decimal lnTemp = loBMP.Height * lnRatio;

lnNewHeight = (int)lnTemp;

}

else
{

lnRatio = (decimal)lnHeight / loBMP.Height;

lnNewHeight = lnHeight;

decimal lnTemp = loBMP.Width * lnRatio;

lnNewWidth = (int)lnTemp;

}

bmpOut = new System.Drawing.Bitmap(lnNewWidth, lnNewHeight);

System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmpOut);

g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

g.FillRectangle(System.Drawing.Brushes.White, 0, 0, lnNewWidth, lnNewHeight);

g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight);

string _tmpFile = System.Configuration.ConfigurationManager.AppSettings["ContentLocationRoot"] + "tmp.jpg";

bmpOut.Save(_tmpFile, System.Drawing.Imaging.ImageFormat.Jpeg);

loBMP.Dispose();
originalimg.Dispose();

System.IO.File.Delete(lcFilename);

System.IO.File.Copy(_tmpFile, lcFilename);
System.IO.File.Delete(_tmpFile);

}