How can I prevent GD from running out of memory?

I'm not sure if memory is the culprit here. I am trying to instantiate a GD image from in-memory data (it previously came from a database). I try the call like this:

my $image = GD::Image->new($image_data);

      

$image

returns as undef

. The POD for GD says the constructor will return undef

for out of memory cases, so I suspect memory.

The image data is in PNG format. The same thing happens if I call newFromPngData.

This works for very small images like up to 30K. However, slightly larger images like ~ 70K will cause a problem. I would not have thought that a 70K image should cause these problems even after it is deflated.

This script runs under CGI through Apache 2.0, on OS 10.4, if it matters at all.

Are there any default limits set by Apache by default? Can they be increased?

Thank you for understanding!

EDIT: For clarification, a GD :: Image object is never created, so clearing $image_data

memory is not really an option.

+1


source to share


2 answers


The GD library consumes many bytes per image size. This ratio is over 10: 1!

When a user uploads an image to our system, we start by checking the size of the file before uploading it to the GD image. If it exceeds the threshold (1 megabyte), we do not use it, but report the error to the user.

If we really do care so that we can dump it to disk, use the convert tool on the command line to rescale it to a reasonable size, then load the output into the GD library and delete the temp file.



convert -define jpeg:size=800x800 tmpfile.jpg -thumbnail '800x800' -

      

Will scale the image to fit the 800 x 800 square. This is the longest edge now 800px and should load safely. The above command will send the .jpg compression to STDOUT. The size = parameter should convert so you don't have to worry about keeping a huge image in memory, but enough to scale up to 800x800.

+1


source


I faced the same problem several times.

One of my solutions was to simply increase the amount of memory available for my scripts. Another is to clear the buffer:

Original Script:

$src_img = imagecreatefromstring($userfile2);
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_width,$thumb_height,$origw,$origh);

      



Edited Script:

$src_img = imagecreatefromstring($userfile2);
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_width,$thumb_height,$origw,$origh);
imagedestroy($src_img);

      

By clearing the memory of the first src_image, it is freed up enough to handle more processing.

0


source







All Articles