21. June 2013 2 min read

Resize, save and add watermark to photo with php and imagick

We will be using Image magick so make sure you sudo apt-get install imagemagick and check the version using imagick -v Then you need to install pecl (sudo apt-get install pecl) and use that to install imagick (sudo pecl install imagick).
Now you want to check your php configuration file (command can be found in multiple file upload tutorial) and enable Image magick using the extension. It is simple - just add extension=imagick.so in there somewhere.

We are now ready for the real program. It is not all that heavy after all:

//start timing for my fun
$before = microtime(true);

//loading watermark
$watermark=new Imagick('watermark.png');
//loading our photo - path is saved into $name variable
$im=new Imagick("$name");

//we want to get it scaled, so that it is not bigger than it should be. 
//next we will want to also make it smaller :D
//you should check filters on PHP:Imagick:reSize

//we want to move watermark a bit

//we calculate position of watermark from top-left corner
$x=$im->getImageWidth() - $watermark->getImageWidth() - $margin_right;
$y=$im->getImageHeight() - $watermark->getImageHeight() - $margin_bottom;

//blending watermark with image
$im->compositeImage($watermark, Imagick::COMPOSITE_OVER,$x , $y);

//save image back to where it came

//preform cleanup (this is wise especially if you are working with more photos)

//now we finish timing stuff
$after= microtime(true);

//and we print the result - you can also add img here
echo 'Processing lasted ' . round((($after-$before)),3) . ' s.';

Newest from this category: