You can Retrieve the list of gallery image entries associated with given product by SKU value in Magento 2.
Using the ProductAttributeMediaGalleryManagement Interface, You can use getList($sku) method to achieve the all the media entry for the product.
Result will be array of the images with details of image path, position, type assigned like small thumbnail or swatch, label and id.
<?php namespace Jesadiya\MediaGallery\Model; use Exception; use Magento\Catalog\Api\ProductAttributeMediaGalleryManagementInterface; use Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface; class GetMediaGallery { /** * @var ProductAttributeMediaGalleryManagementInterface */ private $productAttributeMediaGallery; public function __construct( ProductAttributeMediaGalleryManagementInterface $productAttributeMediaGallery ) { $this->productAttributeMediaGallery = $productAttributeMediaGallery; } /** * @param string $sku * @return ProductAttributeMediaGalleryEntryInterface[] */ public function getMediaGallery($sku) { $gallery = []; try { $gallery = $this->productAttributeMediaGallery->getList($sku); } catch (Exception $exception) { throw new Exception($exception->getMessage()); } return $gallery; } }
You can get the all the images assigned to the product, Iterate over a loop to the gallery array to fetch the specific image details.
Take a SKU from the Native Sample data Product, 24-MB03
$sku = '24-MB03'; $result = $this->getMediaGallery($sku); foreach ($gallery as $image) { echo "<pre>";print_r($image->getData()); }
Output:
Array ( [file] => /m/b/mb03-black-0.jpg [media_type] => image [label] => Image [position] => 1 [disabled] => 0 [types] => Array ( [0] => image [1] => small_image [2] => thumbnail ) [id] => 4 ) Array ( [file] => /m/b/mb03-black-0_alt1.jpg [media_type] => image [label] => Image [position] => 2 [disabled] => 0 [types] => Array ( ) [id] => 5 )
You can see the result of the images as array with all the details.