【问题标题】:Memory errors resizing JPG with PHP使用 PHP 调整 JPG 大小的内存错误
【发布时间】:2021-12-09 23:56:45
【问题描述】:

我已经在我的桌面计算机上安装了 Apache 和 PHP,并运行以下 PHP 脚本来获取一个文件夹中的大图像并将它们转换为将存储在另一个文件夹中的较小的缩略图。

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

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

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

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

我添加了“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);
        }
    }
?>

【问题讨论】:

    标签: php memory resize jpeg imagecreatefromjpg


    【解决方案1】:

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

    在您的情况下,您可能必须在 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 memory limit

    【讨论】:

    • 谢谢。我会试试的。
    猜你喜欢
    • 2013-01-28
    • 2012-11-15
    • 1970-01-01
    • 1970-01-01
    • 2013-02-09
    • 1970-01-01
    • 2012-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多