使用 yii2 在控制器中显示加载的视图图像 [英] Display in view image loaded in controller with yii2
问题描述
我试图在视图中显示加载到控制器中的图像(图像文件夹不能直接从视图中使用).我可以在控制器中正确加载图像,但我没有找到正确的方法来提供视图.
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.
我试图利用 Yii::$app-> 响应解决方案,但它似乎对下载图像很有用,而不是在视图页面中显示它.
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.
控制器代码(部分)
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),
]);
}
我需要的是一种将图像存储在 imgModel
变量中的方法,然后将其显示在视图中
What I need is a way to store in imgModel
variable the image and then show it in the view
当然也欢迎其他方式
有人能给我建议吗?
推荐答案
您可以使用以下代码向您展示图像:
You can show you image with this code:
<?= Html::img('@web/app/myfiles/img/65/img.jpg', ['alt' => 'My image']) ?>
检查这个 - https://www.yiiframework.com/doc/guide/2.0/en/helper-html 部分图像"
Check this - https://www.yiiframework.com/doc/guide/2.0/en/helper-html section "Images"
如果您的图片不在网络文件夹中 - 将其 mvoe 或尝试其他方式:
If your image is not in web folder - mvoe it or try another way:
在您的控制器中:
$imgFullPath = '/app/myfiles/img/65/img.jpg';
$imgContentBase64 = base64_encode(file_get_contents($imgFullPath));
在您看来:
<?= Html::img('data:image/jpeg;base64,'.$imgContentBase64 , ['alt' => 'My image']) ?>
您还必须检查您的 MIME 类型
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
这篇关于使用 yii2 在控制器中显示加载的视图图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!