When working with the PHP GD Image functions, memory usage can become a serious issue. Where PHP developers often stumble is in not realizing that the various imagecreate*() functions create a bitmap in memory with data for each and every pixel. Therefore a source JPEG file that is only a few tens of kilobytes in size might need several megabytes of memory when used as the source of an image (e.g. imagecreatefromjpeg()).
As a rule of thumb to estimate the memory usage of a given image, figure that you’ll need 4 bytes per pixel (3 for the RGB color and 1 for the alpha channel). If you multiply that times the width and height of the image, you will then have a good working number.
Fortunately, PHP’s getimagesize() function will give you the dimensions of an image file without having to first convert it into a GD image, thus allowing you to decide if it’s too big for your application to use or not.
$imgAttrs = getimagesize('path/to/file.jpg');
$estimatedMemory = $imgAttrs[0] * $imgAttrs[1] * 4;
You can then use the result of that estimate to decide if you want to go ahead and process that image, or raise a red flag and do something else, instead.
