PHP图像通过控制器访问时不显示

时间:2012-03-08 07:21:56

标签: php model-view-controller image-processing controller gd

我正在设计自己的PHP MVC

其中任何库文件都可以通过以下步骤使用:

  1. 加载文件$this->registry->load->lib('Image');

  2. 从文件$this->registry->Image->anyMethod();

  3. 访问方法

    第一行加载位于Image.php文件夹中的文件lib并返回instance 作为$this->registry->Image

    然后使用该实例,文件中的方法anyMethod()可以$this->registry->Image->anyMethod();

    Controller访问

    问题在于,我无法输出任何图像!

    如果从Controller访问以下代码不起作用,但如果直接使用则无效!

    代码来自http://in2.php.net/imagettftext

    public function anyMethod()
    {
    // Set the content-type
    header('Content-Type: image/png');
    
    // Create the image
    $im = imagecreatetruecolor(400, 30);
    
    // Create some colors
    $white = imagecolorallocate($im, 255, 255, 255);
    $grey = imagecolorallocate($im, 128, 128, 128);
    $black = imagecolorallocate($im, 0, 0, 0);
    imagefilledrectangle($im, 0, 0, 399, 29, $white);
    
    // The text to draw
    $text = 'Testing...';
    // Replace path by your own font path
    $font = 'arial.ttf';
    
    // Add some shadow to the text
    imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);
    
    // Add the text
    imagettftext($im, 20, 0, 10, 20, $black, $font, $text);
    
    // Using imagepng() results in clearer text compared with imagejpeg()
    imagepng($im);
    imagedestroy($im);
    }
    

    请帮助,我被困住了。

    注意:在ob_clean();之前添加imagepng($im);似乎有效,但图片上没有文字。

1 个答案:

答案 0 :(得分:0)

在销毁图像后添加exit;调用,以防止MVC系统添加任何进一步的输出:

imagepng($im);
imagedestroy($im);
exit;

同时检查在Content-type来电之前没有发出其他anyMethod()标题。