Memory errors resizing JPG with PHP

57 Views Asked by At

I've got Apache and PHP installed on my desktop machine and run the following PHP script to take the large images in one folder and turn them into smaller thumbnails that will be stored in a different folder.

"1000.jpg" in one directory becomes the 400 pixel-wide "1000sm.jpg" in a different directory.

If I've only got 20 images to convert, it'll run and make thumbnails. But if I have too many images the script stops early and reports a memory problem.

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 29440 bytes) in D:\Documents\myserver.com\admin\makethumbnails.php on line 22

The memory error doesn't appear to happen based on file size because by the time it stops, it's already processed larger images.

I added "set_time_limit(300);" because at first it was stopping after 30 seconds, which isn't enough.

Can I do something different here to avoid the memory problems?

<?php
  ini_set('display_errors', 1);
  ini_set('display_startup_errors', 1);
  error_reporting(E_ALL);

  set_time_limit(300);

  $SourcePath = "../img/";
  $TargetPath = "../imgsm/";
  $TargetWidth = 400;

  $dh = opendir($SourcePath);
  while (($FileName = readdir($dh)) !== false)
    {
      if (substr_count($FileName, 'jpg') > 0 )
        {
          $SourcePathAndFileName = $SourcePath . $FileName;
          $TargetPathAndFileName = $TargetPath . str_replace(".jpg", "sm.jpg", $FileName);
          list($SourceWidth, $SourceHeight) = getimagesize($SourcePathAndFileName);
          $TargetHeight = floor($SourceHeight * $TargetWidth / $SourceWidth);
          $thumb = imagecreatetruecolor($TargetWidth, $TargetHeight);
          $source = imagecreatefromjpeg($SourcePathAndFileName);
          imagecopyresized($thumb, $source, 0, 0, 0, 0, $TargetWidth, $TargetHeight, $SourceWidth, $SourceHeight);
          imagejpeg($thumb, $TargetPathAndFileName);
        }
    }
?>
1

There are 1 best solutions below

1
On

You dont have to update the timeout but the memory limit.

In your case, may be you have to add imagedestroy inside the while avec imagejpeg for clear memory before do one more.

if (substr_count($FileName, 'jpg') > 0 )
    {
      $SourcePathAndFileName = $SourcePath . $FileName;
      $TargetPathAndFileName = $TargetPath . str_replace(".jpg", "sm.jpg", $FileName);
      list($SourceWidth, $SourceHeight) = getimagesize($SourcePathAndFileName);
      $TargetHeight = floor($SourceHeight * $TargetWidth / $SourceWidth);
      $thumb = imagecreatetruecolor($TargetWidth, $TargetHeight);
      $source = imagecreatefromjpeg($SourcePathAndFileName);
      imagecopyresized($thumb, $source, 0, 0, 0, 0, $TargetWidth, $TargetHeight, $SourceWidth, $SourceHeight);
      imagejpeg($thumb, $TargetPathAndFileName);
      imagedestroy($thumb);
      imagedestroy($source);

    }

https://www.php.net/manual/en/function.imagedestroy.php

PHP ini_set memory limit