Question: I want to put some restrictions to the images uploaded by the users, so the script that process them never runs out of memory.

The images that take more memory, are the ones with higher resolution. They don't need to have a big size in bytes. For example, a 46kb image, with 4000x2500 resolution, and some transparencies (PNG), took around 90mb to resize it.

Is there a way to precalculate the memory needed accurately?

Any ideas?

Answer: 
Generally, the rule of thumb is, width x height x 4 (rgba) for both the source and destination images, and don't forget about the amount of memory the script itself has already consumed.
Using the GD library once the file has been uploaded you can use [getimagesize()](http://www.php.net/manual/en/function.getimagesize.php). You can then check the height and width to determine if you want to process it or return an error, it also returns the number of bits used per color if you want to take that into account as well.

So your validation can be on file size and dimensions.