<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>

[{'answer_id': 12732, 'author': 'phenry', 'author_id': 1482, 'author_profile': 'https://Stackoverflow.com/users/1482', 'pm_score': 4, 'selected': False, 'text': '<p><a href="http://phpthumb.sourceforge.net/" rel="noreferrer">phpThumb</a> uses ImageMagick whenever possible for speed (falling back to GD if necessary) and seems to cache pretty well to reduce the load on the server. It\'s pretty lightweight to try out (to resize an image, just call phpThumb.php with a GET query that includes the graphic filename and output dimensions), so you might give it a shot to see if it meets your needs.</p>\n'}, {'answer_id': 12805, 'author': 'Kevin', 'author_id': 40, 'author_profile': 'https://Stackoverflow.com/users/40', 'pm_score': 5, 'selected': False, 'text': '<p>Here\'s a snippet from the php.net docs that I\'ve used in a project and works fine:</p>\n\n<pre><code>&lt;?\nfunction fastimagecopyresampled (&amp;$dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h, $quality = 3) {\n    // Plug-and-Play fastimagecopyresampled function replaces much slower imagecopyresampled.\n    // Just include this function and change all "imagecopyresampled" references to "fastimagecopyresampled".\n    // Typically from 30 to 60 times faster when reducing high resolution images down to thumbnail size using the default quality setting.\n    // Author: Tim Eckel - Date: 09/07/07 - Version: 1.1 - Project: FreeRingers.net - Freely distributable - These comments must remain.\n    //\n    // Optional "quality" parameter (defaults is 3). Fractional values are allowed, for example 1.5. Must be greater than zero.\n    // Between 0 and 1 = Fast, but mosaic results, closer to 0 increases the mosaic effect.\n    // 1 = Up to 350 times faster. Poor results, looks very similar to imagecopyresized.\n    // 2 = Up to 95 times faster.  Images appear a little sharp, some prefer this over a quality of 3.\n    // 3 = Up to 60 times faster.  Will give high quality smooth results very close to imagecopyresampled, just faster.\n    // 4 = Up to 25 times faster.  Almost identical to imagecopyresampled for most images.\n    // 5 = No speedup. Just uses imagecopyresampled, no advantage over imagecopyresampled.\n\n    if (empty($src_image) || empty($dst_image) || $quality &lt;= 0) { return false; }\n    if ($quality &lt; 5 &amp;&amp; (($dst_w * $quality) &lt; $src_w || ($dst_h * $quality) &lt; $src_h)) {\n        $temp = imagecreatetruecolor ($dst_w * $quality + 1, $dst_h * $quality + 1);\n        imagecopyresized ($temp, $src_image, 0, 0, $src_x, $src_y, $dst_w * $quality + 1, $dst_h * $quality + 1, $src_w, $src_h);\n        imagecopyresampled ($dst_image, $temp, $dst_x, $dst_y, 0, 0, $dst_w, $dst_h, $dst_w * $quality, $dst_h * $quality);\n        imagedestroy ($temp);\n    } else imagecopyresampled ($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);\n    return true;\n}\n?&gt;\n</code></pre>\n\n<p><a href="http://us.php.net/manual/en/function.imagecopyresampled.php#77679" rel="nofollow noreferrer">http://us.php.net/manual/en/function.imagecopyresampled.php#77679</a></p>\n'}, {'answer_id': 12822, 'author': 'Grzegorz Gierlik', 'author_id': 1483, 'author_profile': 'https://Stackoverflow.com/users/1483', 'pm_score': 7, 'selected': True, 'text': '<p>People say that ImageMagick is much faster. At best just compare both libraries and measure that.</p>\n\n<ol>\n<li>Prepare 1000 typical images.</li>\n<li>Write two scripts -- one for GD, one\nfor ImageMagick.</li>\n<li>Run both of them a few times.</li>\n<li>Compare results (total execution\ntime, CPU and I/O usage, result\nimage quality).</li>\n</ol>\n\n<p>Something which the best everyone else, could not be the best for you.</p>\n\n<p>Also, in my opinion, ImageMagick has much better API interface.</p>\n'}, {'answer_id': 716766, 'author': 'Salman A', 'author_id': 87015, 'author_profile': 'https://Stackoverflow.com/users/87015', 'pm_score': 2, 'selected': False, 'text': '<p>I suggest that you work something along these lines:</p>\n\n<ol>\n<li>Perform a getimagesize( ) on the uploaded file to check image type and size</li>\n<li>Save any uploaded JPEG image smaller than 700x700px in to the destination folder "as-is"</li>\n<li>Use GD library for medium size images (see this article for code sample: <a href="http://salman-w.blogspot.com/2008/10/resize-images-using-phpgd-library.html" rel="nofollow noreferrer">Resize Images Using PHP and GD Library</a>)</li>\n<li>Use ImageMagick for large images. You can use ImageMagick in background if you prefer.</li>\n</ol>\n\n<p>To use ImageMagick in background, move the uploaded files to a temporary folder and schedule a CRON job that "convert"s all files to jpeg and resizes them accordingly. See command syntax at: <a href="http://www.imagemagick.org/script/command-line-processing.php" rel="nofollow noreferrer">imagemagick-command line processing</a></p>\n\n<p>You can prompt the user that file is uploaded and scheduled to be processed. The CRON job could be scheduled to run daily at a specific interval. The source image could be deleted after processing to assure that an image is not processed twice.</p>\n'}, {'answer_id': 957421, 'author': 'Adnan', 'author_id': 88907, 'author_profile': 'https://Stackoverflow.com/users/88907', 'pm_score': 2, 'selected': False, 'text': '<p>For larger images use <a href="http://phpthumb.sourceforge.net/" rel="nofollow noreferrer">phpThumb()</a>. Here is how to use it: <a href="http://abcoder.com/php/problem-with-resizing-corrupted-images-using-php-image-functions/" rel="nofollow noreferrer">http://abcoder.com/php/problem-with-resizing-corrupted-images-using-php-image-functions/</a>. It also works for large corrupted images.</p>\n'}, {'answer_id': 4613341, 'author': 'Steve-o', 'author_id': 175849, 'author_profile': 'https://Stackoverflow.com/users/175849', 'pm_score': 3, 'selected': False, 'text': "<p>For larger images use libjpeg to resize on image load in ImageMagick and thereby significantly reducing memory usage and improving performance, it is not possible with GD.</p>\n\n<pre><code>$im = new Imagick();\ntry {\n  $im-&gt;pingImage($file_name);\n} catch (ImagickException $e) {\n  throw new Exception(_('Invalid or corrupted image file, please try uploading another image.'));\n}\n\n$width  = $im-&gt;getImageWidth();\n$height = $im-&gt;getImageHeight();\nif ($width &gt; $config['width_threshold'] || $height &gt; $config['height_threshold'])\n{\n  try {\n/* send thumbnail parameters to Imagick so that libjpeg can resize images\n * as they are loaded instead of consuming additional resources to pass back\n * to PHP.\n */\n    $fitbyWidth = ($config['width_threshold'] / $width) &gt; ($config['height_threshold'] / $height);\n    $aspectRatio = $height / $width;\n    if ($fitbyWidth) {\n      $im-&gt;setSize($config['width_threshold'], abs($width * $aspectRatio));\n    } else {\n      $im-&gt;setSize(abs($height / $aspectRatio), $config['height_threshold']);\n    }\n    $im-&gt;readImage($file_name);\n\n/* Imagick::thumbnailImage(fit = true) has a bug that it does fit both dimensions\n */\n//  $im-&gt;thumbnailImage($config['width_threshold'], $config['height_threshold'], true);\n\n// workaround:\n    if ($fitbyWidth) {\n      $im-&gt;thumbnailImage($config['width_threshold'], 0, false);\n    } else {\n      $im-&gt;thumbnailImage(0, $config['height_threshold'], false);\n    }\n\n    $im-&gt;setImageFileName($thumbnail_name);\n    $im-&gt;writeImage();\n  }\n  catch (ImagickException $e)\n  {\n    header('HTTP/1.1 500 Internal Server Error');\n    throw new Exception(_('An error occured reszing the image.'));\n  }\n}\n\n/* cleanup Imagick\n */\n$im-&gt;destroy();\n</code></pre>\n"}, {'answer_id': 5004150, 'author': 'alessioalex', 'author_id': 617839, 'author_profile': 'https://Stackoverflow.com/users/617839', 'pm_score': 2, 'selected': False, 'text': '<p>I\'ve heard big things about the Imagick library, unfortunately I couldn\'t install it at my work computer and neither at home (and trust me, I spent hours and hours on all kinds of forums).</p>\n\n<p>Afterwords, I\'ve decided to try this PHP class:</p>\n\n<p><a href="http://www.verot.net/php_class_upload.htm" rel="nofollow">http://www.verot.net/php_class_upload.htm</a></p>\n\n<p>It\'s pretty cool and I can resize all kinds of images (I can convert them to JPG also).</p>\n'}, {'answer_id': 8321603, 'author': 'Alasdair', 'author_id': 1018582, 'author_profile': 'https://Stackoverflow.com/users/1018582', 'pm_score': 2, 'selected': False, 'text': "<p>ImageMagick is multithreaded, so it appears to be faster, but actually uses a lot more resources than GD. If you ran several PHP scripts in parallel all using GD then they'd beat ImageMagick in speed for simple operations. ExactImage is less powerful than ImageMagick but a lot faster, though not available through PHP, you'll have to install it on the server and run it through <code>exec</code>.</p>\n"}, {'answer_id': 19675318, 'author': 'Eathen Nutt', 'author_id': 1970939, 'author_profile': 'https://Stackoverflow.com/users/1970939', 'pm_score': 3, 'selected': False, 'text': '<p>From you quesion, it seems you are kinda new to GD, I will share some experence of mine, \nmaybe this is a bit off topic, but I think it will be helpful to someone new to GD like you:</p>\n\n<p><strong>Step 1, validate file.</strong> Use the following function to check if the <code>$_FILES[\'image\'][\'tmp_name\']</code> file is valid file:</p>\n\n<pre><code>   function getContentsFromImage($image) {\n      if (@is_file($image) == true) {\n         return file_get_contents($image);\n      } else {\n         throw new \\Exception(\'Invalid image\');\n      }\n   }\n   $contents = getContentsFromImage($_FILES[\'image\'][\'tmp_name\']);\n</code></pre>\n\n<p><strong>Step 2, get file format</strong> Try the following function with finfo extension to check file format of the file(contents). You would say why don\'t you just use <code>$_FILES["image"]["type"]</code> to check file format? Because it <strong>ONLY</strong> check file extension not file contents, if someone rename a file originally called <em>world.png</em> to <em>world.jpg</em>, <code>$_FILES["image"]["type"]</code> will return jpeg not png, so <code>$_FILES["image"]["type"]</code> may return wrong result.</p>\n\n<pre><code>   function getFormatFromContents($contents) {\n      $finfo = new \\finfo();\n      $mimetype = $finfo-&gt;buffer($contents, FILEINFO_MIME_TYPE);\n      switch ($mimetype) {\n         case \'image/jpeg\':\n            return \'jpeg\';\n            break;\n         case \'image/png\':\n            return \'png\';\n            break;\n         case \'image/gif\':\n            return \'gif\';\n            break;\n         default:\n            throw new \\Exception(\'Unknown or unsupported image format\');\n      }\n   }\n   $format = getFormatFromContents($contents);\n</code></pre>\n\n<p><strong>Step.3, Get GD resource</strong> Get GD resource from contents we have before:</p>\n\n<pre><code>   function getGDResourceFromContents($contents) {\n      $resource = @imagecreatefromstring($contents);\n      if ($resource == false) {\n         throw new \\Exception(\'Cannot process image\');\n      }\n      return $resource;\n   }\n   $resource = getGDResourceFromContents($contents);\n</code></pre>\n\n<p><strong>Step 4, get image dimension</strong> Now you can get image dimension with the following simple code:</p>\n\n<pre><code>  $width = imagesx($resource);\n  $height = imagesy($resource);\n</code></pre>\n\n<p><strong>Now,</strong> Let\'s see what variable we got from the original image then:</p>\n\n<pre><code>       $contents, $format, $resource, $width, $height\n       OK, lets move on\n</code></pre>\n\n<p><strong>Step 5, calculate resized image arguments</strong> This step is related to your question, the purpose of the following function is to get resize arguments for GD function <code>imagecopyresampled()</code>, the code is kinda long, but it works great, it even has three options: stretch, shrink, and fill.</p>\n\n<p><strong><em>stretch</em></strong>: output image\'s dimension is the same as the new dimension you set. Won\'t keep height/width ratio.</p>\n\n<p><strong><em>shrink</em></strong>: output image\'s dimension won\'t exceed the new dimension you give, and keep image height/width ratio.</p>\n\n<p><strong><em>fill</em></strong>: output image\'s dimension will be the same as new dimension you give, it will <strong><em>crop &amp; resize</em></strong> image if needed, and keep image height/width ratio. <strong>This option is what you need in your question.</strong></p>\n\n<pre><code>   function getResizeArgs($width, $height, $newwidth, $newheight, $option) {\n      if ($option === \'stretch\') {\n         if ($width === $newwidth &amp;&amp; $height === $newheight) {\n            return false;\n         }\n         $dst_w = $newwidth;\n         $dst_h = $newheight;\n         $src_w = $width;\n         $src_h = $height;\n         $src_x = 0;\n         $src_y = 0;\n      } else if ($option === \'shrink\') {\n         if ($width &lt;= $newwidth &amp;&amp; $height &lt;= $newheight) {\n            return false;\n         } else if ($width / $height &gt;= $newwidth / $newheight) {\n            $dst_w = $newwidth;\n            $dst_h = (int) round(($newwidth * $height) / $width);\n         } else {\n            $dst_w = (int) round(($newheight * $width) / $height);\n            $dst_h = $newheight;\n         }\n         $src_x = 0;\n         $src_y = 0;\n         $src_w = $width;\n         $src_h = $height;\n      } else if ($option === \'fill\') {\n         if ($width === $newwidth &amp;&amp; $height === $newheight) {\n            return false;\n         }\n         if ($width / $height &gt;= $newwidth / $newheight) {\n            $src_w = (int) round(($newwidth * $height) / $newheight);\n            $src_h = $height;\n            $src_x = (int) round(($width - $src_w) / 2);\n            $src_y = 0;\n         } else {\n            $src_w = $width;\n            $src_h = (int) round(($width * $newheight) / $newwidth);\n            $src_x = 0;\n            $src_y = (int) round(($height - $src_h) / 2);\n         }\n         $dst_w = $newwidth;\n         $dst_h = $newheight;\n      }\n      if ($src_w &lt; 1 || $src_h &lt; 1) {\n         throw new \\Exception(\'Image width or height is too small\');\n      }\n      return array(\n          \'dst_x\' =&gt; 0,\n          \'dst_y\' =&gt; 0,\n          \'src_x\' =&gt; $src_x,\n          \'src_y\' =&gt; $src_y,\n          \'dst_w\' =&gt; $dst_w,\n          \'dst_h\' =&gt; $dst_h,\n          \'src_w\' =&gt; $src_w,\n          \'src_h\' =&gt; $src_h\n      );\n   }\n   $args = getResizeArgs($width, $height, 150, 170, \'fill\');\n</code></pre>\n\n<p><strong>Step 6, resize image</strong> Use <code>$args</code>, <code>$width</code>, <code>$height</code>, <code>$format</code> and $resource we got from above into the following function and get the new resource of the resized image:</p>\n\n<pre><code>   function runResize($width, $height, $format, $resource, $args) {\n      if ($args === false) {\n         return; //if $args equal to false, this means no resize occurs;\n      }\n      $newimage = imagecreatetruecolor($args[\'dst_w\'], $args[\'dst_h\']);\n      if ($format === \'png\') {\n         imagealphablending($newimage, false);\n         imagesavealpha($newimage, true);\n         $transparentindex = imagecolorallocatealpha($newimage, 255, 255, 255, 127);\n         imagefill($newimage, 0, 0, $transparentindex);\n      } else if ($format === \'gif\') {\n         $transparentindex = imagecolorallocatealpha($newimage, 255, 255, 255, 127);\n         imagefill($newimage, 0, 0, $transparentindex);\n         imagecolortransparent($newimage, $transparentindex);\n      }\n      imagecopyresampled($newimage, $resource, $args[\'dst_x\'], $args[\'dst_y\'], $args[\'src_x\'], $args[\'src_y\'], $args[\'dst_w\'], $args[\'dst_h\'], $args[\'src_w\'], $args[\'src_h\']);\n      imagedestroy($resource);\n      return $newimage;\n   }\n   $newresource = runResize($width, $height, $format, $resource, $args);\n</code></pre>\n\n<p><strong>Step 7, get new contents</strong>, Use the following function to get contents from the new GD resource:</p>\n\n<pre><code>   function getContentsFromGDResource($resource, $format) {\n      ob_start();\n      switch ($format) {\n         case \'gif\':\n            imagegif($resource);\n            break;\n         case \'jpeg\':\n            imagejpeg($resource, NULL, 100);\n            break;\n         case \'png\':\n            imagepng($resource, NULL, 9);\n      }\n      $contents = ob_get_contents();\n      ob_end_clean();\n      return $contents;\n   }\n   $newcontents = getContentsFromGDResource($newresource, $format);\n</code></pre>\n\n<p><strong>Step 8 get extension</strong>, Use the following function to get extension of from image format(note, image format is not equal to image extension):</p>\n\n<pre><code>   function getExtensionFromFormat($format) {\n      switch ($format) {\n         case \'gif\':\n            return \'gif\';\n            break;\n         case \'jpeg\':\n            return \'jpg\';\n            break;\n         case \'png\':\n            return \'png\';\n      }\n   }\n   $extension = getExtensionFromFormat($format);\n</code></pre>\n\n<p><strong>Step 9 save image</strong> If we have a user named mike, you can do the following, it will save to the same folder as this php script:</p>\n\n<pre><code>$user_name = \'mike\';\n$filename = $user_name . \'.\' . $extension;\nfile_put_contents($filename, $newcontents);\n</code></pre>\n\n<p><strong>Step 10 destroy resource</strong> Don\'t forget destroy GD resource!</p>\n\n<pre><code>imagedestroy($newresource);\n</code></pre>\n\n<p>or you can write all your code into a class, and simply use the following:</p>\n\n<pre><code>   public function __destruct() {\n      @imagedestroy($this-&gt;resource);\n   }\n</code></pre>\n\n<p><strong>TIPS</strong></p>\n\n<p><strong>I recommend not to convert file format that user upload, you will meet many problems.</strong></p>\n'}]
['https://Stackoverflow.com/questions/12661', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1477/']