title: Image Resize in C# - Algorith to determine resize dimensions (height and width)
body: <p>I need to scale down an image that has a height or width greater than a predefined pixel value.</p>
  
  <p>I wrote some code that takes a look at the original image, checks to see if either the width, the height, or the height and width are greater than the Max Width/Max Height settings.</p>
  
  <p>I now need to figure out what dimensions to resize to based on the max of the latter value.</p>
  
  <p>For example: If the image is <code>900h x 300w</code> and the MAX Height is <code>700h</code> I will need to resize the height to <code>700</code> and the width to <code>????</code> &lt;-- this is what I need to calculate.. </p>
  
  <p>Creating and saving the image file is simple, and outside the scope of this post:</p>
  
  <pre><code>// First I get the max height and width allowed:
  
  int resizeMaxHeight =  int.Parse(Utility.GetConfigValue("ResizeMaxHeight")); // in config: 700px
  int resizeMaxWidth =  int.Parse(Utility.GetConfigValue("ResizeMaxWidth"));  //  in config: 500px
  
  // Save original: 
  try
  {
      filebase.SaveAs(savedFileName);
  }
  catch (System.IO.DirectoryNotFoundException ex)
  {
      Logger.Instance.LogException(ex, 0, "FileTransfer");
  }
  
  // Determin original dimensions:
  Image image = System.Drawing.Image.FromFile(Server.MapPath(savedFileName));
  
  int resizeHeight, resizeWidth;
  bool doResize = true;
  
  // both height and width are greater than the allowed height and width:
  if (image.Width &gt; resizeMaxWidth &amp;&amp; image.Height &gt; resizeMaxHeight)
  {
      if (image.Height &gt; image.Width) 
          resizeHeight = resizeMaxHeight;
      else
          resizeWidth = resizeMaxWidth;
  }
  else if (image.Width &gt; resizeMaxWidth)
  {
      // width is too great, but height is ok
      resizeWidth = resizeMaxWidth;
  }
  else if (image.Height &gt; resizeMaxHeight)
  {
      // height is too great, but width is ok
      resizeHeight = resizeMaxHeight;
  }
  else
  {
      // image is ok size, don't resize:
      doResize = false;
  }
  </code></pre>
  
  <p>Create thumbnail:
  This is what I'm working now... not complete:</p>
  
  <pre><code>if (doResize)
  {
      ImageUtilities.ResizeImage(image, resizeWidth, resizeHeight);
  }
  </code></pre>