How to get an image URL for a product programmatically?

Use \Magento\Catalog\Helper\Image::getUrl().

fad606f29aa039b8e6d746a774508274b5f7c560/Core/lib/catalog.php?ts=4#L27-L72

/**
 * 2016-04-23
 * How to get an image URL for a product programmatically?
 * https://mage2.pro/t/1313
 * How is @uses \Magento\Catalog\Helper\Image::getUrl() implemented and used?
 * https://mage2.pro/t/1316
 * @param Product $product
 * @param string|null $type [optional]
 * @param array(string => string) $attrs [optional]
 * @return string
 */
function df_product_image_url(Product $product, $type = null, $attrs = []) {
	/** @var string|null $result */
	if ($type) {
		$result = df_catalog_image_h()
			->init($product, $type, ['type' => $type] + $attrs + df_view_config()->getMediaAttributes(
				'Magento_Catalog', ImageHelper::MEDIA_TYPE_CONFIG_NODE, $type
			))
			->getUrl()
		;
	}
	else {
		/**
		 * 2016-05-02
		 * How is @uses \Magento\Catalog\Model\Product::getMediaAttributes() implemented and used?
		 * https://mage2.pro/t/1505
		 * @var string[] $types
		 */
		$types = array_keys($product->getMediaAttributes());
		// Give priority to the «image» attribute.
		/** @var int|null $key */
		$key = array_search('image', $types);
		if (false !== $key) {
			unset($types[$key]);
			array_unshift($types, 'image');
		}
		$result = '';
		foreach ($types as $type) {
			$result = df_product_image_url($product, $type, $attrs);
			if ($result) {
				break;
			}
		}
	}
	return $result;
}
1 Like

See also:

1 Like