title: Resize image in PHP
body: <p>I want to write some PHP code that automatically resizes any image uploaded via a form to 147x147px, but I have no idea how to go about it (I'm a relative PHP novice).</p>
  <p>So far, I've got images uploading successfully, filetypes being recognized and names cleaned up, but I'd like to add the resize functionality into the code. For example, I've got a test image that is 2.3MB, and 1331x1331 in dimension, and I'd like the code to size it down, which I'm guessing will dramatically compress the file size of the image, too.</p>
  <p>So far, I've got the following:</p>
  <pre><code>if ($_FILES) {
                  //Put file properties into variables
                  $file_name = $_FILES['profile-image']['name'];
                  $file_size = $_FILES['profile-image']['size'];
                  $file_tmp_name = $_FILES['profile-image']['tmp_name'];
                  
                  //Determine filetype
                  switch ($_FILES['profile-image']['type']) {
                      case 'image/jpeg': $ext = &quot;jpg&quot;; break;
                      case 'image/png': $ext = &quot;png&quot;; break;
                      default: $ext = ''; break;
                  }
                  
                  if ($ext) {
                      //Check filesize
                      if ($file_size &lt; 500000) {
                          //Process file - clean up filename and move to safe location
                          $n = &quot;$file_name&quot;;
                          $n = ereg_replace(&quot;[^A-Za-z0-9.]&quot;, &quot;&quot;, $n);
                          $n = strtolower($n);
                          $n = &quot;avatars/$n&quot;;
                          move_uploaded_file($file_tmp_name, $n);
                      } else {
                          $bad_message = &quot;Please ensure your chosen file is less than 5MB.&quot;;
                      }
                  } else {
                      $bad_message = &quot;Please ensure your image is of filetype .jpg or.png.&quot;;
                  }
              }
  $query = &quot;INSERT INTO users (image) VALUES ('$n')&quot;;
  mysql_query($query) or die(&quot;Insert failed. &quot; . mysql_error() . &quot;&lt;br /&gt;&quot; . $query);
  </code></pre>