Resource 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 via releaseHandle() method.

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:

  1. $img = WideImage::load('…');
  2. do some stuff
  3. $img->destroy();
  4. // or
  5. unset($img);
  6. // 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.

Lost handle

Every magic has its drawbacks. Because of the automatic handling the image resource is sometimes released too early.

Example:

  1. // load an image
  2. $img = WideImage::load('…');
  3.  
  4. // copy the image and retrieve the copy's resource handle
  5. $handle = $img->copy()->getHandle();
  6.  
  7. // now let's output the copy with php's native function and our handle
  8. imagepng($handle);
  9.  
  10. // 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.

  1. $copied = $img->copy();
  2. $handle = $copied->getHandle();
  3. 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:

  1. echo $img->copy()->asString('png');
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Reddit
  • Tumblr
  • Twitter