Magento 2.2.6 – How to Get the Image Directory

directoryimagemagento2.2.6

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

Best Answer

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.