首页 > 解决方案 > PHP Image Resize 致命错误:内存不足

问题描述

我有以下 PHP 代码将我的图片调整为所需的大小:

/* POSTER - resize */
                $remote_file = $castImages[$name];
                $new_width  = 296;
                $new_height = 436;
                list($width, $height) = getimagesize($remote_file);
                $image_p = imagecreatetruecolor($new_width, $new_height);
                $image = imagecreatefromjpeg($remote_file);
                imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
                imagejpeg($image_p, '../glumci/'.$name.' BIG.jpg', 100);
                $new_width  = 74;
                $new_height = 109;
                list($width, $height) = getimagesize($remote_file);
                $image_p = imagecreatetruecolor($new_width, $new_height);
                $image = imagecreatefromjpeg($remote_file);
                imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
                imagejpeg($image_p, '../glumci/'.$name.'.jpg', 100);
                imagedestroy($image_p);
                imagedestroy($image);

我有大约 5500 张图片要调整大小,所以我将这段代码运行到 while 循环中并从 PHP 中得到这个错误:

Fatal error: Out of memory (allocated 473956352) (tried to allocate 27263000 bytes) in D:\portal_ONLINE\UwAmp\www\inc\test.php on line 54

然后我在 PHP 脚本中添加这段代码:

ini_set('memory_limit', '-1');

但是我收到相同的错误消息..那么如何修复这个错误,以便脚本重命名所有 5500 张图片而不仅仅是 50 并抛出这个错误?

标签: phpmemoryout

解决方案


在上述重播答案的成员的帮助下,我得到了最终的工作代码:

/* POSTER - resize */
            $remote_file = $castImages[$name];
            $new_width  = 296;
            $new_height = 436;
            list($width, $height) = getimagesize($remote_file);
            $image_p = imagecreatetruecolor($new_width, $new_height);
            $image = imagecreatefromjpeg($remote_file);
            imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
            imagejpeg($image_p, '../glumci/'.$name.' BIG.jpg', 100);
            $image_p = null;
            $image = null;

            $new_width  = 74;
            $new_height = 109;
            list($width, $height) = getimagesize($remote_file);
            $image_p = imagecreatetruecolor($new_width, $new_height);
            $image = imagecreatefromjpeg($remote_file);
            imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
            imagejpeg($image_p, '../glumci/'.$name.'.jpg', 100);
            imagedestroy($image_p);
            imagedestroy($image);
            $image_p = null;
            $image = null;

使用:

$image_p = null;
$image = null;

它现在可以运行大约 20 分钟,并且脚本正在运行并且不会出现错误消息。


推荐阅读