|
Posted by Mattia on 01/03/06 19:06
**************************************************
Manage image without exhausted memory
**************************************************
Hi;
I have a big problem. I must create a script that upload an image an
then resize it, if width or height are more than 250px.
Now, after upload an image (in this example I suppose that it's a JPEG
image):
1) I create an image identifier representing the image obtained from
the given filename. In this case the given filename is the image
uploaded (I remember that an user can upload a very big image, but I
control that it isn't more than 1 MB).
$this->src_image = imagecreatefromjpeg($this->imageName);
2) I call a method that resized the image
$this->resizeImage();
this is the code of the method:
***************************
$this->dest_image = imagecreatetruecolor($thumb_w, $thumb_h);
imagecopyresized($this->dest_image, $this->src_image, 0, 0, 0, 0,
$thumb_w, $thumb_h, $old_x, $old_y);
**************************
In this code show above I create an image identifier representing the
new image that I want resized, and then copy and resize image from
image uploaded.
3) I create the image file resized
imagejpeg($this->dest_image, $this->resizedImageName);
But, if I upload a image file, and its size is more than 512KB, the
script crash an this is the error message:
*********************************************
Fatal error: Allowed memory size of 19922944 bytes exhausted (tried to
allocate 1000 bytes) in
/web/htdocs/www.bestbostonterrier.it/home/sNews/ImageResizeClass.php on
line 57.
*********************************************
So, I read some comment in php.net about imagecreatefromjpeg()
function, where the script crash. A user say this:
*******************************************
In addition to yaroukh at gmail dot com comment.
It seems that even a small image can eat up your default memory limit
real quick. Config value 'memory_limit' is marked PHP_INI_ALL, so you
can change it dynamically using ini_set. Therefore, we can "allocate
memory dynamically", to prevent those memory limit exceeded errors.
<?php
$imageInfo = getimagesize('PATH/TO/YOUR/IMAGE');
$memoryNeeded = round(($imageInfo[0] * $imageInfo[1] *
$imageInfo['bits'] * $imageInfo['channels'] / 8 + Pow(2, 16)) * 1.65);
if (function_exists('memory_get_usage') && memory_get_usage() +
$memoryNeeded > (integer) ini_get('memory_limit') * pow(1024, 2)) {
ini_set('memory_limit', (integer) ini_get('memory_limit') +
ceil(((memory_get_usage() + $memoryNeeded) - (integer)
ini_get('memory_limit') * pow(1024, 2)) / pow(1024, 2)) . 'M');
}
?>
***********************************************
So, before resize an image, I ensure that there is enough memory
available to executes the script.
Not often, but in some case (image size > 512KB), the crash the
script!!!
Anyone can help me?
Navigation:
[Reply to this message]
|