图像调整大小zf2

Pra*_*ant 6 image-resizing zend-framework2

我需要在zend框架2中实现图像大小调整功能(最好使用gd2库扩展).

我找不到相同的任何组件/帮助器.任何参考?

如果我想创建一个,我应该在哪里添加它.在较旧的Zend框架中,有一个Action Helper的概念,那么Zend框架2呢?

请在此提出最佳解决方案.

Ocr*_*ius 17

我目前使用ImagineZend Framework 2来处理这个问题.

  1. 安装想象: php composer.phar require imagine/Imagine:0.3.*
  2. Imagine服务(in YourModule::getServiceConfig)创建服务工厂:

    return array(
        'invokables' => array(
            // defining it as invokable here, any factory will do too
            'my_image_service' => 'Imagine\Gd\Imagine',
        ),
    );
    
    Run Code Online (Sandbox Code Playgroud)
  3. 在你的逻辑中使用它(这是一个带控制器的小例子):

    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;
    }
    
    Run Code Online (Sandbox Code Playgroud)

这显然是"快速而肮脏"的方式,因为您应该遵循以下(可重复使用的可选但良好的做法):

  1. 可能处理服务中的图像转换
  2. 从服务中检索图像
  3. 使用输入过滤器来验证文件和参数
  4. 缓存输出(最终参见http://zend-framework-community.634137.n4.nabble.com/How-to-handle-404-with-action-controller-td4659101.html)

相关:Zend框架 - 使用Controller返回图像/文件