Thursday, February 26, 2009

Image resizing asp.net c#

Some times you want to resize images as per your required size using asp.net.


using System.Drawing;
using System.Drawing.Drawing2D;

Resizeimage(intheight, intwidth, userPostedFile.FileName.ToString(), userPostedFile.InputStream);


public string Resizeimage(int intHeight, int intWidth, string ImageUrl, System.IO.Stream Buffer)
{
try
{ string filepath = ConfigurationManager.AppSettings["UploadURL"];
string savepath = ConfigurationManager.AppSettings["SaveURL"];
string filename;
string[] imagefilename = new string[2];
char[] split ={ '.' };
imagefilename = ImageUrl.Split(split);
imagefilename[0] = imagefilename[0].Replace(" ", "_") + DateTime.Now.ToFileTime();
filename = (imagefilename[0].ToString() + "." + imagefilename[1].ToString());
System.Drawing.Image image = System.Drawing.Image.FromStream(Buffer);
int srcWidth = image.Width;
int srcHeight = image.Height;
Decimal sizeRatio = ((Decimal)srcHeight / srcWidth);
Bitmap bmp = new Bitmap(intWidth, intHeight);
System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp);
gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, intWidth, intHeight);
gr.DrawImage(image, rectDestination, 0, 0, srcWidth, srcHeight, GraphicsUnit.Pixel);
bmp.Save(filepath + intHeight.ToString() + System.IO.Path.GetFileName(filename));
string strImageUrl=savepath+intHeight.ToString() + System.IO.Path.GetFileName(filename);
bmp.Dispose();
image.Dispose();
return strImageUrl;
}
catch (Exception ex)
{
// MessageBox("Some Error has occured while uploading the images");
}
return "";
}

No comments:

Post a Comment