Return to Snippet

Revision: 34953
at November 12, 2010 12:25 by housecor


Updated Code
/// <summary>
		/// Save posted data to the db
		/// </summary>
		public void Save(object sender, EventArgs e)
		{
			if (!Page.IsValid) return;

			if (Request["ID"] != null) //so editing news
			{
				teamMember = GetTeamMember();
			}

			FileUpload fileUpload = ((FileUpload)Page.Master.FindControl("ContentPlaceHolder1").FindControl("fuPhoto"));
			if (fileUpload.HasFile)
			{
				//resize uploaded photo and save
				using (Bitmap img = ResizeImage(new Bitmap(fuPhoto.PostedFile.InputStream), MemberPhotoWidth, MemberPhotoHeight, FileResizeOptions.MaxWidthAndHeight))
				{
					var filename = System.IO.Path.GetFileName(fileUpload.PostedFile.FileName);
					var destination = Path.Combine(System.Configuration.ConfigurationManager.AppSettings["TeamMemberPhotosPath"], filename);

					switch (Path.GetExtension(fuPhoto.FileName).ToLower())
					{
						case ".png":
							img.Save(destination, System.Drawing.Imaging.ImageFormat.Png);
							break;
						default:
							img.Save(destination, System.Drawing.Imaging.ImageFormat.Jpeg);
							break;
					}
				}
			}

			teamMember.Name = txtName.Text;
			teamMember.Bio = txtBio.Text;
			teamMember.Modified = DateTime.Now;
			teamMember.Status = ddStatus.SelectedValue;
			teamMember.Photo = fuPhoto.FileName;

			if (Request["ID"] == null) //so adding
			{
				db.TeamMembers.InsertOnSubmit(teamMember);
			}

			db.SubmitChanges();

			Notification n = new Notification("Save Complete.", ScreenMessageType.Confirmation);
			Response.Redirect("/Admin/Team", true);
		}

		/// <summary>
		/// Do the actual resize of the image
		/// </summary>
		/// <param name="originalImg"></param>
		/// <param name="widthInPixels"></param>
		/// <param name="heightInPixels"></param>
		/// <returns></returns>
		public static Bitmap DoResize(Bitmap originalImg, int widthInPixels, int heightInPixels)
		{
			Bitmap bitmap;
			try
			{
				bitmap = new Bitmap(widthInPixels, heightInPixels);
				using (Graphics graphic = Graphics.FromImage(bitmap))
				{
					// Quality properties
					graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
					graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
					graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
					graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

					graphic.DrawImage(originalImg, 0, 0, widthInPixels, heightInPixels);
					return bitmap;
				}
			}
			finally
			{
				if (originalImg != null)
				{
					originalImg.Dispose();
				}
			}
		}

		/// <summary>
		/// Determine how the image will be resized.
		/// </summary>
		/// <param name="image"></param>
		/// <param name="width"></param>
		/// <param name="height"></param>
		/// <param name="resizeOptions"></param>
		/// <returns></returns>
		public static Bitmap ResizeImage(Bitmap image, int width, int height, FileResizeOptions resizeOptions)
		{
			float f_width;
			float f_height;
			float dim;
			switch (resizeOptions)
			{
				case FileResizeOptions.ExactWidthAndHeight:
					return DoResize(image, width, height);

				case FileResizeOptions.MaxHeight:
					f_width = image.Width;
					f_height = image.Height;

					if (f_height <= height)
						return DoResize(image, (int)f_width, (int)f_height);

					dim = f_width / f_height;
					width = (int)((float)(height) * dim);
					return DoResize(image, width, height);

				case FileResizeOptions.MaxWidth:
					f_width = image.Width;
					f_height = image.Height;

					if (f_width <= width)
						return DoResize(image, (int)f_width, (int)f_height);

					dim = f_width / f_height;
					height = (int)((float)(width) / dim);
					return DoResize(image, width, height);

				case FileResizeOptions.MaxWidthAndHeight:
					int tmpHeight = height;
					int tmpWidth = width;
					f_width = image.Width;
					f_height = image.Height;

					if (f_width <= width && f_height <= height)
						return DoResize(image, (int)f_width, (int)f_height);

					dim = f_width / f_height;

					// Check if the width is ok
					if (f_width < width)
						width = (int)f_width;
					height = (int)((float)(width) / dim);
					// The width is too width
					if (height > tmpHeight)
					{
						if (f_height < tmpHeight)
							height = (int)f_height;
						else
							height = tmpHeight;
						width = (int)((float)(height) * dim);
					}
					return DoResize(image, width, height);
				default:
					return image;
			}
		}
	}

