August 4, 2008 7:02 pm GMT

How to save the images processed with Imagick as file

by Gary Illyes


Scenario: You created with Imagick a cool thumbnail, and now you want to send it to a buffer other than the browser window. We already saw that it’s possible to process images on-the-fly, for example you have a 1024*768 wide image and you want to show its thumbnail version without having a thumbnail for the respective image. So what we do now is the exact opposite: we load the image in Imagick, process it, then save as a file. Probably this is the most encountered situation when processing images.

Let’s see the code, then I explain it step by step, as usual:

$im = new Imagick('/path/to/your/image.jpg');
$im->thumbnailImage( 100, null );
$fp =fopen('/path/to/the_new/thumbnail.jpg', 'w');
@fwrite($fp, $im);
@fclose($fp);

Now the explanation:

  1. st line: we loaded the image in Imagick, it’s now ready to be processed
  2. nd line: this time we create a thumbnail, store it in memory/cache: the X axis to be 100 pixels and preserve aspect ratio by setting the second parameter to ‘null’
  3. rd line: create a new file, you specify the path. The file shouldn’t exist, but all the directories Yes! W means we open the file for write
  4. th line: we write the Imagick object’s ($im) content in the open file
  5. th line: and finally, we close the file

That was all. We saved again the world.

As always, if you have questions regarding the post, drop a comment and will try to answer as soon as possible.


Comments

2 Comments on " How to save the images processed with Imagick as file "

  1. Dogo on Tue, 15th Sep 2009 5:58 am  

    $im = new Imagick($inbox_folder.DS.$sourcefile);
    $im->thumbnailImage( 100, 0);
    $im->writeImage($thumbnail_folder.DS.$destinationfile);

    Works for any filetype, even tiff to jpg.

  2. Dogo on Tue, 15th Sep 2009 5:58 am  

    Sorry, the “DS” comes from CakePhp.

Tell us what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!

If you want to use your OpenID, fill out the field labeled "Website" with the OpenID URL. The other fields may remain empty.
Note that comments are pre-moderated.

Subscribe without commenting