Marco DC
Marco DC

Reputation: 49

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.

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?

Upvotes: 0

Views: 831

Answers (1)

vvpanchev
vvpanchev

Reputation: 577

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

Upvotes: 2

Related Questions