Tuesday, October 6, 2009

ASP.NET/C# Upload & Resize Image

Here is source code used for resizing image by ASP.NET/C#. Hope it helps you.


//********Begin Resize image area********

int intWidth = 0;
int intHeight = 0;
string UlFileName = null;
string NewFileName = null;

intWidth = 100;
//*** Fix Width ***//
//intHeight = 0 '*** If = 0 Auto Re-Cal Size ***//
intHeight = 120;

UlFileName = "images/photos/2009/10/" + rdApplication[22].ToString();

//*** Save Images ***//
//this.fiUpload.SaveAs(Server.MapPath(UlFileName));

NewFileName = "images/photos/2009/10/Thumbnail_" + rdApplication[22].ToString();

System.Drawing.Image objGraphic = System.Drawing.Image.FromFile(Server.MapPath(UlFileName));

Bitmap objBitmap = default(Bitmap);
//*** Calculate Height ***//
if (intHeight > 0)
{
objBitmap = new Bitmap(objGraphic, intWidth, intHeight);
}
else
{
if (objGraphic.Width > intWidth)
{
double ratio = objGraphic.Height / objGraphic.Width;
intHeight = (int)ratio * (int)intWidth;
objBitmap = new Bitmap(objGraphic, intWidth, intHeight);
}
else
{
objBitmap = new Bitmap(objGraphic);
}
}

//*** Save As ***//
objBitmap.Save(Server.MapPath(NewFileName.ToString()), objGraphic.RawFormat);

//*** Close ***//
objGraphic.Dispose();

//*** View Images ***//
//this.imgPicture.Visible = true;
// this.imgPicture.ImageUrl = NewFileName;

//********End Resize image area********


REF: http://www.thaicreate.com/asp.net/c-sharp-asp.net-upload-resize-image.html

No comments: