How to Get Full Path URL for Configuration Image Field in Magento 2

magento2

Check below code which I have used for upload image in configuration.

<field id="icon" translate="label comment" type="image" sortOrder="150" showInDefault="1" showInWebsite="1" showInStore="1">
    <label>Icon</label>
    <backend_model>Magento\Config\Model\Config\Backend\Image</backend_model>
    <upload_dir config="system/filesystem/media" scope_info="1">{vender_name}/{module_name}/icon</upload_dir>
    <base_url type="media" scope_info="1">{vender_name>/{module_name}/icon</base_url>
</field>

But when I try to retrieve image URL based on below code, It's getting only default/image_name.ext

$this->scopeConfig->getValue("<section>/<group>/icon", \Magento\Store\Model\ScopeInterface::SCOPE_STORE);

How can I get full path of image URL?

Best Answer

You can use ObjectManager or Block.

Objectmanager :

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$store = $objectManager->get('Magento\Store\Model\StoreManagerInterface')->getStore();
$imageUrl = $store->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . 'catalog/product' . $product->getImage();

Block :

protected $_storeManagerInterface;

public function __construct(
  ...
  \Magento\Store\Model\StoreManagerInterface $storeManagerInterface,
  ...
)
{
  ...
  $this->_storeManagerInterface = $storeManagerInterface;
  ...
}

...

public function getStoreInterface($imgUrl){
   $store = $this->_storeManagerInterface->getStore();
   $storeMedia = $store->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . 'catalog/product' . $imgUrl;
   return $storeMedia;
}
...

Call the function :

<img src="<?php echo $block->getStoreInterface($imgUrl) ?>"/>

And don't forget to add your module class to XML.

example :

<block class="<vendor>\<module>\Block\<yourblockname>" name="" template="YOUR TEMPLATE FILE" />
Related Topic