PHP imagecreatefromjpeg memory limit error

Sometimes when you are dealing with relatively large images, functions such as imagecreatefromjpeg, return errors like the one below.

Allowed memory size of X bytes exhausted

The reason behind this is that the amount of memory that needs to be allocated for the image, doesn’t depend directly on the image size in terms of KB or MB. It isrelated to other properties such as dimensions in pixels, channels, bits, etc. One way to get around this issue would be to force the processed images to have some maximum dimensions, which will be in line with your memory_limit PHP setting. However if that is not an option and you need to be able to handle arbitrary image sizes, there are 2 ways to go about it:

Method 1

Just increase the amount of memory allocated to the PHP process, by increasing the memory_limit either in php.ini or per request using ini_set

Better way

A better way of doing it, instead of increasing the memory amount to an arbitrary value (which may not be high enough in certain cases, or might be too high) is to try and dynamically calculate the amount of memory that the operation will take and then set the memory_limit to that pre-calculated amount. The following snippet is originally posted by K.Tamutis on the php manual and it does the job just fine:

$imageInfo = getimagesize('PATH/TO/YOUR/IMAGE'); 
$memoryNeeded = round(($imageInfo[0] * $imageInfo[1] * $imageInfo['bits'] * $imageInfo['channels'] / 8 + Pow(2,16)) * 1.65); 
if (function_exists('memory_get_usage') && memory_get_usage() + $memoryNeeded (integer) ini_get('memory_limit') *pow(1024, 2)) {
 ini_set('memory_limit', (integer) ini_get('memory_limit') + ceil(((memory_get_usage() + $memoryNeeded) - (integer) ini_get('memory_limit') * pow(1024, 2)) / pow(1024, 2)) . 'M'); 
}