Search code examples
phpimage-resizingmemory-limit

resize multiple images in php without exceeding memory limit


I am currently trying to get a form which will allow multiple images to be uploaded and resized on the server using PHP. Each uploaded image by the client is around 2.5mb in size.

I am currently using the move_uploaded_file() function.

There are no issues to move the files onto the server. The problem arises when I try to crop. Having not ImageMagick on my host I am using this setup (not all the code just what's relevant, this is in a loop with $width etc. changing for the different crop sizes)

$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
imagejpeg($image_p, $output_filename, 80);

As it stands this will only work for 2 images. If there is 3 or more submitted I get a 'memory exhausted' error. I have researched into this as my memory limit is 120mb. Apparently the imagecreatefromjpeg function uses a lot of memory, especially if the file has a large resolution (which mine does - hence why I need them cropped/resized).

Does anyone know of a more efficient approach to this task? I have researched on google but everyone uses the same technique I am.


Solution

  • Use imagedestroy to clear any memory associated with $image and $image_p :

    $image_p = imagecreatetruecolor($width, $height);
    $image = imagecreatefromjpeg($filename);
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
    imagejpeg($image_p, $output_filename, 80);
    imagedestroy($image);
    imagedestroy($image_p);