Would anyone be able to give me a quick primer on how memory resources are used? I know I can up the PHP memory limit in PHP.ini as well as through lines of code such as:
ini_set("memory_limit","24M");
I have an image upload script that I'm writing that is making use of a pretty cool PHP script called simpleImage which can be found here: http://www.white-hat-web-design.co.uk/articles/php-image-resizing.php
I have a basic form that accepts JPGs and PNGs. I've set my PHP memory limit to 24m, thinking this would be high enough, but when I tried to upload a 3mb image I still received the beautiful memory allocation exhausted error. Bumping the value up to a meatier 240M and the script runs fine (locally).
My script does this:
1) Accepts the TMP Image being uploaded
2) Runs getimagesize() on the image to check that it's a valid image.
3) Moves the temporary image to the final destination directory.
4) Loads the image using simple image.
5) Resizes the image using simple image.
6) Saves the resized image using simple image script.
So I guess that all the loading/checking/resizing requires a bit more than the 24M. But I'm worried about what an acceptable memory limit allocation would be. I would like for users to comfortable be able to upload ~6MB images. Is this going to be extremely stressful on your average dedicated servers?
Here's the gist of my script.. personally I don't think it's excessively wasteful on resources??
if (!empty($_FILES)) {
// get image
ini_set("memory_limit","24M");
require_once('simpleImage.php');
require_once('db.php');
$tempFile = $_FILES['file']['tmp_name'];
$originalFile = $_FILES['file']['name'];
$extension = strtolower(end(explode(".", $originalFile)));
$targetFile = "path/to/directory/";
// validate image
$validExtensions = array('jpg', 'jpeg', 'png');
if(in_array($extension, $validExtensions)) {
$validExtension = true;
} else {
$validExtension = false;
}
if(getimagesize($tempFile) == false) {
$validImage = false;
} else {
$validImage = true;
}
if($validExtension == true && $validImage == true) {
if(move_uploaded_file($tempFile,$targetFile)) {
$image = new SimpleImage();
$image->load($targetFile);
$image->resizeToWidth(500);
$image->save($targetFile);
}
}
}
Formats such as JPG and PNG are highly compressed and hence a 3MB file which is say 6 megapixels could easily expand to 24MB in memory. Adding in the output image and PHP's own requirements could easily make the memory usage cross 30MB.
The actual memory requirement depends more on the image dimensions rather than the file size. A rough estimate would be megapixels * 3 MB for RGB images (JPEGs and opaque PNGs) or megapixels * 4 MB for RGBA images (transparent PNGs). Don't forget that the GD library itself may maintain temporary internal buffers for various purposes, so double this estimate should be a reasonable memory limit to use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With