I have to render something with Imagick on PHP CLI. I have noticed that every 3-5 days the server memory gets full, so i can't even connet via ssh or ftp.
with memory_get_usage() i narrwoed the memory leak down to the imagick part of the script. the script looks something like this:
$sourceImg = 'source.png';
$destImg = 'dest.png';
$background ='#00ff00';
$im = new Imagick();
$im->pingImage($sourceImg);
$im->readImage($sourceImg);
$draw = new ImagickDraw();
for($i=1;$i<=5;$i++){
$draw->setFillColor( $background);
$draw->rectangle( 10*$i+5, 10, 10*$i+10, 20);
}
$im->drawImage( $draw );
$im->writeImage( $destImg );
$im->destroy();
unset($im,$draw);
I destroy the image reference, and unset the imagick and imagickDraw object, but the script won't release any memory. The setFillColor() method takes the most memory
Can i do something else to free the space used by imageick?
image of the memory consumption
Imagick is a PHP extension to create and modify images using the ImageMagick library. There is also a version of Imagick available for HHVM. Although the two extensions are mostly compatible in their API, and they both call the ImageMagick library, the two extensions are completely separate code-bases.
Use ImageMagick®to create, edit, compose, or convert digital images. It can read and write images in a variety of formats (over 200) including PNG, JPEG, GIF, WebP, HEIC, SVG, PDF, DPX, EXR and TIFF.
Imagick is a PHP extension which provides better image quality for media uploads, smarter image resizing (for smaller images) and PDF thumbnail support, when Ghost Script is also available.
I know this is old but I ran into the same problem and calling $im->clear()
instead of $im->destroy()
fixed the memory leak for me.
According to the documentation Imagick::destroy() has been deprecated in favor of Imagick::clear()
. So clear()
should be used.
You can use this.
Note that clear()
is preferred over destroy()
according to the docs to release memory use.
// clear temp files
$imagick_image->clear(); // in your case "$img->clear();"
You can also run a cron to delete the temp files for you, otherwise your server could crash. This is not php code, it is command line code.
# linux command
find /tmp/ -name "magick-*" -type f -delete
# cron
45 * * * * find /tmp/ -name "magick-*" -type f -delete
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