Проблема с памятью библиотеки GD в скрипте PHP

На моем сайте я разрешаю пользователям загружать 6 изображений размером до 5 МБ. Они должны быть в формате GIF, JPG / JPEG. Большинство изображений, которые пользователи загружают, имеют размер около 2 МБ (1006188 байт) и высоту:1536 пикселей по ширине:2048 пикселей, что довольно много (особенно при попытке изменить размер).

Затем у меня есть две директории (large_img и small_img) на сервере. В large_img я перемещаю туда загруженный файл. Затем я изменил размер изображения из этого каталога large_img с помощью библиотеки GD до размера миниатюры (высота 100 на 100 ширины) и переместил его в small_img.

Я иногда получаю сообщение об ошибке

PHP Fatal error:  Out of memory (allocated 80740352) (tried to allocate 14592 bytes)

Максимально допустимая память на моем сервере Apache составляет 64 МБ. Таким образом, существует некоторая проблема с моим кодом, то есть взятие нескольких пар кусков этого 64 МБ и не выпуск его по какой-то причине.

Вот мой код, чтобы взять изображение и изменить его размер. Я предоставил его для первого изображения из 6 и не включил здесь проверку ошибок, чтобы многое скопировать и вставить:

if(move_uploaded_file($_FILES['uploadedfile_0']['tmp_name'], $move_file_to_directoryname_large))
{
        $n_width=100;$n_height=100; /*specify height/width of thumbnail image to be*/

        if($_FILES["uploadedfile_0"]["type"]=="image/gif")
        {
                    $im=imagecreatefromgif($move_file_to_directoryname_large);
                    if(!$im)
                    {
                            /*error could occur here if image was say named .gif but was another type like .jpg casing file type error*/
                            $image_resize_error++; 
                            $array_error_msg_resize[$image_resize_error]="<p class='form_error_messages'>&#8226; An unfixable error occurred with your image ('<span class='standard_span'> " .$_FILES['uploadedfile_0']['name']." </span>').</p>";
                    }
                    else
                    {
                            $width=imagesx($im); $height=imagesy($im);
                            $newsmallerimage=imagecreatetruecolor($n_width,$n_height);                 
                            imagecopyresized($newsmallerimage,$im,0,0,0,0,$n_width,$n_height,$width,$height);
                            $move_file_to_directoryname_small=$target_path_small.$newfilename;
                            if(function_exists("imagegif"))
                            {
                                    imagegif($newsmallerimage,$move_file_to_directoryname_small); 
                                    $images_db_small[0]=substr_replace($move_file_to_directoryname_small, "", 0, 24);
                            }
                            /*frees image from memory */
                            imagedestroy($newsmallerimage);
                    }
            }
            if($_FILES["uploadedfile_0"]["type"]=="image/jpeg")
            {
                            $im=imagecreatefromjpeg($move_file_to_directoryname_large); /*create from image stored in directory specified when moving from /tmp*/
                            if(!$im)
                            {
                                    /*error could occur here if image was say named .gif but was another type like .jpg casing file type error*/
                                    $image_resize_error++; 
                                    $array_error_msg_resize[$image_resize_error]="<p class='form_error_messages'>&#8226; An unfixable error occurred with your image ('<span class='standard_span'> " .$_FILES['uploadedfile_0']['name']." </span>').</p>";
                            }
                            else
                            {
                                    $width=imagesx($im);/*Original picture width is stored*/$height=imagesy($im);/*Original picture height is stored*/
                                    $newsmallerimage=imagecreatetruecolor($n_width,$n_height);                 
                                    $imagecopyresized($newsmallerimage,$im,0,0,0,0,$n_width,$n_height,$width,$height);
                                    $move_file_to_directoryname_small=$target_path_small.$newfilename;
                                    if(function_exists("imagejpeg"))
                                    {
                                            imagejpeg($newsmallerimage,$move_file_to_directoryname_small); 
                                            $images_db_small[0]=substr_replace($move_file_to_directoryname_small, "", 0, 24);
                                    }
                                    /*frees image from memory */
                                    imagedestroy($newsmallerimage);
                            }
                }
}

Вот мои настройки php.ini:

upload_max_filesize = 30M
post_max_size = 30M
max_execution_time = 120 
max_file_uploads = 6
memory_limit=128M 

Что-то в сценарии пожирает память. Произошла ошибка, упомянутая выше, возникает в этой части кода $im=imagecreatefromjpeg($move_file_to_directoryname_large);если это jpeg фото или imagecreatefromgif() если его формат gif фото

Я освобождаю память, уничтожая образ $imagedestroy($newsmallerimage);

Обратите внимание на тот же код, если оператор () повторяется для других 5 изображений с именем ['uploadedfile_1'] ...2 и т. Д

Любые предложения, возможно, считывают файлы в память, используя file_get_contents или библиотеку GD. Я знаю, что GD хранит в памяти изображение без сжатия, что может быть проблемой. Спасибо, парни

2 ответа

Решение

Вы не освобождаете $imможет быть в этом проблема.

Уничтожьте изображение, которое вы создаете с помощью imagecreatefromjpeg()

в if() условие добавить строку,

imagedestroy($im);

как это,

if(!$im)
{
    $image_resize_error++; 
    $array_error_msg_resize[$image_resize_error]="<p class='form_error_messages'>&#8226; An unfixable error occurred with your image ('<span class='standard_span'> " .$_FILES['uploadedfile_0']['name']." </span>').</p>";
    imagedestroy($im);
}
Другие вопросы по тегам