Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Imagick memory leak

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

like image 328
Slemgrim Avatar asked Apr 03 '12 12:04

Slemgrim


People also ask

What does PHP imagick do?

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.

What is the use of imagick?

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.

What is imagick module?

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.


2 Answers

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.

like image 157
aandis Avatar answered Oct 01 '22 09:10

aandis


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
like image 39
kintsukuroi Avatar answered Oct 01 '22 11:10

kintsukuroi