Display in view image loaded in controller with yii2

情到浓时终转凉″ 提交于 2021-02-11 15:22:52

问题


I'm trying to display in a view an image loaded in a controller (the image folder is not available directly from the view). I can correctly load the image in the controller but I did not find the correct way in order to provide the view with it.

I tried to exploit the Yii::$app->response solution but it seems useful for the download of the image and not for showing it in the view page.

Controller code (partial)

public function actionView($id)
{
     $imgFullPath = '/app/myfiles/img/65/img.jpg';

     return $this->render('view', [
         'model' => $this->findModel($id),
         'imgModel' => Yii::$app->response->sendFile($imgFullPath),
      ]);
}

What I need is a way to store in imgModel variable the image and then show it in the view

Of course also alternative way are welcome

Can someone give me a suggestion?


回答1:


You can show you image with this code:

<?= Html::img('@web/app/myfiles/img/65/img.jpg', ['alt' => 'My image']) ?>

Check this - https://www.yiiframework.com/doc/guide/2.0/en/helper-html section "Images"

If your image is not in web folder - mvoe it or try another way:

in your controller:

$imgFullPath = '/app/myfiles/img/65/img.jpg';
$imgContentBase64 = base64_encode(file_get_contents($imgFullPath));

in your view:

<?= Html::img('data:image/jpeg;base64,'.$imgContentBase64 , ['alt' => 'My image']) ?>

Also you have to check for your MIME type

image/jpeg for .jpg and .jpeg files
image/png for .png files
image/gif fir .gif files


来源:https://stackoverflow.com/questions/64932881/display-in-view-image-loaded-in-controller-with-yii2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!