Skip to content

Example: Own command Placing watermark

tck edited this page Jun 23, 2014 · 2 revisions

Application/Module.php

<?php
public function onBootstrap(MvcEvent $e)
{
    //...
    $e->getApplication()->getServiceManager()->get('Application\Service\ImageWatermark')->registerCommand();
}

Application/config/module.config.php

<?php
return array(
    //...
    'service_manager' => array(
        'factories' => array(
            'Application\Service\ImageWatermark' => 'Application\Service\ImageWatermarkFactory',
        ),
    ),
    //...
);

Application/src/Application/Service/ImageWatermarkFactory.php

<?php
namespace Application\Service;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class ImageWatermarkFactory implements FactoryInterface
{
    /**
     * Create Service Factory
     * 
     * @param ServiceLocatorInterface $serviceLocator
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $imagine = $serviceLocator->get('TckImageResizerImagine');

        $service = new ImageWatermark($imagine);
        return $service;
    }
}

Application/src/Application/Service/ImageWatermark.php

<?php
namespace Application\Service;

use TckImageResizer\Service\CommandRegistry;
use Imagine\Image\AbstractImagine;
use Imagine\Image\ImageInterface;
use Imagine\Image\Point;

class ImageWatermark
{
    /**
     * @var AbstractImagine
     */
    protected $imagine;
    
    /**
     * constructor
     * 
     * @param AbstractImagine
     */
    public function __construct(AbstractImagine $imagine)
    {
        $this->setImagineService($imagine);
    }
    
    /**
     * set the imagine service
     * 
     * @param AbstractImagine
     */
    public function setImagineService(AbstractImagine $imagine)
    {
        $this->imagine = $imagine;

        return $this;
    }
    
    /**
     * Get the imagine service
     * 
     * @return AbstractImagine
     */
    public function getImagineService()
    {
        return $this->imagine;
    }
    /**
     * register command
     */
    public function registerCommand()
    {
        CommandRegistry::register('watermark', array($this, 'watermark'));

        return $this;
    }

    /**
     * place watermark to image
     */
    public function watermark(ImageInterface $image)
    {
        $watermark = $this->getImagineService()->open('public/img/watermark.png');
        $iSize = $image->getSize();
        $wSize = $watermark->getSize();

        $bottomRight = new Point($iSize->getWidth() - $wSize->getWidth() - 10, $iSize->getHeight() - $wSize->getHeight() - 10);

        $image->paste($watermark, $bottomRight);
    }
}
Clone this wiki locally