title: Efficient JPEG Image Resizing in PHP
body: <p>What's the most efficient way to resize large images in PHP?</p>
  
  <p>I'm currently using the <a href="http://en.wikipedia.org/wiki/GD_Graphics_Library" rel="noreferrer">GD</a> function imagecopyresampled to take high resolution images, and cleanly resize them down to a size for web viewing (roughly 700 pixels wide by 700 pixels tall).</p>
  
  <p>This works great on small (under 2 MB) photos and the entire resize operation takes less than a second on the server. However, the site will eventually service photographers who may be uploading images up to 10 MB in size (or images up to 5000x4000 pixels in size).</p>
  
  <p>Doing this kind of resize operation with large images tends to increase the memory usage by a very large margin (larger images can spike the memory usage for the script past 80 MB). Is there any way to make this resize operation more efficient? Should I be using an alternate image library such as <a href="http://en.wikipedia.org/wiki/ImageMagick" rel="noreferrer">ImageMagick</a>?</p>
  
  <p>Right now, the resize code looks something like this</p>
  
  <pre><code>function makeThumbnail($sourcefile, $endfile, $thumbwidth, $thumbheight, $quality) {
      // Takes the sourcefile (path/to/image.jpg) and makes a thumbnail from it
      // and places it at endfile (path/to/thumb.jpg).
  
      // Load image and get image size.
      $img = imagecreatefromjpeg($sourcefile);
      $width = imagesx( $img );
      $height = imagesy( $img );
  
      if ($width &gt; $height) {
          $newwidth = $thumbwidth;
          $divisor = $width / $thumbwidth;
          $newheight = floor( $height / $divisor);
      } else {
          $newheight = $thumbheight;
          $divisor = $height / $thumbheight;
          $newwidth = floor( $width / $divisor );
      }
  
      // Create a new temporary image.
      $tmpimg = imagecreatetruecolor( $newwidth, $newheight );
  
      // Copy and resize old image into new image.
      imagecopyresampled( $tmpimg, $img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height );
  
      // Save thumbnail into a file.
      imagejpeg( $tmpimg, $endfile, $quality);
  
      // release the memory
      imagedestroy($tmpimg);
      imagedestroy($img);
  </code></pre>