12

I need to get the file PATH for an image in pub/static/[VENDOR_THEME] folder.

Currently, I can do this by using a helper:

public function __construct(
    \Magento\Framework\App\Helper\Context $context,
    \Magento\Framework\View\Asset\Repository $assetRepository,
    \Magento\Framework\App\Filesystem\DirectoryList $directoryList
) {
    parent::__construct($context);
    $this->_assetRepo = $assetRepository;
    $this->_directoryList = $directoryList;
}

public function getImagePath($image)
{
    return $this->_directoryList->getPath(DirectoryList::STATIC_VIEW) . 
        '/' . 
        $this->_assetRepo->getStaticViewFileContext()->getPath() . 
        '/' . 
        $image;
}

Is there any built-in Magento function which handles this, so I do not have to create my own helper?

1
  • How about your issue? Commented Feb 27, 2017 at 17:19

2 Answers 2

14

As @Khoa TruongDinh states you can use the Magento\Framework\View\Asset\Repository to get a file class Magento\Framework\View\Asset\File, which you can then use to get various data.

/** @var `Magento\Framework\View\Asset\Repository $assetRepository **/
 $asset = $this->assetRepository->createAsset('Magento_Catalog::images/image.png');
 $asset = $this->assetRepository->createAsset('My_Module::images/image.png');

To get asset in your theme folder app/design/frontend/VENDOR/THEME/web simply strip the module name as below....

$asset = $this->assetRepository->createAsset('images/image.png');

See Magento\Framework\View\Asset\File for functions you can use to get file data.

// Get the file url
$asset->getUrl();

// Get the file path
$asset->getFilePath();

// Get the content of the file
$asset->getContent();
1
  • this code is not working in RecurringData.php Commented Nov 27, 2019 at 10:47
2

In our block, we should try with:

$block->getViewFileUrl('/')

enter image description here

Take a look:

  • vendor/magento/module-backend/view/adminhtml/templates/page/js/require_js.phtml

  • vendor/magento/module-theme/view/frontend/templates/page/js/require_js.phtml

EDIT: we can use Magento\Framework\View\Asset\Repository

For example: your image is under : app/code/Vendor/Module/view/frontend/web/images/image.png

/** @var `Magento\Framework\View\Asset\Repository $assetRepository **/

$this->assetRepository->getUrlWithParams('Vendor_Module::images/image.png', $params);

See more here: Magento 2 Get image Url in controller or helper?

3
  • 2
    I need the PATH - not the url
    – minlare
    Commented Jan 26, 2017 at 8:37
  • @minlare see my updated answer. Commented Feb 7, 2017 at 14:06
  • This code I am trying in RecurringData.php, its not working Commented Nov 27, 2019 at 10:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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