Category full image path in Magento 2

Full image path in Magento 2
Morning guys, today our team was working on category APIs for mobile app and we had to sent full image path of categories in the outcome of this API. Please see below the code snippet to get the image path either using existing Magento core function or if you already have category image name then you can write your own function to return category image path.

Method 1
Magento core function is available in MagentoCatalogModelCategory file and it is called getImageUrl, code snippet can be seen below -:

 /** * Get image url by attribute code. * * @param string $attributeCode * @return string * @throws MagentoFrameworkExceptionLocalizedException */ public function getImageUrl($attributeCode = 'image') { $url = false; $image = $this->getData($attributeCode); if ($image) { if (is_string($image)) { $url = $this->_storeManager->getStore()->getBaseUrl( MagentoFrameworkUrlInterface::URL_TYPE_MEDIA ) . 'catalog/category/' . $image; } else { throw new MagentoFrameworkExceptionLocalizedException( __('Something went wrong while getting the image url.') ); } } return $url; }

If you are using your own class then you need to add MagentoCatalogModelCategoryFactory $categoryFactory in the constructor and call the function below to get full category image path

$category = $this->categoryFactory->create()->load($categoryId);
$fullCategoryPath = $category->getImageUrl();
echo $fullCategoryPath

Method 2

If you already have category image name then you can write your own function to return full category image path using the following snippet

 /** * Get image url by imagename. * * @param string $image * @return string * @throws MagentoFrameworkExceptionLocalizedException */ protected function getImageUrl($image) { $url = $image; if ($image) { if (is_string($image)) { $url = $this->storeManager->getStore()->getBaseUrl( MagentoFrameworkUrlInterface::URL_TYPE_MEDIA ) . 'catalog/category/' . $image; } else { throw new MagentoFrameworkExceptionLocalizedException( __('Something went wrong while getting the image url.') ); } } return $url; } 

Hope this article helped you in some way. Please leave us your comment and let us know what do you think? Thanks.