9

How to get the image in the controller or helper. For example, the path of images folder:

 /app/code/Nitesh/Module/view/frontend/web/images
 /app/code/Nitesh/Module/view/frontend/web/images/image.png
12

Use below code for getting image url in view

<img src="<?php echo $this->getViewFileUrl('Vendor_Module::images/image.png'); ?>" />

UPDATE:

<?php echo $block->getViewFileUrl('images/demo.jpg'); ?>
  • 1
    This answer is nice and simple. The first option worked for me. – Milan Simek May 31 '17 at 16:16
  • how to get in controller file? – jafar pinjar Nov 26 '19 at 12:42
20

To get Image Path in your Helper or Controller, you need to use

use Magento\Framework\View\Asset\Repository;
use Magento\Framework\App\RequestInterface; // for $this->request

in your file.
Once you add the repository and create object assetRepo & request, call image path with function,

$params = array('_secure' => $this->request->isSecure());
$this->assetRepo->getUrlWithParams('Nitesh_Module::images/image.png', $params);

Refer to vendor\magento\module-payment\Model\CcConfig.php::getViewFileUrl($fileId, array $params = []) function

EDIT

To get correct image paths for Setup scripts, API calls and Cronjobs, you will require to add emulation like below to get correct image paths.

public function __construct(
    \Magento\Framework\View\Asset\Repository $assetRepo,
    \Magento\Framework\App\RequestInterface $request,
    \Magento\Store\Model\App\Emulation $appEmulation
)
{
    $this->assetRepo = $assetRepo;
    $this->request = $request;
    $this->appEmulation = $appEmulation;
}

public FunctionName($param){
    $this->appEmulation->startEnvironmentEmulation($storeId, \Magento\Framework\App\Area::AREA_FRONTEND, true);

    $params = array('_secure' => $this->request->isSecure());
    $this->assetRepo->getUrlWithParams('Nitesh_Module::images/image.png', $params);

    $this->appEmulation->stopEnvironmentEmulation();
}

Reference: https://magento.stackexchange.com/a/297121/2443

  • Error comes -> Notice: Undefined property: ...::$request in – Nitesh Feb 7 '17 at 7:10
  • got it from your reference ty – Nitesh Feb 7 '17 at 7:20
  • Thanks alot man. Its really helpful to getting image url. – Nitesh Feb 7 '17 at 7:29
  • @Jaimin, this is not working in recurringData.php, have u tried there? – jafar pinjar Nov 27 '19 at 10:32
  • 1
    @JaiminSutariya, Yes. I'm trying in RecurringData.php, where i set Area_code as Global, so the Url is forming with _view/global which is not working, you may try once with RecurringData.php , then u you will get the idea about the issue – jafar pinjar Nov 27 '19 at 13:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.