image resize zf2

前端 未结 5 1470
情话喂你
情话喂你 2020-12-30 13:52

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

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-30 14:46

    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

提交回复
热议问题