Resource handling
Automatic handling
WideImage takes care of image resources for you; you don't have to destroy the images explicitly, they're automatically destroyed when an image object is no longer used. You can change that at runtime by
releasing the handle of an image.
In most cases, this is fine.
Memory consumption issue
Sometimes PHP's garbage collector doesn't destroy objects immediately after the object is dereferenced. This could mean the memory allocated to an image doesn't get freed soon enough. If you're operating on a lot of images at once, you could hit PHP's memory limit. This behavior was noticed with code that operated on images in a loop.
The solution
You can explicitly destroy the resource after you don't need the image object anymore, like this:
$img = wiImage::
load('...');
...
do some stuff
$img->
destroy();
// or
unset($img);
// which also calls destroy() through the destructor
Important: you shouldn't use the image object after you call destroy() method on it, because the image resource doesn't exist anymore. You'll get a lot of errors. Actually,
unsetting∞ is the preferred method.
Note: unless it's really important, I advise you not to use this method of freeing resources. Let the garbage collector do its magic. ;)
Lost handle
Every magic has its drawbacks. Because of the automatic handling the image resource is sometimes released
too early.
Example
// load an image
$img = wiImage::load('...');
// copy the image and retrieve the copy's resource handle
$handle = $img->copy()->getHandle();
// now let's output the copy with php's native function and our handle
imagepng($handle);
// Invalid image resource!
Explanation
The copy() method creates and returns an image object which is very short-lived in the eyes of PHP. It actually only lives to get returned from $img->copy(), then it's not referred to anymore and it gets destroyed by the garbage collector, which results in the handle being destroyed as well.
The solution
You can retrieve the copy to a new variable, so that the object will seem "in use" and won't get immediately destroyed.
$copied = $img->copy();
$handle = $copied->getHandle();
imagepng($handle);
Well, to be precise, in this exact case a much better solution would be to just use the library to output the image:
echo $img->
copy()->
asString('png');
There are no comments on this page. [Add comment]