title: Algorithm to resize image and maintain aspect ratio to fit iPhone
body: <p>I'm creating a web service for an iPhone app to interact with.</p>
  
  <p>When my client uploads images server-side, I want my php script to resize the image, <strong>whilst maintaining the aspect ratio</strong>, so that it will fit onto the iPhone screen. (i.e. the longest side is &lt;= 960 and the shortest &lt;= 640</p>
  
  <p>I've created a mock-up in JS, simply because I find it easier to do quickly.</p>
  
  <p>I'm pretty sure, though I may be wrong, that this isn't the most efficient way of doing it. Could someone correct me with either better logic (especially the bit at the start), or a more mathematical way of approaching this? </p>
  
  <pre><code>var w = 960, h = 960, new_w, new_h;
  if (w &gt;= h &amp;&amp; w &gt; 960 || h &gt;= w &amp;&amp; h &gt; 960 || w &gt;= h &amp;&amp; h &gt; 640 || h &gt;= w &amp;&amp; w &gt; 640) {
      if (w &gt; h) {
          if (w&gt;960) {
              new_w = 960;
              new_h = h*(new_w/w);
          }
          if (h&gt;640) {
              new_h = 640;
              new_w = w*(new_h/h);
          }
      }
      else {
          if (h&gt;960) {
              new_h = 960;
              new_w = w*(new_h/h);
          }
          if (w&gt;640) {
              new_w = 640;
              new_h = h*(new_w/w);
          }
      }
  }
  </code></pre>