Revision: 34952
at November 12, 2010 12:23 by housecor


Updated Code
public partial class Manage : System.Web.UI.Page
	{
		private SSHPortalDataClassesDataContext db = new SSHPortalDataClassesDataContext();
		private SSH_Portal.App_Data.TeamMember teamMember = new SSH_Portal.App_Data.TeamMember();
		private const int MemberPhotoWidth = 80;
		private const int MemberPhotoHeight = 100;
		private List<string> ValidFileExtensions = new List<string>();

		protected void Page_Load(object sender, EventArgs e)
		{
			ValidFileExtensions.Add("jpg");
			ValidFileExtensions.Add("jpeg");
			ValidFileExtensions.Add("png");

			if (!IsPostBack)
			{
				litTitle.Text = (Request["ID"] == null) ? "Add" : "Edit";
				SetFields();
			}
		}


		/// <summary>
		/// Returns true if the filetype uploaded has an accepted extension.
		/// </summary>
		/// <param name="filename"></param>
		/// <returns></returns>
		private bool ValidFileType(string filename)
		{
			if (filename.Length == 0) return true;
			string uploadedFileExtension = Path.GetExtension(filename).Substring(1);



			foreach (string extension in ValidFileExtensions)
			{
				if (uploadedFileExtension == extension) return true;
			}
			return false;
		}

		/// <summary>
		/// Save posted data to the db
		/// </summary>
		public void Save(object sender, EventArgs e)
		{
			if (!Page.IsValid) return;

			if (Request["ID"] != null) //so editing news
			{
				teamMember = GetTeamMember();
			}

			FileUpload fileUpload = ((FileUpload)Page.Master.FindControl("ContentPlaceHolder1").FindControl("fuPhoto"));
			if (fileUpload.HasFile)
			{
				//resize uploaded photo and save
				using (Bitmap img = ResizeImage(new Bitmap(fuPhoto.PostedFile.InputStream), MemberPhotoWidth, MemberPhotoHeight, FileResizeOptions.MaxWidthAndHeight))
				{
					var filename = System.IO.Path.GetFileName(fileUpload.PostedFile.FileName);
					var destination = Path.Combine(System.Configuration.ConfigurationManager.AppSettings["TeamMemberPhotosPath"], filename);

					switch (Path.GetExtension(fuPhoto.FileName).ToLower())
					{
						case ".png":
							img.Save(destination, System.Drawing.Imaging.ImageFormat.Png);
							break;
						default:
							img.Save(destination, System.Drawing.Imaging.ImageFormat.Jpeg);
							break;
					}
				}
			}

			teamMember.Name = txtName.Text;
			teamMember.Bio = txtBio.Text;
			teamMember.Modified = DateTime.Now;
			teamMember.Status = ddStatus.SelectedValue;
			teamMember.Photo = fuPhoto.FileName;

			if (Request["ID"] == null) //so adding
			{
				db.TeamMembers.InsertOnSubmit(teamMember);
			}

			db.SubmitChanges();

			Notification n = new Notification("Save Complete.", ScreenMessageType.Confirmation);
			Response.Redirect("/Admin/Team", true);
		}

		/// <summary>
		/// Do the actual resize of the image
		/// </summary>
		/// <param name="originalImg"></param>
		/// <param name="widthInPixels"></param>
		/// <param name="heightInPixels"></param>
		/// <returns></returns>
		public static Bitmap DoResize(Bitmap originalImg, int widthInPixels, int heightInPixels)
		{
			Bitmap bitmap;
			try
			{
				bitmap = new Bitmap(widthInPixels, heightInPixels);
				using (Graphics graphic = Graphics.FromImage(bitmap))
				{
					// Quality properties
					graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
					graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
					graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
					graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

					graphic.DrawImage(originalImg, 0, 0, widthInPixels, heightInPixels);
					return bitmap;
				}
			}
			finally
			{
				if (originalImg != null)
				{
					originalImg.Dispose();
				}
			}
		}

		/// <summary>
		/// Determine how the image will be resized.
		/// </summary>
		/// <param name="image"></param>
		/// <param name="width"></param>
		/// <param name="height"></param>
		/// <param name="resizeOptions"></param>
		/// <returns></returns>
		public static Bitmap ResizeImage(Bitmap image, int width, int height, FileResizeOptions resizeOptions)
		{
			float f_width;
			float f_height;
			float dim;
			switch (resizeOptions)
			{
				case FileResizeOptions.ExactWidthAndHeight:
					return DoResize(image, width, height);

				case FileResizeOptions.MaxHeight:
					f_width = image.Width;
					f_height = image.Height;

					if (f_height <= height)
						return DoResize(image, (int)f_width, (int)f_height);

					dim = f_width / f_height;
					width = (int)((float)(height) * dim);
					return DoResize(image, width, height);

				case FileResizeOptions.MaxWidth:
					f_width = image.Width;
					f_height = image.Height;

					if (f_width <= width)
						return DoResize(image, (int)f_width, (int)f_height);

					dim = f_width / f_height;
					height = (int)((float)(width) / dim);
					return DoResize(image, width, height);

				case FileResizeOptions.MaxWidthAndHeight:
					int tmpHeight = height;
					int tmpWidth = width;
					f_width = image.Width;
					f_height = image.Height;

					if (f_width <= width && f_height <= height)
						return DoResize(image, (int)f_width, (int)f_height);

					dim = f_width / f_height;

					// Check if the width is ok
					if (f_width < width)
						width = (int)f_width;
					height = (int)((float)(width) / dim);
					// The width is too width
					if (height > tmpHeight)
					{
						if (f_height < tmpHeight)
							height = (int)f_height;
						else
							height = tmpHeight;
						width = (int)((float)(height) * dim);
					}
					return DoResize(image, width, height);
				default:
					return image;
			}
		}
	}

