PHP memory_limit calculator for image resizing
This simple calculator helps you to set the memory size limit of your PHP processes. This is a very important step when you're about to build some image processing website as you'll need to allocate enough memory to process both the input and the output image.
Fatal error: Allowed memory size of 8388608 bytes exhausted (tried to allocate 41 bytes) in example.php
Looks familiar? PHP memory limit calculator to the rescue! :)
2. The calculator
Where can I set the memory limit?
You can set
- in Apache configuration (even in
- runtime using
Is there anything else I need to know?
Once you've got the memory limit and the image size, take time to
- verify the upload_max_filesize setting on the server
- validate the dimensions of the input image
I want to set memory limit on the fly!
You can! There's even a function ready to use
that sets the process memory limit dynamically (link below).
Be warned though -
the memory taken by a process will never decrease!
Using extreme large files (like 10000x10000)
your PHP process(es) can eat up the server memory.
Be wise and control memory usage.
I've pushed both buttons and the numbers changed! It sucks!
Remember, the calculator is rounding to megabytes, which leads to extra/lost pixels when you're doing a reverse calculation.
4. Background info
Guess what? Setting
memory_limit is not an exact science.
That's why we have "tweak factor", a multiplier based on
real life experience. In practice, 1.5-1.6 is okay, 1.8 is quite safe
in most cases.
There's a script on php.net to find an approximate "tweak factor" based on your own images. The script runs a single imagecreate function on each image, measures runtime memory usage and gives an average, which is the "tweak factor" multiplier - most likely you'll get a number between 1.5-1.8 too. However, you may add some
to simulate the entire resizing process.
Image processing in PHP is handled by the GD extension. Should you have the time to find out why we need the tweak factor, please let me know. Unfortunately the FAQ doesn't give too much clues:
Why is it so much pain?
Most tasks in PHP don't consume the amount of memory available by default for a process on most servers: developers simply don't get used to deal with such problems.
Who did this?
The glorious guys behind dotsamazing.com. We've got lots of experience with image and video processing, community networks, media related sites, custom applications. Hire us! ;)
Please leave your comments in our blog at http://blog.dotsamazing.com/2009/08/php-memory_limit-calculator-for-image-resizing/