Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

image resize zf2

I need to implement image resize functionality (preferably with gd2 library extension) in zend framework 2.

I could not find any component/helper for the same. Any references?

If i want to create one, where should I add it. In older Zend framework, there was a concept of Action Helper, what about Zend framework 2 ?

Please suggest the best solution here.

like image 715
Prashant Avatar asked Feb 12 '13 12:02

Prashant


2 Answers

I currently use Imagine together with Zend Framework 2 to handle this.

  1. Install Imagine: php composer.phar require imagine/Imagine:0.3.*
  2. Create a service factory for the Imagine service (in YourModule::getServiceConfig):

    return array(
        'invokables' => array(
            // defining it as invokable here, any factory will do too
            'my_image_service' => 'Imagine\Gd\Imagine',
        ),
    );
    
  3. Use it in your logic (hereby a small example with a controller):

    public function imageAction()
    {
        $file    = $this->params('file'); // @todo: apply STRICT validation!
        $width   = $this->params('width', 30); // @todo: apply validation!
        $height  = $this->params('height', 30); // @todo: apply validation!
        $imagine = $this->getServiceLocator()->get('my_image_service');
        $image   = $imagine->open($file);
    
        $transformation = new \Imagine\Filter\Transformation();
    
        $transformation->thumbnail(new \Imagine\Image\Box($width, $height));
        $transformation->apply($image);
    
        $response = $this->getResponse();
        $response->setContent($image->get('png'));
        $response
            ->getHeaders()
            ->addHeaderLine('Content-Transfer-Encoding', 'binary')
            ->addHeaderLine('Content-Type', 'image/png')
            ->addHeaderLine('Content-Length', mb_strlen($imageContent));
    
        return $response;
    }
    

This is obviously the "quick and dirty" way, since you should do following (optional but good practice for re-usability):

  1. probably handle image transformations in a service
  2. retrieve images from a service
  3. use an input filter to validate files and parameters
  4. cache output (see http://zend-framework-community.634137.n4.nabble.com/How-to-handle-404-with-action-controller-td4659101.html eventually)

Related: Zend Framework - Returning Image/File using Controller

like image 146
Ocramius Avatar answered Sep 19 '22 15:09

Ocramius


Use a service for this and inject it to controllers needing the functionality.

like image 39
Hikaru-Shindo Avatar answered Sep 21 '22 15:09

Hikaru-Shindo