Saturday, December 1, 2007

Image manipulation in ASP.NET: Loading & Resizing

How to load an image from your system and return it to the system or browser using the correct mime type by detecting the image format of the loaded file. You can also resize the image making a simplistic thumbnail.

Here I use File-browser for uploading image and get the size of the image to be resulted one. I save in physical drive.

if ((FileUpload1.PostedFile != null) && (FileUpload1.PostedFile.ContentLength > 0))

{

string fn = FileUpload1.PostedFile.FileName;

try

{

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

}

catch (Exception ex)

{

Response.Write(ex.Message);

}

if (ddlHeight.SelectedValue != "0")

{

height = Convert.ToInt32(ddlHeight.SelectedValue);

}

else

{

height = 100;

}

if (ddlWidth.SelectedValue != "0")

{

width = Convert.ToInt32(ddlWidth.SelectedValue);

}

else

{

width = 100;

}


thumb = originalimg.GetThumbnailImage(width, height, null, inp);


//Response.ContentType = "image/jpeg"; //Image Type

//thumb.Save(Response.OutputStream, ImageFormat.Jpeg); //It's going to display ur image in page itself


thumb.Save("D:\\Images\\abc.jpg", ImageFormat.Jpeg); // to save image in location


originalimg.Dispose();

thumb.Dispose();

}


No comments: