Magento – Magento2 – Get image url in model/helper

helperimagemagento2module

I have a helper class Email under vendor/module/model/helper/Email.php

I have to access a image in the module_path/view/frontend/web/images

I can't use $this->getViewFileUrl('vendor_module::images/image.jpg'); or $block->getViewFileUrl('vendor_module::images/image.jpg');

How can I call the image in my helper class?

Helper file

<?php

namespace Vendor\Module\Model\Helper;

use Magento\Framework\View\Asset\Repository;
use Magento\Framework\App\RequestInterface;

/**
 * Class Email
 * @package Vendor\Module\Model\Helper
 */
class Email
{
    protected $request;

    public function __construct(
        \Magento\Framework\App\Request\Http $request
    )
    {
        $this->request = $request;
    }
    /**
     * @param array $params
     */
    public function sendBasicmoduleFormMails(array $params)
    {
        $params = array('_secure' => $this->request->isSecure());
        $image = $this->assetRepo->getUrlWithParams('Vendor_Module::images/image.jpg', $params);
        $headers = 'MIME-Version: 1.0' . "\r\n";
        $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
        $headers .= "From: <from_email>" . "\r\n" .

        $headers .= "X-Mailer: PHP/" . phpversion();
        $body = "Some email content with an {$image}";

        mail(some_email, 'a subject', $body, $headers);
    }
}

Best Answer

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->result

protected $request;

public function __construct(
      Repository $assetRepo,
      RequestInterface $request,
)
{
      $this->assetRepo = $assetRepo;
      $this->request = $request;
}

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

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

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