Revision: 34951
at November 12, 2010 12:21 by housecor


Updated Code
public partial class Manage : System.Web.UI.Page
	{
		private SSHPortalDataClassesDataContext db = new SSHPortalDataClassesDataContext();
		private SSH_Portal.App_Data.TeamMember teamMember = new SSH_Portal.App_Data.TeamMember();
		private const int MemberPhotoWidth = 80;
		private const int MemberPhotoHeight = 100;
		private List<string> ValidFileExtensions = new List<string>();

		protected void Page_Load(object sender, EventArgs e)
		{
			ValidFileExtensions.Add("jpg");
			ValidFileExtensions.Add("jpeg");
			ValidFileExtensions.Add("png");

			if (!IsPostBack)
			{
				litTitle.Text = (Request["ID"] == null) ? "Add" : "Edit";
				SetFields();
			}
		}

		/// <summary>
		/// Populate fields on initial page load
		/// </summary>
		private void SetFields()
		{
			if (Request["ID"] != null)
			{
				teamMember = GetTeamMember();
				if (teamMember == null) throw new HttpException(404, "file not found"); //so the ID requested wasn't found. Redirect to 404.

				txtName.Text = teamMember.Name;
				txtBio.Text = teamMember.Bio;
				ddStatus.SelectedValue = teamMember.Status;
			}
		}

		/// <summary>
		/// Validate file meets all qualifications. Show error message if it doesn't.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		public void ValidatePhotoUpload(object sender, ServerValidateEventArgs e)
		{
			string filename = ((FileUpload)Page.Master.FindControl("ContentPlaceHolder1").FindControl("fuPhoto")).FileName;
			CustomValidator validator = ((CustomValidator)sender);

			//if file wasn't uploaded at all, exit.
			if (filename.Length == 0) return;

			//make sure the file uploaded is of an accepted type
			if (!ValidFileType(filename))
			{
				e.IsValid = false;
				string errorMessage = "Only files of the following type are accepted: ";
				
				foreach (string extension in ValidFileExtensions)
				{
					errorMessage += extension + " ";
				}

				validator.ErrorMessage = errorMessage;
				return;
			}

			//make sure the file is under the size limit
			int filesizeInBytes = ((FileUpload)Page.Master.FindControl("ContentPlaceHolder1").FindControl("fuPhoto")).PostedFile.ContentLength;
			const int maxFileSizeInMB = 4;
			const int maxFileSizeInBytes = maxFileSizeInMB * 1000000;
			if (filesizeInBytes > maxFileSizeInBytes)
			{
				e.IsValid = false;
				validator.ErrorMessage = "The max file size for uploaded files is " + maxFileSizeInMB + "MB.";
				return;
			}

			//make sure a file doesn't already exist on the server with the same name
			int numFilesWithSameName = (from f in db.TeamMembers
										where f.Photo == filename
										select f).Count();
			if (numFilesWithSameName > 0)
			{
				validator.ErrorMessage = "A file already exists with the name " + filename + ". Please rename the file and upload it again.";
				e.IsValid = false;
				return;
			}

			//validate photo aspect ratio is 8x10 for consistency
			System.Drawing.Image file = System.Drawing.Image.FromStream(fuPhoto.PostedFile.InputStream);
			float aspectRatio = ((float)file.Height / file.Width);
			if (aspectRatio != 1.25)
			{
				validator.ErrorMessage = "For consistency, photos should be a head shot with an aspect ratio of 8x10. For example, if you upload an image that is 1000 pixels tall, it must be 800 pixels wide. Please crop the image to 8x10 and reupload.";
				e.IsValid = false;
				return;
			}
			
			//validate photo meets minimum dimsension requirements
			if (file.Width < MemberPhotoWidth || file.Height < MemberPhotoHeight)
			{
				validator.ErrorMessage = "The photo must be at least + " MemberPhotoHeight + " pixels tall and " + MemberPhotoWidth + " pixels wide.";
				e.IsValid = false;
				return;
			}

			e.IsValid = true;
		}

		/// <summary>
		/// Returns true if the filetype uploaded has an accepted extension.
		/// </summary>
		/// <param name="filename"></param>
		/// <returns></returns>
		private bool ValidFileType(string filename)
		{
			if (filename.Length == 0) return true;
			string uploadedFileExtension = Path.GetExtension(filename).Substring(1);



			foreach (string extension in ValidFileExtensions)
			{
				if (uploadedFileExtension == extension) return true;
			}
			return false;
		}

		/// <summary>
		/// Save posted data to the db
		/// </summary>
		public void Save(object sender, EventArgs e)
		{
			if (!Page.IsValid) return;

			if (Request["ID"] != null) //so editing news
			{
				teamMember = GetTeamMember();
			}

			FileUpload fileUpload = ((FileUpload)Page.Master.FindControl("ContentPlaceHolder1").FindControl("fuPhoto"));
			if (fileUpload.HasFile)
			{
				//resize uploaded photo and save
				using (Bitmap img = ResizeImage(new Bitmap(fuPhoto.PostedFile.InputStream), MemberPhotoWidth, MemberPhotoHeight, FileResizeOptions.MaxWidthAndHeight))
				{
					var filename = System.IO.Path.GetFileName(fileUpload.PostedFile.FileName);
					var destination = Path.Combine(System.Configuration.ConfigurationManager.AppSettings["TeamMemberPhotosPath"], filename);

					switch (Path.GetExtension(fuPhoto.FileName).ToLower())
					{
						case ".png":
							img.Save(destination, System.Drawing.Imaging.ImageFormat.Png);
							break;
						default:
							img.Save(destination, System.Drawing.Imaging.ImageFormat.Jpeg);
							break;
					}
				}
			}

			teamMember.Name = txtName.Text;
			teamMember.Bio = txtBio.Text;
			teamMember.Modified = DateTime.Now;
			teamMember.Status = ddStatus.SelectedValue;
			teamMember.Photo = fuPhoto.FileName;

			if (Request["ID"] == null) //so adding
			{
				db.TeamMembers.InsertOnSubmit(teamMember);
			}

			db.SubmitChanges();

			Notification n = new Notification("Save Complete.", ScreenMessageType.Confirmation);
			Response.Redirect("/Admin/Team", true);
		}

		/// <summary>
		/// Get a team member based on the ID in the URL
		/// </summary>
		/// <returns></returns>
		private TeamMember GetTeamMember()
		{
			return (from m in db.TeamMembers
					where m.TeamMemberID == Convert.ToInt16(Request["ID"])
					select m).FirstOrDefault();
		}

		/// <summary>
		/// Do the actual resize of the image
		/// </summary>
		/// <param name="originalImg"></param>
		/// <param name="widthInPixels"></param>
		/// <param name="heightInPixels"></param>
		/// <returns></returns>
		public static Bitmap DoResize(Bitmap originalImg, int widthInPixels, int heightInPixels)
		{
			Bitmap bitmap;
			try
			{
				bitmap = new Bitmap(widthInPixels, heightInPixels);
				using (Graphics graphic = Graphics.FromImage(bitmap))
				{
					// Quality properties
					graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
					graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
					graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
					graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

					graphic.DrawImage(originalImg, 0, 0, widthInPixels, heightInPixels);
					return bitmap;
				}
			}
			finally
			{
				if (originalImg != null)
				{
					originalImg.Dispose();
				}
			}
		}

		/// <summary>
		/// Determine how the image will be resized.
		/// </summary>
		/// <param name="image"></param>
		/// <param name="width"></param>
		/// <param name="height"></param>
		/// <param name="resizeOptions"></param>
		/// <returns></returns>
		public static Bitmap ResizeImage(Bitmap image, int width, int height, FileResizeOptions resizeOptions)
		{
			float f_width;
			float f_height;
			float dim;
			switch (resizeOptions)
			{
				case FileResizeOptions.ExactWidthAndHeight:
					return DoResize(image, width, height);

				case FileResizeOptions.MaxHeight:
					f_width = image.Width;
					f_height = image.Height;

					if (f_height <= height)
						return DoResize(image, (int)f_width, (int)f_height);

					dim = f_width / f_height;
					width = (int)((float)(height) * dim);
					return DoResize(image, width, height);

				case FileResizeOptions.MaxWidth:
					f_width = image.Width;
					f_height = image.Height;

					if (f_width <= width)
						return DoResize(image, (int)f_width, (int)f_height);

					dim = f_width / f_height;
					height = (int)((float)(width) / dim);
					return DoResize(image, width, height);

				case FileResizeOptions.MaxWidthAndHeight:
					int tmpHeight = height;
					int tmpWidth = width;
					f_width = image.Width;
					f_height = image.Height;

					if (f_width <= width && f_height <= height)
						return DoResize(image, (int)f_width, (int)f_height);

					dim = f_width / f_height;

					// Check if the width is ok
					if (f_width < width)
						width = (int)f_width;
					height = (int)((float)(width) / dim);
					// The width is too width
					if (height > tmpHeight)
					{
						if (f_height < tmpHeight)
							height = (int)f_height;
						else
							height = tmpHeight;
						width = (int)((float)(height) * dim);
					}
					return DoResize(image, width, height);
				default:
					return image;
			}
		}
	}

