Magento 2 – How to Get Image from Swatch ID

color-swatchesmagento2swatches

I have attribute color_swatch which is visual swatch and it has some items with images.
In my code I can take this data:

[swatch_id] => 57
[color_swatch] => Red

[swatch_id] => 58
[color_swatch] => Blue

[swatch_id] => 59
[color_swatch] => Black

How can I get image of the swatch using this data?

Best Answer

You can get swatch Image from this,

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$swatch = $objectManager->create('Magento\Swatches\Model\Swatch')->load($swatchId);

$imageName=$swatch->getData('value');

if(!empty($imageName)){
$imagePath=$objectManager->create('Magento\Swatches\Helper\Media')->getSwatchMediaUrl().$imageName;
echo $imagePath;
}

You can find Image value from eav_attribute_option_swatch table. Where value is Image path and type 1 is uploaded image filer and 2 is color selected from color swatch.


Note: I am against of direct loading object with $objectManager, for better impact you can inject it in your constructor. I have just given example how you can achieve it. `