4

I need to get image directory means full path. I get the image path from the following code

$product = $this->productmodel->load($orderItem->getProductId());
$product->getThumbnail();

I got url

/w/b/wb02-green-0.jpg

I need

   /var/www/html/magento/pub/media/catalog/product/w/b/wb02-green-0.jpg

How do i get that i did following code

$path = $this->directorylist->getPath("media");

it returns

/var/www/html/magento/pub/media

but i need

/var/www/html/magento/pub/media/catalog/product/w/b/wb02-green-0.jpg

2 Answers 2

3

First, inject below class in your constructor

     use Magento\Catalog\Model\Product\Media\Config;
     use Magento\Framework\Filesystem;


    /** 
     * @var Config
     */
    private $mediaConfig;

    /**
     * @var Filesystem
     */
    private $filesystem;


    /**
     * @param Config $mediaConfig
     * @param Filesystem $filesystem
     */
    public function __construct(
        Config $mediaConfig,
        Filesystem $filesystem
    )
    {
        $this->mediaConfig = $mediaConfig;
        $this->filesystem = $filesystem;
    }

Now you can use this like,

        $directory = $this->filesystem->getDirectoryRead('media');
        $fullImagePath = $directory->getAbsolutePath($this->mediaConfig->getMediaPath($product->getThumbnail()));

Where $product is your product object.

1
  • Thank you for your answer . it saves my time . i need one more clarification if $product->getThumbnail() returns null. Then how do i get the default image Dec 20, 2018 at 5:48
4

A quick solution according to your tests:

$fullPath = $this->directorylist->getPath("media").'/catalog/product'.$product->getThumbnail();

Your Answer

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

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