Friday, September 24, 2010

Image Resizing in c#

Resizing the image in C#

This is a very simple example for image resizing while uploading through fileupload control.

//OriginalFile - Path for the original image
//NewFile - Path for the New image
//NewWidth - Define new width
//MaxHeight - Define MAX Height
//OnlyResizeIfWider - True if you want to resize images which have greater dimensions from defined new dimensions.
public void ResizeImage(string OriginalFile, string NewFile, int NewWidth, int MaxHeight, bool OnlyResizeIfWider)


System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(OriginalFile);
// Prevent using images internal thumbnail


if (OnlyResizeIfWider)


if (FullsizeImage.Width <= NewWidth)


NewWidth = FullsizeImage.Width;


int NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width;

if (NewHeight > MaxHeight)


// Resize with height instead

NewWidth = FullsizeImage.Width * MaxHeight / FullsizeImage.Height;

NewHeight = MaxHeight;

System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero);
// Clear handle to original file so that we can overwrite it if necessary

// Save resized picture



No comments:

Post a Comment