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);

}

"Internet Explorer cannot display the webpage" error caused by ASP.NET file upload control

I recently encountered a problem with ASP.NET whilst using a file upload control. Initial thoughts were that it was related to the AJAX extensions I was using, however after a lot of playing about, i found adding the following line to the web.config file resolved the problem,



Basically the problem is caused by an ASP.NET limit of around 4MB for a file upload, the above setting tells ASP.NET to allow larger files to be attached / uploaded.

Hope this helps someone.

"Internet Explorer cannot display the webpage" error caused by ASP.NET file upload control

I recently encountered a problem with ASP.NET whilst using a file upload control. Initial thoughts were that it was related to the AJAX extensions I was using, however after a lot of playing about, i found adding the following line to the web.config file resolved the problem,



Basically the problem is caused by an ASP.NET limit of around 4MB for a file upload, the above setting tells ASP.NET to allow larger files to be attached / uploaded.

Hope this helps someone.