Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A fail-safe way to prevent GD image library from running out of memory? (PHP)

Tags:

php

memory

gd

Is there a way to prevent the PHP GD image library from running out of memory? If too large an image is uploaded, GD tends to run out of memory, terminating the script. I'd like it to throw a catchable exception or something to that extend, but alas it doesn't.

Right now I'm using a cobbled-together script that first issues an ini_set('memory_limit', '128M'), if that works I'm usually all set. Depending on the server configuration though that may not be possible, so I'm falling back on an algorithm that tries to estimate the amount of memory needed (taking resolution, color depth, channels and a fudge factor into account), then compares it to memory_get_usage() if the function exists, otherwise does a rough estimate.

The whole thing works so far, but it's far from elegant and will fail in some edge cases, I'm sure. Is there any better way to do this, i.e. have GD fail gracefully if it has to, instead of grinding everything to a halt?

like image 682
deceze Avatar asked Jul 13 '09 00:07

deceze


2 Answers

Buy more memory! :-P

Seriously though, it is impossible to handle being out of memory because any action you take would require more memory.

Your best bet is to limit the size of image being uploaded based on the current memory settings.

like image 93
Nick Presta Avatar answered Nov 14 '22 20:11

Nick Presta


After you create an image.

imagepng($image);
imagedestroy($image);

will remove the memory problem

like image 42
Kevin Baker Avatar answered Nov 14 '22 22:11

Kevin Baker