0

我在我的台式机上安装了 Apache 和 PHP,并运行以下 PHP 脚本将大图像放在一个文件夹中,并将它们转换为较小的缩略图,然后存储在不同的文件夹中。

一个目录中的“1000.jpg”在另一个目录中变成了 400 像素宽的“1000sm.jpg”。

如果我只有 20 张图像要转换,它会运行并制作缩略图。但如果我有太多图像,脚本会提前停止并报告内存问题。

致命错误:第22行的D:\Documents\myserver.com\admin\makethumbnails.php中允许的内存大小为 134217728 字节已用尽(尝试分配 29440 字节)

内存错误似乎不会根据文件大小发生,因为当它停止时,它已经处理了更大的图像。

我添加了“set_time_limit(300);” 因为起初它在 30 秒后停止,这还不够。

我可以在这里做一些不同的事情来避免内存问题吗?

<?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);
        }
    }
?>
4

1 回答 1

0

您不必更新超时但内存限制。

在您的情况下,您可能必须在 while avec imagejpeg 中添加 imagedestroy 以清除内存,然后再执行一次。

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 内存限制

于 2021-10-25T14:42:48.783 回答