image resize zf2

2019-02-05 05:44发布

问题:

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.

回答1:

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



回答2:

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



回答3:

Here is a module called WebinoImageThumb in Zend Framework 2. Checkout this. It has some great feature such as -

  • Image Resize
  • Image crop, pad, rotate, show and save images
  • Create image reflection


回答4:

For those who are unable to integrate Imagine properly like me..

I found another solution WebinoImageThumb here which worked perfectly fine with me. Here is little explanation if you don't want to read full documentation :

Run: php composer.phar require webino/webino-image-thumb:dev-develop and add WebinoImageThumb as active module in config/application.config.php which further looks like :

<?php
return array(
    // This should be an array of module namespaces used in the application.
    'modules' => array(
        'Application',
        'WebinoImageThumb'
    ),

.. below remains the same

Now in your controller action use this through service locator like below :

// at top on your controller
use Zend\Validator\File\Size;
use Zend\Validator\File\ImageSize;
use Zend\Validator\File\IsImage;
use Zend\Http\Request

    // in action
$file = $request->getFiles();
$fileAdapter = new \Zend\File\Transfer\Adapter\Http();
$imageValidator = new IsImage();
if ($imageValidator->isValid($file['file_url']['tmp_name'])) {
    $fileParts = explode('.', $file['file_url']['name']);
    $filter = new \Zend\Filter\File\Rename(array(
               "target" => "file/path/to/image." . $fileParts[1],
               "randomize" => true,
              ));

    try {
         $filePath = $filter->filter($file['file_url'])['tmp_name'];
         $thumbnailer = $this->getServiceLocator()
                        ->get('WebinoImageThumb');
         $thumb = $thumbnailer->create($filePath, $options = [], $plugins = []);
         $thumb->adaptiveResize(540, 340)->save($filePath);

      } catch (\Exception $e) {
          return new ViewModel(array('form' => $form, 
                     'file_errors' => array($e->getMessage())));
      }
  } else {
      return new ViewModel(array('form' => $form, 
                 'file_errors' => $imageValidator->getMessages()));
  }

Good luck..!!



回答5:

In order to resize uploaded image on the fly you should do this:

public function imageAction() 
{
// ...
$imagine = $this->getImagineService();
$size = new \Imagine\Image\Box(150, 150);
$mode = \Imagine\Image\ImageInterface::THUMBNAIL_INSET;

$image = $imagine->open($destinationPath);
$image->thumbnail($size, $mode)->save($destinationPath);
// ...
}

public function getImagineService()
{
    if ($this->imagineService === null)
    {
        $this->imagineService = $this->getServiceLocator()->get('my_image_service');
    }
    return $this->imagineService;
}