通过内容类型图像Yii的php文件显示图像


Display image via php file with content type image Yii

<?php
class TestController extends CController
{
    public function actionIndex()
    {
            $filename = "test.jpg";
            $path=Yii::getPathOfAlias('webroot.protected.images') . '/';
            $file=$path.$filename;
            if (file_exists($file))
            {
                $img=getimagesize($file);
                header('Content-Type: '.$img['mime']);
                readfile($file);
                exit;
            }
    }
    public function actionDisplayimg()
    {
            echo "<img src='".CController::createUrl('test/')."' />";
    }
}
?>

它无法在测试/索引或测试/显示图像上显示图像。有什么帮助吗?

我认为在调用readfile之前,您必须为其设置正确的标题和内容类型。

public function actionIndex()
{
        $filename = "test.jpg";
        $path=Yii::getPathOfAlias('webroot.protected.images') . '/';
        $file=$path.$filename;
        if (file_exists($file))
        {
               $request = Yii::app()->getRequest();
               $request->sendFile(basename($file),file_get_contents($file));
        }
好吧,

您可以调用 view 并从操作中传递一些参数并在那里显示它们

例如(未测试(

<?php
class TestController extends CController
{
    public function actionIndex()
    {
            $filename = "test.jpg";
            $path=Yii::getPathOfAlias('webroot.protected.images') . '/';
            $file=$path.$filename;
            if (file_exists($file))
            {
                $this->render('view',array(
            'filepath'=>$file,
        ));
    }
}
?>

view你可以做点什么

echo CHtml::image(filepath, 'image', array('class' => 'banner'));