0

When my PHP 7.4.33 website (running on linux) attempts to shrink/downsize an uploaded jpeg I get this error:

Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 16384 bytes)

I have carefully studied similar SO posts such as this and this.

Here is the code that crashes:

function ShrinkImage($sourcePath, $destinationPath, $maxWidth) {
    // Get the original image dimensions
    list($originalWidth, $originalHeight) = getimagesize($sourcePath);
    
    // Calculate the new height while maintaining the aspect ratio
    $newWidth = $maxWidth;
    $newHeight = ($originalHeight / $originalWidth) * $newWidth;
    
    // Create a new image resource
    $newImage = imagecreatetruecolor($newWidth, $newHeight);
    
    // Load the original image
    $originalImage = imagecreatefromjpeg($sourcePath); // Change this line based on the image type (e.g., imagecreatefrompng for PNG)
    
    // Resize the image
    imagecopyresampled($newImage, $originalImage, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);
    
    // Save the resized image
    imagejpeg($newImage, $destinationPath, 80); // Change this line based on the desired image format and quality (e.g., imagepng for PNG)
    
    // Free up memory
    imagedestroy($newImage);
    imagedestroy($originalImage);
}

That code works fine on my local IIS-PHP-Windows11 setup. But on my Bluehost linux VPS it crashes with the error shown above.

I don't believe my PHP memory settings are too low, because all the jpegs I have tried (all of which cause the same error) are under 4 Mb.

Here are my PHP.ini settings on the server:

enter image description here

From studying similar SO posts it seems that this error most often occurs because of coding errors and not ini memory limits.

Any ideas?

HerrimanCoder
  • 6,835
  • 24
  • 78
  • 158
  • _"because all the jpegs I have tried (all of which cause the same error) are under 4 Mb."_ - that is only the _file_ size, the size of the _compressed_ image data. To _manipulate_ a compressed image, it needs to be unpacked. Typical color depth is three bits, image libraries often also work with an alpha channel (even if your input format did not have one, further image manipulations might require one) - so the uncompressed image will take at least (width in pixels) times (height in pixels) times three, or maybe even times four, bytes in memory ... – CBroe Jun 09 '23 at 06:44
  • You're right, increasing my memory size to 128M solved this. If you want to submit it as an answer, I'll accept and upvote. – HerrimanCoder Jun 10 '23 at 19:05

0 Answers0