Chuck Le Butt
Chuck Le Butt

Reputation: 48758

PHP Fatal Error: Out of Memory when creating an image

I have a simple PHP script that takes an image that's been uploaded and processes it with imagecreatefromjpeg. It works great on small images, but not on larger ones. With an image of say, 5,799,936 bytes, I get the following error:

Fatal error: Out of memory (allocated 56623104) (tried to allocate 3072 bytes)

If the image is less than 1MB, I get no such error.

I've ensured that I always use imagedestroy whenever an image has been successfully processed, and I've used memory_get_usage() to see what's currently in use (186260).

Is there anyway to get to the bottom of this error and change the outcome -- or do I need to put a check in place for the size of the image, as the server will never be able to process anything of that size. (If so, how can I tell what size is OK for the server?)

Upvotes: 0

Views: 626

Answers (3)

Chuck Le Butt
Chuck Le Butt

Reputation: 48758

Thanks to the help of Your Common Sense and Pekka웃 I tried various pixel dimensions until I got a rough idea of the number that could be handled by the server. For me it was around 10,200,000 pixels in a single image.

I then used getimagesize() to get the height and width of any uploaded image, and checked to see the total number of pixels. If it was more than 10,200,000, I throw an exception before I get to imagecreatefromjpeg, letting the user know to resize and image.

Upvotes: 0

Pekka
Pekka

Reputation: 449395

The way @Common Sense outlines is the only way to try and predict how much memory a resize process is going to consume. It's never going to be 100% accurate but with the right safety margins, it'll likely be adequate.

Another option that comes to mind is to trigger a separate PHP process that attempts the resize operation (through file_get_contents or exec()). If that operation fails with a fatal error, you can catch it and show a friendly message to the user that their image is too large.

If you can get binaries installed on your server, you could also consider relying on an external tool like ImageMagick to do the resizing. A command-line tool's memory usage does not count towards your PHP memory limit.

Upvotes: 2

Your Common Sense
Your Common Sense

Reputation: 157839

It is not file size but image size require certain amount of memory. And you can get required dimensions from familiar getimagesize() function.

To calculate the dimensions limits just get the resizable file, get it's dimensions, measure consumed memory with memory_get_peak_usage() and divide it by the number ofpixels in the image. Yu will get the rough coefficient which will tell you dimensions which you allowed to

Upvotes: 3

Related Questions