title: php image copy/crop/resize memory limits
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/7092404/php-rebuilding-images-memory-usage">PHP rebuilding images: memory usage</a>  </p>
  </blockquote>
  
  
  
  <p>I have a simple image upload script. A user is allowed to upload an image (gif,jpg or png) with a max file size of 10MB. The user is also allowed to apply a crop to
  the image, so I set the memory limit on the script to 256MB. I figured 256MB was more then enough memory to crop a 10MB image. I was wrong. 
  When a user uploads a large image (around 5000x5000) and barely crops it, the script always throws an out of memory error. I found <a href="http://www.dotsamazing.com/en/labs/phpmemorylimit" rel="nofollow noreferrer">this neat tool</a> to help determine the memory limit when resizing an image with php. I also came across this formula</p>
  
  <pre><code>$width * $height * $channels * 1.7
  </code></pre>
  
  <p>to determine how much memory an image will require. I am looking for someone to explain what is going on here. It is pretty clear to me that a 10MB jpeg
  is not 10MB when loaded into memory, but how can I determine how much memory it will take up? Is the formula above correct? And is there a more efficent way to crop large images
  or do I have to use massive amounts of memory?</p>
  
  <p>For anyone interested, here is the code to crop an image.</p>
  
  <pre><code>function myCropImage(&amp;$src, $x, $y, $width, $height) {
      $src_width = imagesx($src);
      $src_height = imagesy($src);
  
      $max_dst_width = 1024;
      $dst_width = $width;
  
      $dst_height = $height;
      $max_dst_height = 768;
  
      // added to restrict size of output image.
      // without this check an out of memory error is thrown.
      if($dst_width &gt; $max_dst_width || $dst_height &gt; $max_dst_height) {
          $scale = min($max_dst_width / $dst_width, $max_dst_height  / $dst_height);
          $dst_width *= $scale;
          $dst_height *= $scale;
      }
  
      if($x &lt; 0) {
          $width += $x;
          $x = 0;
      }
      if($y &lt; 0) {
          $height += $y;
          $y = 0;
      }
  
      if (($x + $width) &gt; $src_width) {
          $width = $src_width - $x;
      }
  
      if (($y + $height) &gt; $src_height) {
          $height = $src_height - $y;
      }
  
      $temp = imagecreatetruecolor($dst_width, $dst_height);
      imagesavealpha($temp, true);
      imagefill($temp, 0, 0, imagecolorallocatealpha($temp, 0, 0, 0, 127));
      imagecopyresized($temp, $src, 0, 0, $x, $y, $dst_width, $dst_height, $width, $height);
  
      return $temp;
  }
  </code></pre>