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 \Magento\Catalog\Model\Category file and it is called getImageUrl, code snippet can be seen below -:

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

        return $url;
    }

If you are using your own class then you need to add \Magento\Catalog\Model\CategoryFactory $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 \Magento\Framework\Exception\LocalizedException
     */
    protected function getImageUrl($image)
    {
        $url = $image;
        if ($image) {
            if (is_string($image)) {
                $url = $this->storeManager->getStore()->getBaseUrl(
                        \Magento\Framework\UrlInterface::URL_TYPE_MEDIA
                    ) . 'catalog/category/' . $image;
            } else {
                throw new \Magento\Framework\Exception\LocalizedException(
                    __('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.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.