If you want to get the cache path (hash) of the small_image on PLP then you can get the following way.
- Need to get the size of the small_image from view.xml.
- Need to generate the directory hash.
- Generate an URL, based on the hash.
1. Step
Inject this class into the constructor.
use Magento\Framework\View\ConfigInterface as ViewConfigInterface;
Then you can retrieve width and height like this. If the sizes are different in the GRID view then need to use category_page_grid instead of category_page_list. (But you can use any other id here.)
$imagesConfig =$this->viewConfig->getViewConfig()->getMediaEntities(
'Magento_Catalog',
'images'
);
$width = $imagesConfig['category_page_list']['width'];
$height = $imagesConfig['category_page_list']['height'];
2. step
Inject EncryptorInterface into the constructor.
use Magento\Framework\Encryption\Encryptor;
use Magento\Framework\Encryption\EncryptorInterface;
Then you need this function.
/**
* Converting bool into a string representation
*
* @param array $miscParams
* @return array
*/
private function convertToReadableFormat(array $miscParams)
{
$miscParams['image_height'] = 'h:' . ($miscParams['image_height'] ?? 'empty');
$miscParams['image_width'] = 'w:' . ($miscParams['image_width'] ?? 'empty');
$miscParams['quality'] = 'q:' . ($miscParams['quality'] ?? 'empty');
$miscParams['angle'] = 'r:' . ($miscParams['angle'] ?? 'empty');
$miscParams['keep_aspect_ratio'] = (!empty($miscParams['keep_aspect_ratio']) ? '' : 'non') . 'proportional';
$miscParams['keep_frame'] = (!empty($miscParams['keep_frame']) ? '' : 'no') . 'frame';
$miscParams['keep_transparency'] = (!empty($miscParams['keep_transparency']) ? '' : 'no') . 'transparency';
$miscParams['constrain_only'] = (!empty($miscParams['constrain_only']) ? 'do' : 'not') . 'constrainonly';
$miscParams['background'] = !empty($miscParams['background'])
? 'rgb' . implode(',', $miscParams['background'])
: 'nobackground';
return $miscParams;
}
Finally, you can get the path like this:
$path = $this->encryptor->hash(
implode('_', $this->convertToReadableFormat([
'image_height' => $height,
'image_width' => $width,
'background' => [255, 255, 255],
'angle' => null,
'quality' => 80,
'keep_aspect_ratio' => true,
'keep_frame' => true,
'keep_transparency' => true,
'constrain_only' => true,
])),
Encryptor::HASH_VERSION_MD5
);
3. step
You can use StoreManager to get the media URL and generate the URL.
{MEDIA_URL}/catalog/product/cache/{CACHE_PATH}