将内容类型更改为image / png - cakephp

时间:2013-02-25 09:10:59

标签: image cakephp content-type

我有一个cakephp应用程序。我知道我的应用程序使用default.ctp进行布局。在默认布局中,我的标题设置为html / text。我想将我的标题类型更改为image / png。我应该在哪里更改 ?请别人帮助我

代码:

$this->layout=NULL; 
$this->autoRender=false; 
$this->RequestHandler->respondAs('image/jpg');

      View Coding :(index.ctp)
           <?php 
           session_start(); 
           $text = rand(10000,99999); 
           $_SESSION["vercode"] = $text; 
           $height = 25; 
           $width = 65; 

           $image_p = imagecreate($width, $height); 
           $black = imagecolorallocate($image_p, 0, 0, 0); 
            $white = imagecolorallocate($image_p, 255, 255, 255); 
            $font_size = 14; 
            imagestring($image_p, $font_size, 5, 5, $text, $white); 
            imagejpeg($image_p, null, 80); 
                  ?>
           Controller coding :

                public function index() 
                {
                      $this->layout=false;
                      $this->response->type('png');
                } 

注意:CakePHP版本2.3.0

3 个答案:

答案 0 :(得分:2)

使用CakePHP 3

您应该始终尝试使用CakePHP方式,而不是使用PHP的header()函数手动设置标头。在这种情况下,文档不是很清楚。我不得不弄清楚。

这就是我使用CakePHP 3.3实现它的方法:

  • 首先,将图像的内容放入变量中,因为我们希望CakePHP呈现内容,而不仅仅是输出和死亡。

  • 然后销毁图像资源以释放内存。

  • 可选:您可以设置缓存标头。 (在下面的代码中评论)

  • 将响应对象类型设置为&#34; jpg&#34;或&#34; png&#34;等。See docs

  • 将布局设置为:&#34; false &#34;

  • 将图像输出到响应正文并将autoRender设置为false,以避免创建不必要的模板文件(.ctp)。

// Controller method
public function image($id = null) {
    // Create an image resource: $image ...
    ob_start();
    imagejpeg($image);
    $buffer = ob_get_clean();
    imagedestroy($image);

    // $this->response->cache('-1 minute', '+1 days');
    $this->response->type('jpg');
    $this->viewBuilder()->layout(false);
    $this->response->body($buffer);
    $this->autoRender = false;
}

答案 1 :(得分:1)

如果你真的必须将视图/布局的内容作为图像返回(我非常怀疑):

$this->response->type('png'); // as documented in the 2.x docs

会自动将image/png设置为标题的响应类型。

如果您需要在没有布局的情况下渲染视图,请尝试

$this->layout = false;
// OR
$this->render('my_view', false); // false should not render a layout

您无法使用“null”,因为它会呈现默认布局。

无论哪种方式,都不要在视图中调用header()内容,始终通过响应对象在控制器中调用。

答案 2 :(得分:0)

(是的,旧线程,但我刚遇到这个问题。)

$this->autoRender = false;
header('Content-Type: image/png');

在Controller的方法中为我工作。