Revision: 34950
at October 31, 2010 04:27 by housecor


Updated Code
public partial class Manage : System.Web.UI.Page
	{
		private SSHPortalDataClassesDataContext db = new SSHPortalDataClassesDataContext();
		private SSH_Portal.App_Data.TeamMember teamMember = new SSH_Portal.App_Data.TeamMember();
		private const int MemberPhotoWidth = 80;
		private const int MemberPhotoHeight = 100;
		private List<string> ValidFileExtensions = new List<string>();

		protected void Page_Load(object sender, EventArgs e)
		{
			ValidFileExtensions.Add("jpg");
			ValidFileExtensions.Add("jpeg");
			ValidFileExtensions.Add("png");

			if (!IsPostBack)
			{
				litTitle.Text = (Request["ID"] == null) ? "Add" : "Edit";
				SetFields();
			}
		}

		/// <summary>
		/// Populate fields on initial page load
		/// </summary>
		private void SetFields()
		{
			if (Request["ID"] != null)
			{
				teamMember = GetTeamMember();
				if (teamMember == null) throw new HttpException(404, "file not found"); //so the ID requested wasn't found. Redirect to 404.

				txtName.Text = teamMember.Name;
				txtBio.Text = teamMember.Bio;
				ddStatus.SelectedValue = teamMember.Status;
			}
		}

		/// <summary>
		/// Validate file meets all qualifications. Show error message if it doesn't.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		public void ValidatePhotoUpload(object sender, ServerValidateEventArgs e)
		{
			string filename = ((FileUpload)Page.Master.FindControl("ContentPlaceHolder1").FindControl("fuPhoto")).FileName;
			CustomValidator validator = ((CustomValidator)sender);

			//if file wasn't uploaded at all, exit.
			if (filename.Length == 0) return;

			//make sure the file uploaded is of an accepted type
			if (!ValidFileType(filename))
			{
				e.IsValid = false;
				string errorMessage = "Only files of the following type are accepted: ";
				
				foreach (string extension in ValidFileExtensions)
				{
					errorMessage += extension + " ";
				}

				validator.ErrorMessage = errorMessage;
				return;
			}

			//make sure the file is under the size limit
			int filesizeInBytes = ((FileUpload)Page.Master.FindControl("ContentPlaceHolder1").FindControl("fuPhoto")).PostedFile.ContentLength;
			const int maxFileSizeInMB = 4;
			const int maxFileSizeInBytes = maxFileSizeInMB * 1000000;
			if (filesizeInBytes > maxFileSizeInBytes)
			{
				e.IsValid = false;
				validator.ErrorMessage = "The max file size for uploaded files is " + maxFileSizeInMB + "MB.";
				return;
			}

			//make sure a file doesn't already exist on the server with the same name
			int numFilesWithSameName = (from f in db.TeamMembers
										where f.Photo == filename
										select f).Count();
			if (numFilesWithSameName > 0)
			{
				validator.ErrorMessage = "A file already exists with the name " + filename + ". Please rename the file and upload it again.";
				e.IsValid = false;
				return;
			}

			//validate photo aspect ratio is 8x10 for consistency
			System.Drawing.Image file = System.Drawing.Image.FromStream(fuPhoto.PostedFile.InputStream);
			float aspectRatio = ((float)file.Height / file.Width);
			if (aspectRatio != 1.25)
			{
				validator.ErrorMessage = "For consistency, photos should be a head shot with an aspect ratio of 8x10. For example, if you upload an image that is 1000 pixels tall, it must be 800 pixels wide. Please crop the image to 8x10 and reupload.";
				e.IsValid = false;
				return;
			}
			
			//validate photo meets minimum dimsension requirements
			if (file.Width < MemberPhotoWidth || file.Height < MemberPhotoHeight)
			{
				validator.ErrorMessage = "The photo must be at least 100 pixels tall and 80 pixels wide.";
				e.IsValid = false;
				return;
			}

			e.IsValid = true;
		}

		/// <summary>
		/// Returns true if the filetype uploaded has an accepted extension.
		/// </summary>
		/// <param name="filename"></param>
		/// <returns></returns>
		private bool ValidFileType(string filename)
		{
			if (filename.Length == 0) return true;
			string uploadedFileExtension = Path.GetExtension(filename).Substring(1);



			foreach (string extension in ValidFileExtensions)
			{
				if (uploadedFileExtension == extension) return true;
			}
			return false;
		}

		/// <summary>
		/// Save posted data to the db
		/// </summary>
		public void Save(object sender, EventArgs e)
		{
			if (!Page.IsValid) return;

			if (Request["ID"] != null) //so editing news
			{
				teamMember = GetTeamMember();
			}

			FileUpload fileUpload = ((FileUpload)Page.Master.FindControl("ContentPlaceHolder1").FindControl("fuPhoto"));
			if (fileUpload.HasFile)
			{
				//resize uploaded photo and save
				using (Bitmap img = ResizeImage(new Bitmap(fuPhoto.PostedFile.InputStream), MemberPhotoWidth, MemberPhotoHeight, FileResizeOptions.MaxWidthAndHeight))
				{
					var filename = System.IO.Path.GetFileName(fileUpload.PostedFile.FileName);
					var destination = Path.Combine(System.Configuration.ConfigurationManager.AppSettings["TeamMemberPhotosPath"], filename);

					switch (Path.GetExtension(fuPhoto.FileName).ToLower())
					{
						case ".png":
							img.Save(destination, System.Drawing.Imaging.ImageFormat.Png);
							break;
						default:
							img.Save(destination, System.Drawing.Imaging.ImageFormat.Jpeg);
							break;
					}
				}
			}

			teamMember.Name = txtName.Text;
			teamMember.Bio = txtBio.Text;
			teamMember.Modified = DateTime.Now;
			teamMember.Status = ddStatus.SelectedValue;
			teamMember.Photo = fuPhoto.FileName;

			if (Request["ID"] == null) //so adding
			{
				db.TeamMembers.InsertOnSubmit(teamMember);
			}

			db.SubmitChanges();

			Notification n = new Notification("Save Complete.", ScreenMessageType.Confirmation);
			Response.Redirect("/Admin/Team", true);
		}

		/// <summary>
		/// Get a team member based on the ID in the URL
		/// </summary>
		/// <returns></returns>
		private TeamMember GetTeamMember()
		{
			return (from m in db.TeamMembers
					where m.TeamMemberID == Convert.ToInt16(Request["ID"])
					select m).FirstOrDefault();
		}

		/// <summary>
		/// Do the actual resize of the image
		/// </summary>
		/// <param name="originalImg"></param>
		/// <param name="widthInPixels"></param>
		/// <param name="heightInPixels"></param>
		/// <returns></returns>
		public static Bitmap DoResize(Bitmap originalImg, int widthInPixels, int heightInPixels)
		{
			Bitmap bitmap;
			try
			{
				bitmap = new Bitmap(widthInPixels, heightInPixels);
				using (Graphics graphic = Graphics.FromImage(bitmap))
				{
					// Quality properties
					graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
					graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
					graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
					graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

					graphic.DrawImage(originalImg, 0, 0, widthInPixels, heightInPixels);
					return bitmap;
				}
			}
			finally
			{
				if (originalImg != null)
				{
					originalImg.Dispose();
				}
			}
		}

		/// <summary>
		/// Determine how the image will be resized.
		/// </summary>
		/// <param name="image"></param>
		/// <param name="width"></param>
		/// <param name="height"></param>
		/// <param name="resizeOptions"></param>
		/// <returns></returns>
		public static Bitmap ResizeImage(Bitmap image, int width, int height, FileResizeOptions resizeOptions)
		{
			float f_width;
			float f_height;
			float dim;
			switch (resizeOptions)
			{
				case FileResizeOptions.ExactWidthAndHeight:
					return DoResize(image, width, height);

				case FileResizeOptions.MaxHeight:
					f_width = image.Width;
					f_height = image.Height;

					if (f_height <= height)
						return DoResize(image, (int)f_width, (int)f_height);

					dim = f_width / f_height;
					width = (int)((float)(height) * dim);
					return DoResize(image, width, height);

				case FileResizeOptions.MaxWidth:
					f_width = image.Width;
					f_height = image.Height;

					if (f_width <= width)
						return DoResize(image, (int)f_width, (int)f_height);

					dim = f_width / f_height;
					height = (int)((float)(width) / dim);
					return DoResize(image, width, height);

				case FileResizeOptions.MaxWidthAndHeight:
					int tmpHeight = height;
					int tmpWidth = width;
					f_width = image.Width;
					f_height = image.Height;

					if (f_width <= width && f_height <= height)
						return DoResize(image, (int)f_width, (int)f_height);

					dim = f_width / f_height;

					// Check if the width is ok
					if (f_width < width)
						width = (int)f_width;
					height = (int)((float)(width) / dim);
					// The width is too width
					if (height > tmpHeight)
					{
						if (f_height < tmpHeight)
							height = (int)f_height;
						else
							height = tmpHeight;
						width = (int)((float)(height) * dim);
					}
					return DoResize(image, width, height);
				default:
					return image;
			}
		}
	}

Revision: 34949
at October 31, 2010 04:18 by housecor


Initial Code
Also see SSH Portal Meet the Team Manage page.

Initial URL
http://mironabramson.com/blog/post/2007/10/Resize-images-\\\\\\\\\\\\\\\'on-the-fly\\\\\\\\\\\\\\\'-while-uploading.aspx

Initial Description

                                

Initial Title
Resize uploaded image on the fly

Initial Tags

                                

Initial Language
C#