Magento 2 Get image Url in controller or helper?

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


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'); ?>

Tags:

Image

Magento2