How to get product image and url in Magento 2 The 2019 Stack Overflow Developer Survey Results Are InHow to load multiple id's for products in magento 2 using objectManager?Magento 2 PHP Foreach loop help!Product Atttribute ImageSet custom price of product when adding to cart code not workingHow to get Tier Price of product magento2?Magento 2 Sending emails triggered by observermagento 2 get child product image thumbnailMagento 2: Add a product to the cart programmaticallyGet product id from order historyMagento 2: I Want to add multiple product using checkboxHow can Save API respond (For each order request - PDF file) with order id in database?Magento 2.2.5: Add, Update and Delete existing products Custom OptionsMagento 2.2.3 CE unable to add/remove item from wishlist?

How to charge AirPods to keep battery healthy?

Is bread bad for ducks?

Accepted by European university, rejected by all American ones I applied to? Possible reasons?

Why don't hard Brexiteers insist on a hard border to prevent illegal immigration after Brexit?

What to do when moving next to a bird sanctuary with a loosely-domesticated cat?

Does HR tell a hiring manager about salary negotiations?

Why are there uneven bright areas in this photo of black hole?

What is this sharp, curved notch on my knife for?

How do I free up internal storage if I don't have any apps downloaded?

How do you keep chess fun when your opponent constantly beats you?

Short story: child made less intelligent and less attractive

What is the most efficient way to store a numeric range?

Can a flute soloist sit?

Loose spokes after only a few rides

Is an up-to-date browser secure on an out-of-date OS?

If I score a critical hit on an 18 or higher, what are my chances of getting a critical hit if I roll 3d20?

Why does the nucleus not repel itself?

Falsification in Math vs Science

Why isn't the circumferential light around the M87 black hole's event horizon symmetric?

Match Roman Numerals

What is the motivation for a law requiring 2 parties to consent for recording a conversation

Why didn't the Event Horizon Telescope team mention Sagittarius A*?

How to support a colleague who finds meetings extremely tiring?

How to notate time signature switching consistently every measure



How to get product image and url in Magento 2



The 2019 Stack Overflow Developer Survey Results Are InHow to load multiple id's for products in magento 2 using objectManager?Magento 2 PHP Foreach loop help!Product Atttribute ImageSet custom price of product when adding to cart code not workingHow to get Tier Price of product magento2?Magento 2 Sending emails triggered by observermagento 2 get child product image thumbnailMagento 2: Add a product to the cart programmaticallyGet product id from order historyMagento 2: I Want to add multiple product using checkboxHow can Save API respond (For each order request - PDF file) with order id in database?Magento 2.2.5: Add, Update and Delete existing products Custom OptionsMagento 2.2.3 CE unable to add/remove item from wishlist?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








14















This is my observer:



public function execute(MagentoFrameworkEventObserver $observer)

$orderIds = $observer->getEvent()->getOrderIds();
$order = $this->_orderRepositoryInterface->get($orderIds[0]);
$items =$order->getAllVisibleItems();
$productQuantity = array();
$productPrice = array();
$productName = array();
$productIds = array();
foreach($items as $item)
$productIds[]= $item->getProductId();
$productName[]= $item->getSku();
$productPrice[] = $item->getPrice();
$productQuantity[]= floor($item->getQtyOrdered());




How can I get product image and product url from item?










share|improve this question
























  • Which event you catched?

    – Khoa TruongDinh
    Sep 19 '16 at 12:41











  • checkout_onepage_controller_success_action

    – Ramkishan Suthar
    Sep 19 '16 at 12:46

















14















This is my observer:



public function execute(MagentoFrameworkEventObserver $observer)

$orderIds = $observer->getEvent()->getOrderIds();
$order = $this->_orderRepositoryInterface->get($orderIds[0]);
$items =$order->getAllVisibleItems();
$productQuantity = array();
$productPrice = array();
$productName = array();
$productIds = array();
foreach($items as $item)
$productIds[]= $item->getProductId();
$productName[]= $item->getSku();
$productPrice[] = $item->getPrice();
$productQuantity[]= floor($item->getQtyOrdered());




How can I get product image and product url from item?










share|improve this question
























  • Which event you catched?

    – Khoa TruongDinh
    Sep 19 '16 at 12:41











  • checkout_onepage_controller_success_action

    – Ramkishan Suthar
    Sep 19 '16 at 12:46













14












14








14


2






This is my observer:



public function execute(MagentoFrameworkEventObserver $observer)

$orderIds = $observer->getEvent()->getOrderIds();
$order = $this->_orderRepositoryInterface->get($orderIds[0]);
$items =$order->getAllVisibleItems();
$productQuantity = array();
$productPrice = array();
$productName = array();
$productIds = array();
foreach($items as $item)
$productIds[]= $item->getProductId();
$productName[]= $item->getSku();
$productPrice[] = $item->getPrice();
$productQuantity[]= floor($item->getQtyOrdered());




How can I get product image and product url from item?










share|improve this question
















This is my observer:



public function execute(MagentoFrameworkEventObserver $observer)

$orderIds = $observer->getEvent()->getOrderIds();
$order = $this->_orderRepositoryInterface->get($orderIds[0]);
$items =$order->getAllVisibleItems();
$productQuantity = array();
$productPrice = array();
$productName = array();
$productIds = array();
foreach($items as $item)
$productIds[]= $item->getProductId();
$productName[]= $item->getSku();
$productPrice[] = $item->getPrice();
$productQuantity[]= floor($item->getQtyOrdered());




How can I get product image and product url from item?







magento2






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 5 '17 at 2:51









thaddeusmt

933518




933518










asked Sep 19 '16 at 12:37









Ramkishan SutharRamkishan Suthar

2,29221435




2,29221435












  • Which event you catched?

    – Khoa TruongDinh
    Sep 19 '16 at 12:41











  • checkout_onepage_controller_success_action

    – Ramkishan Suthar
    Sep 19 '16 at 12:46

















  • Which event you catched?

    – Khoa TruongDinh
    Sep 19 '16 at 12:41











  • checkout_onepage_controller_success_action

    – Ramkishan Suthar
    Sep 19 '16 at 12:46
















Which event you catched?

– Khoa TruongDinh
Sep 19 '16 at 12:41





Which event you catched?

– Khoa TruongDinh
Sep 19 '16 at 12:41













checkout_onepage_controller_success_action

– Ramkishan Suthar
Sep 19 '16 at 12:46





checkout_onepage_controller_success_action

– Ramkishan Suthar
Sep 19 '16 at 12:46










5 Answers
5






active

oldest

votes


















18














This way may not a best way to get product image.



Inject MagentoCatalogApiProductRepositoryInterfaceFactory in our constructor.



protected $_productRepositoryFactory;

public function __construct(
MagentoCatalogApiProductRepositoryInterfaceFactory $productRepositoryFactory
)

$this->_productRepositoryFactory = $productRepositoryFactory;



We can get the image:



$product = $this->_productRepositoryFactory->create()->getById($item->getProductId());
$product->getData('image');
$product->getData('thumbnail');
$product->getData('small_image');





share|improve this answer

























  • your answer is right but what shoild i do if i have more than one product in cart how can i show more than one product image

    – Ramkishan Suthar
    Sep 20 '16 at 4:17











  • ok i got it @khoa. if i have more than one produc image. thanks alot

    – Ramkishan Suthar
    Sep 20 '16 at 4:22











  • This is not working. Value returned is some kind of string like this "/w/s/wsh10-orange_main.jpg"

    – piavgh
    Oct 17 '16 at 1:37






  • 1





    @piavgh it's the path to image: pub/media/catalog/product

    – Khoa TruongDinh
    Oct 17 '16 at 2:17






  • 1





    so how do i use /w/s/wsh10-orange_main.jpg in <img src="" /> attribute so i can load the actual image

    – Lachezar Raychev
    Nov 8 '17 at 11:06


















13














If you want the published/cache frontend URL of an image for a specific store view (like I did) this is working for me:



/**
* @var MagentoStoreModelAppEmulation
*/
protected $appEmulation;

/**
* @var MagentoStoreModelStoreManagerInterface
*/
protected $storeManager;

/**
* @var MagentoCatalogApiProductRepositoryInterfaceFactory
*/
protected $productRepositoryFactory;

/**
* @var MagentoCatalogHelperImageFactory
*/
protected $imageHelperFactory;

/**
* @param MagentoStoreModelStoreManagerInterface $storeManager
* @param MagentoStoreModelAppEmulation $appEmulation
* @param MagentoCatalogApiProductRepositoryInterfaceFactory $productRepositoryFactory
* @param MagentoCatalogHelperImageFactory $helperFactory
*/
public function __construct(
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoStoreModelAppEmulation $appEmulation,
MagentoCatalogApiProductRepositoryInterfaceFactory $productRepositoryFactory,
MagentoCatalogHelperImageFactory $imageHelperFactory
)

$this->storeManager = $storeManager;
$this->appEmulation = $appEmulation;
$this->productRepositoryFactory = $productRepositoryFactory;
$this->imageHelperFactory = $imageHelperFactory;



Then, wherever you need to get the image frontend URL:



$sku = "my-sku";
// get the store ID from somewhere (maybe a specific store?)
$storeId = $this->storeManager->getStore()->getId();
// emulate the frontend environment
$this->appEmulation->startEnvironmentEmulation($storeId, MagentoFrameworkAppArea::AREA_FRONTEND, true);
// load the product however you want
$product = $this->productRepositoryFactory->create()->get($sku);
// now the image helper will get the correct URL with the frontend environment emulated
$imageUrl = $this->imageHelperFactory->create()
->init($product, 'product_thumbnail_image')->getUrl();
// end emulation
$this->appEmulation->stopEnvironmentEmulation();


You can select other images types besides product_thumbnail_image: see magento/theme-frontend-luma/etc/view.xml for a list of available product images, or create your own in a view.xml file.






share|improve this answer

























  • WTF? that is just sick :D

    – Lachezar Raychev
    Nov 2 '17 at 9:13











  • Just tried this solution and I'm not getting any errors, though the returned URL doesn't exist and the string is empty. I've tried with 'product_base_image', 'product_small_image' and 'product_thumbnail_image', none of which work. Can you advise please? Or is there an efficient way to do this using the product repository? As I am already loading that elsewhere in my block.

    – Joshua Flood
    Apr 24 '18 at 15:57


















6














If you need to return a product URL it should look like this:



//todo get product object $product 

$objectManager =MagentoFrameworkAppObjectManager::getInstance();
$helperImport = $objectManager->get('MagentoCatalogHelperImage');

$imageUrl = $helperImport->init($product, 'product_page_image_small')
->setImageFile($product->getSmallImage()) // image,small_image,thumbnail
->resize(380)
->getUrl();
echo $imageUrl;





share|improve this answer






























    5














    That's the way I did. it's quite efficient and clean:



    1) First, you need to inject the following classes:



    protected $_storeManager;
    protected $_appEmulation;
    protected $_blockFactory;

    public function __construct(
    ...
    MagentoStoreModelStoreManagerInterface $storeManager,
    MagentoFrameworkViewElementBlockFactory $blockFactory,
    MagentoStoreModelAppEmulation $appEmulation)

    $this->_storeManager = $storeManager;
    $this->_blockFactory = $blockFactory;
    $this->_appEmulation = $appEmulation;



    2) Then, create a getImageUrl method with the code below:



    protected function getImageUrl($product, string $imageType = '')

    $storeId = $this->_storeManager->getStore()->getId();

    $this->_appEmulation->startEnvironmentEmulation($storeId, MagentoFrameworkAppArea::AREA_FRONTEND, true);

    $imageBlock = $this->_blockFactory->createBlock('MagentoCatalogBlockProductListProduct');
    $productImage = $imageBlock->getImage($product, $imageType);
    $imageUrl = $productImage->getImageUrl();

    $this->_appEmulation->stopEnvironmentEmulation();

    return $imageUrl;



    Note: The "appEmulation" code is only necessary when you making this call from the admin or for an API. Otherwise, you will get the error below (or similar):



    Unable to resolve the source file for 'webapi_rest/_view/en_AU/Magento_Catalog/images/product/placeholder/.jpg'


    3) Call the getImageUrl passing the product object and the type of image you want (based on your view.xml file)



    ...
    $smallImage = $this->getImageUrl($productObject, 'product_page_image_small');
    ...





    share|improve this answer
































      0














      For gettting custom image url I used this code. So if the image does not exits it will load the default theme image.



      $product = $block->getProduct();

      $productImageAttr = $product->getCustomAttribute('product_banner_image');

      if ($productImageAttr && $productImageAttr->getValue() != 'no_selection')

      $productImage = $this->helper('MagentoCatalogHelperImage')
      ->init($product, 'product_banner_image')
      ->setImageFile($productImageAttr->getValue());

      $imageUrl = $productImage->getUrl();

      else

      $imageUrl = $this->getViewFileUrl('images/cat-img1.jpg'); // Theme/web/images







      share|improve this answer























        Your Answer








        StackExchange.ready(function()
        var channelOptions =
        tags: "".split(" "),
        id: "479"
        ;
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function()
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled)
        StackExchange.using("snippets", function()
        createEditor();
        );

        else
        createEditor();

        );

        function createEditor()
        StackExchange.prepareEditor(
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: false,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: null,
        bindNavPrevention: true,
        postfix: "",
        imageUploader:
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        ,
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        );



        );













        draft saved

        draft discarded


















        StackExchange.ready(
        function ()
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f137057%2fhow-to-get-product-image-and-url-in-magento-2%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown

























        5 Answers
        5






        active

        oldest

        votes








        5 Answers
        5






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        18














        This way may not a best way to get product image.



        Inject MagentoCatalogApiProductRepositoryInterfaceFactory in our constructor.



        protected $_productRepositoryFactory;

        public function __construct(
        MagentoCatalogApiProductRepositoryInterfaceFactory $productRepositoryFactory
        )

        $this->_productRepositoryFactory = $productRepositoryFactory;



        We can get the image:



        $product = $this->_productRepositoryFactory->create()->getById($item->getProductId());
        $product->getData('image');
        $product->getData('thumbnail');
        $product->getData('small_image');





        share|improve this answer

























        • your answer is right but what shoild i do if i have more than one product in cart how can i show more than one product image

          – Ramkishan Suthar
          Sep 20 '16 at 4:17











        • ok i got it @khoa. if i have more than one produc image. thanks alot

          – Ramkishan Suthar
          Sep 20 '16 at 4:22











        • This is not working. Value returned is some kind of string like this "/w/s/wsh10-orange_main.jpg"

          – piavgh
          Oct 17 '16 at 1:37






        • 1





          @piavgh it's the path to image: pub/media/catalog/product

          – Khoa TruongDinh
          Oct 17 '16 at 2:17






        • 1





          so how do i use /w/s/wsh10-orange_main.jpg in <img src="" /> attribute so i can load the actual image

          – Lachezar Raychev
          Nov 8 '17 at 11:06















        18














        This way may not a best way to get product image.



        Inject MagentoCatalogApiProductRepositoryInterfaceFactory in our constructor.



        protected $_productRepositoryFactory;

        public function __construct(
        MagentoCatalogApiProductRepositoryInterfaceFactory $productRepositoryFactory
        )

        $this->_productRepositoryFactory = $productRepositoryFactory;



        We can get the image:



        $product = $this->_productRepositoryFactory->create()->getById($item->getProductId());
        $product->getData('image');
        $product->getData('thumbnail');
        $product->getData('small_image');





        share|improve this answer

























        • your answer is right but what shoild i do if i have more than one product in cart how can i show more than one product image

          – Ramkishan Suthar
          Sep 20 '16 at 4:17











        • ok i got it @khoa. if i have more than one produc image. thanks alot

          – Ramkishan Suthar
          Sep 20 '16 at 4:22











        • This is not working. Value returned is some kind of string like this "/w/s/wsh10-orange_main.jpg"

          – piavgh
          Oct 17 '16 at 1:37






        • 1





          @piavgh it's the path to image: pub/media/catalog/product

          – Khoa TruongDinh
          Oct 17 '16 at 2:17






        • 1





          so how do i use /w/s/wsh10-orange_main.jpg in <img src="" /> attribute so i can load the actual image

          – Lachezar Raychev
          Nov 8 '17 at 11:06













        18












        18








        18







        This way may not a best way to get product image.



        Inject MagentoCatalogApiProductRepositoryInterfaceFactory in our constructor.



        protected $_productRepositoryFactory;

        public function __construct(
        MagentoCatalogApiProductRepositoryInterfaceFactory $productRepositoryFactory
        )

        $this->_productRepositoryFactory = $productRepositoryFactory;



        We can get the image:



        $product = $this->_productRepositoryFactory->create()->getById($item->getProductId());
        $product->getData('image');
        $product->getData('thumbnail');
        $product->getData('small_image');





        share|improve this answer















        This way may not a best way to get product image.



        Inject MagentoCatalogApiProductRepositoryInterfaceFactory in our constructor.



        protected $_productRepositoryFactory;

        public function __construct(
        MagentoCatalogApiProductRepositoryInterfaceFactory $productRepositoryFactory
        )

        $this->_productRepositoryFactory = $productRepositoryFactory;



        We can get the image:



        $product = $this->_productRepositoryFactory->create()->getById($item->getProductId());
        $product->getData('image');
        $product->getData('thumbnail');
        $product->getData('small_image');






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Apr 9 at 1:23

























        answered Sep 19 '16 at 13:04









        Khoa TruongDinhKhoa TruongDinh

        22.2k64187




        22.2k64187












        • your answer is right but what shoild i do if i have more than one product in cart how can i show more than one product image

          – Ramkishan Suthar
          Sep 20 '16 at 4:17











        • ok i got it @khoa. if i have more than one produc image. thanks alot

          – Ramkishan Suthar
          Sep 20 '16 at 4:22











        • This is not working. Value returned is some kind of string like this "/w/s/wsh10-orange_main.jpg"

          – piavgh
          Oct 17 '16 at 1:37






        • 1





          @piavgh it's the path to image: pub/media/catalog/product

          – Khoa TruongDinh
          Oct 17 '16 at 2:17






        • 1





          so how do i use /w/s/wsh10-orange_main.jpg in <img src="" /> attribute so i can load the actual image

          – Lachezar Raychev
          Nov 8 '17 at 11:06

















        • your answer is right but what shoild i do if i have more than one product in cart how can i show more than one product image

          – Ramkishan Suthar
          Sep 20 '16 at 4:17











        • ok i got it @khoa. if i have more than one produc image. thanks alot

          – Ramkishan Suthar
          Sep 20 '16 at 4:22











        • This is not working. Value returned is some kind of string like this "/w/s/wsh10-orange_main.jpg"

          – piavgh
          Oct 17 '16 at 1:37






        • 1





          @piavgh it's the path to image: pub/media/catalog/product

          – Khoa TruongDinh
          Oct 17 '16 at 2:17






        • 1





          so how do i use /w/s/wsh10-orange_main.jpg in <img src="" /> attribute so i can load the actual image

          – Lachezar Raychev
          Nov 8 '17 at 11:06
















        your answer is right but what shoild i do if i have more than one product in cart how can i show more than one product image

        – Ramkishan Suthar
        Sep 20 '16 at 4:17





        your answer is right but what shoild i do if i have more than one product in cart how can i show more than one product image

        – Ramkishan Suthar
        Sep 20 '16 at 4:17













        ok i got it @khoa. if i have more than one produc image. thanks alot

        – Ramkishan Suthar
        Sep 20 '16 at 4:22





        ok i got it @khoa. if i have more than one produc image. thanks alot

        – Ramkishan Suthar
        Sep 20 '16 at 4:22













        This is not working. Value returned is some kind of string like this "/w/s/wsh10-orange_main.jpg"

        – piavgh
        Oct 17 '16 at 1:37





        This is not working. Value returned is some kind of string like this "/w/s/wsh10-orange_main.jpg"

        – piavgh
        Oct 17 '16 at 1:37




        1




        1





        @piavgh it's the path to image: pub/media/catalog/product

        – Khoa TruongDinh
        Oct 17 '16 at 2:17





        @piavgh it's the path to image: pub/media/catalog/product

        – Khoa TruongDinh
        Oct 17 '16 at 2:17




        1




        1





        so how do i use /w/s/wsh10-orange_main.jpg in <img src="" /> attribute so i can load the actual image

        – Lachezar Raychev
        Nov 8 '17 at 11:06





        so how do i use /w/s/wsh10-orange_main.jpg in <img src="" /> attribute so i can load the actual image

        – Lachezar Raychev
        Nov 8 '17 at 11:06













        13














        If you want the published/cache frontend URL of an image for a specific store view (like I did) this is working for me:



        /**
        * @var MagentoStoreModelAppEmulation
        */
        protected $appEmulation;

        /**
        * @var MagentoStoreModelStoreManagerInterface
        */
        protected $storeManager;

        /**
        * @var MagentoCatalogApiProductRepositoryInterfaceFactory
        */
        protected $productRepositoryFactory;

        /**
        * @var MagentoCatalogHelperImageFactory
        */
        protected $imageHelperFactory;

        /**
        * @param MagentoStoreModelStoreManagerInterface $storeManager
        * @param MagentoStoreModelAppEmulation $appEmulation
        * @param MagentoCatalogApiProductRepositoryInterfaceFactory $productRepositoryFactory
        * @param MagentoCatalogHelperImageFactory $helperFactory
        */
        public function __construct(
        MagentoStoreModelStoreManagerInterface $storeManager,
        MagentoStoreModelAppEmulation $appEmulation,
        MagentoCatalogApiProductRepositoryInterfaceFactory $productRepositoryFactory,
        MagentoCatalogHelperImageFactory $imageHelperFactory
        )

        $this->storeManager = $storeManager;
        $this->appEmulation = $appEmulation;
        $this->productRepositoryFactory = $productRepositoryFactory;
        $this->imageHelperFactory = $imageHelperFactory;



        Then, wherever you need to get the image frontend URL:



        $sku = "my-sku";
        // get the store ID from somewhere (maybe a specific store?)
        $storeId = $this->storeManager->getStore()->getId();
        // emulate the frontend environment
        $this->appEmulation->startEnvironmentEmulation($storeId, MagentoFrameworkAppArea::AREA_FRONTEND, true);
        // load the product however you want
        $product = $this->productRepositoryFactory->create()->get($sku);
        // now the image helper will get the correct URL with the frontend environment emulated
        $imageUrl = $this->imageHelperFactory->create()
        ->init($product, 'product_thumbnail_image')->getUrl();
        // end emulation
        $this->appEmulation->stopEnvironmentEmulation();


        You can select other images types besides product_thumbnail_image: see magento/theme-frontend-luma/etc/view.xml for a list of available product images, or create your own in a view.xml file.






        share|improve this answer

























        • WTF? that is just sick :D

          – Lachezar Raychev
          Nov 2 '17 at 9:13











        • Just tried this solution and I'm not getting any errors, though the returned URL doesn't exist and the string is empty. I've tried with 'product_base_image', 'product_small_image' and 'product_thumbnail_image', none of which work. Can you advise please? Or is there an efficient way to do this using the product repository? As I am already loading that elsewhere in my block.

          – Joshua Flood
          Apr 24 '18 at 15:57















        13














        If you want the published/cache frontend URL of an image for a specific store view (like I did) this is working for me:



        /**
        * @var MagentoStoreModelAppEmulation
        */
        protected $appEmulation;

        /**
        * @var MagentoStoreModelStoreManagerInterface
        */
        protected $storeManager;

        /**
        * @var MagentoCatalogApiProductRepositoryInterfaceFactory
        */
        protected $productRepositoryFactory;

        /**
        * @var MagentoCatalogHelperImageFactory
        */
        protected $imageHelperFactory;

        /**
        * @param MagentoStoreModelStoreManagerInterface $storeManager
        * @param MagentoStoreModelAppEmulation $appEmulation
        * @param MagentoCatalogApiProductRepositoryInterfaceFactory $productRepositoryFactory
        * @param MagentoCatalogHelperImageFactory $helperFactory
        */
        public function __construct(
        MagentoStoreModelStoreManagerInterface $storeManager,
        MagentoStoreModelAppEmulation $appEmulation,
        MagentoCatalogApiProductRepositoryInterfaceFactory $productRepositoryFactory,
        MagentoCatalogHelperImageFactory $imageHelperFactory
        )

        $this->storeManager = $storeManager;
        $this->appEmulation = $appEmulation;
        $this->productRepositoryFactory = $productRepositoryFactory;
        $this->imageHelperFactory = $imageHelperFactory;



        Then, wherever you need to get the image frontend URL:



        $sku = "my-sku";
        // get the store ID from somewhere (maybe a specific store?)
        $storeId = $this->storeManager->getStore()->getId();
        // emulate the frontend environment
        $this->appEmulation->startEnvironmentEmulation($storeId, MagentoFrameworkAppArea::AREA_FRONTEND, true);
        // load the product however you want
        $product = $this->productRepositoryFactory->create()->get($sku);
        // now the image helper will get the correct URL with the frontend environment emulated
        $imageUrl = $this->imageHelperFactory->create()
        ->init($product, 'product_thumbnail_image')->getUrl();
        // end emulation
        $this->appEmulation->stopEnvironmentEmulation();


        You can select other images types besides product_thumbnail_image: see magento/theme-frontend-luma/etc/view.xml for a list of available product images, or create your own in a view.xml file.






        share|improve this answer

























        • WTF? that is just sick :D

          – Lachezar Raychev
          Nov 2 '17 at 9:13











        • Just tried this solution and I'm not getting any errors, though the returned URL doesn't exist and the string is empty. I've tried with 'product_base_image', 'product_small_image' and 'product_thumbnail_image', none of which work. Can you advise please? Or is there an efficient way to do this using the product repository? As I am already loading that elsewhere in my block.

          – Joshua Flood
          Apr 24 '18 at 15:57













        13












        13








        13







        If you want the published/cache frontend URL of an image for a specific store view (like I did) this is working for me:



        /**
        * @var MagentoStoreModelAppEmulation
        */
        protected $appEmulation;

        /**
        * @var MagentoStoreModelStoreManagerInterface
        */
        protected $storeManager;

        /**
        * @var MagentoCatalogApiProductRepositoryInterfaceFactory
        */
        protected $productRepositoryFactory;

        /**
        * @var MagentoCatalogHelperImageFactory
        */
        protected $imageHelperFactory;

        /**
        * @param MagentoStoreModelStoreManagerInterface $storeManager
        * @param MagentoStoreModelAppEmulation $appEmulation
        * @param MagentoCatalogApiProductRepositoryInterfaceFactory $productRepositoryFactory
        * @param MagentoCatalogHelperImageFactory $helperFactory
        */
        public function __construct(
        MagentoStoreModelStoreManagerInterface $storeManager,
        MagentoStoreModelAppEmulation $appEmulation,
        MagentoCatalogApiProductRepositoryInterfaceFactory $productRepositoryFactory,
        MagentoCatalogHelperImageFactory $imageHelperFactory
        )

        $this->storeManager = $storeManager;
        $this->appEmulation = $appEmulation;
        $this->productRepositoryFactory = $productRepositoryFactory;
        $this->imageHelperFactory = $imageHelperFactory;



        Then, wherever you need to get the image frontend URL:



        $sku = "my-sku";
        // get the store ID from somewhere (maybe a specific store?)
        $storeId = $this->storeManager->getStore()->getId();
        // emulate the frontend environment
        $this->appEmulation->startEnvironmentEmulation($storeId, MagentoFrameworkAppArea::AREA_FRONTEND, true);
        // load the product however you want
        $product = $this->productRepositoryFactory->create()->get($sku);
        // now the image helper will get the correct URL with the frontend environment emulated
        $imageUrl = $this->imageHelperFactory->create()
        ->init($product, 'product_thumbnail_image')->getUrl();
        // end emulation
        $this->appEmulation->stopEnvironmentEmulation();


        You can select other images types besides product_thumbnail_image: see magento/theme-frontend-luma/etc/view.xml for a list of available product images, or create your own in a view.xml file.






        share|improve this answer















        If you want the published/cache frontend URL of an image for a specific store view (like I did) this is working for me:



        /**
        * @var MagentoStoreModelAppEmulation
        */
        protected $appEmulation;

        /**
        * @var MagentoStoreModelStoreManagerInterface
        */
        protected $storeManager;

        /**
        * @var MagentoCatalogApiProductRepositoryInterfaceFactory
        */
        protected $productRepositoryFactory;

        /**
        * @var MagentoCatalogHelperImageFactory
        */
        protected $imageHelperFactory;

        /**
        * @param MagentoStoreModelStoreManagerInterface $storeManager
        * @param MagentoStoreModelAppEmulation $appEmulation
        * @param MagentoCatalogApiProductRepositoryInterfaceFactory $productRepositoryFactory
        * @param MagentoCatalogHelperImageFactory $helperFactory
        */
        public function __construct(
        MagentoStoreModelStoreManagerInterface $storeManager,
        MagentoStoreModelAppEmulation $appEmulation,
        MagentoCatalogApiProductRepositoryInterfaceFactory $productRepositoryFactory,
        MagentoCatalogHelperImageFactory $imageHelperFactory
        )

        $this->storeManager = $storeManager;
        $this->appEmulation = $appEmulation;
        $this->productRepositoryFactory = $productRepositoryFactory;
        $this->imageHelperFactory = $imageHelperFactory;



        Then, wherever you need to get the image frontend URL:



        $sku = "my-sku";
        // get the store ID from somewhere (maybe a specific store?)
        $storeId = $this->storeManager->getStore()->getId();
        // emulate the frontend environment
        $this->appEmulation->startEnvironmentEmulation($storeId, MagentoFrameworkAppArea::AREA_FRONTEND, true);
        // load the product however you want
        $product = $this->productRepositoryFactory->create()->get($sku);
        // now the image helper will get the correct URL with the frontend environment emulated
        $imageUrl = $this->imageHelperFactory->create()
        ->init($product, 'product_thumbnail_image')->getUrl();
        // end emulation
        $this->appEmulation->stopEnvironmentEmulation();


        You can select other images types besides product_thumbnail_image: see magento/theme-frontend-luma/etc/view.xml for a list of available product images, or create your own in a view.xml file.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Apr 4 '17 at 20:27

























        answered Mar 16 '17 at 21:26









        thaddeusmtthaddeusmt

        933518




        933518












        • WTF? that is just sick :D

          – Lachezar Raychev
          Nov 2 '17 at 9:13











        • Just tried this solution and I'm not getting any errors, though the returned URL doesn't exist and the string is empty. I've tried with 'product_base_image', 'product_small_image' and 'product_thumbnail_image', none of which work. Can you advise please? Or is there an efficient way to do this using the product repository? As I am already loading that elsewhere in my block.

          – Joshua Flood
          Apr 24 '18 at 15:57

















        • WTF? that is just sick :D

          – Lachezar Raychev
          Nov 2 '17 at 9:13











        • Just tried this solution and I'm not getting any errors, though the returned URL doesn't exist and the string is empty. I've tried with 'product_base_image', 'product_small_image' and 'product_thumbnail_image', none of which work. Can you advise please? Or is there an efficient way to do this using the product repository? As I am already loading that elsewhere in my block.

          – Joshua Flood
          Apr 24 '18 at 15:57
















        WTF? that is just sick :D

        – Lachezar Raychev
        Nov 2 '17 at 9:13





        WTF? that is just sick :D

        – Lachezar Raychev
        Nov 2 '17 at 9:13













        Just tried this solution and I'm not getting any errors, though the returned URL doesn't exist and the string is empty. I've tried with 'product_base_image', 'product_small_image' and 'product_thumbnail_image', none of which work. Can you advise please? Or is there an efficient way to do this using the product repository? As I am already loading that elsewhere in my block.

        – Joshua Flood
        Apr 24 '18 at 15:57





        Just tried this solution and I'm not getting any errors, though the returned URL doesn't exist and the string is empty. I've tried with 'product_base_image', 'product_small_image' and 'product_thumbnail_image', none of which work. Can you advise please? Or is there an efficient way to do this using the product repository? As I am already loading that elsewhere in my block.

        – Joshua Flood
        Apr 24 '18 at 15:57











        6














        If you need to return a product URL it should look like this:



        //todo get product object $product 

        $objectManager =MagentoFrameworkAppObjectManager::getInstance();
        $helperImport = $objectManager->get('MagentoCatalogHelperImage');

        $imageUrl = $helperImport->init($product, 'product_page_image_small')
        ->setImageFile($product->getSmallImage()) // image,small_image,thumbnail
        ->resize(380)
        ->getUrl();
        echo $imageUrl;





        share|improve this answer



























          6














          If you need to return a product URL it should look like this:



          //todo get product object $product 

          $objectManager =MagentoFrameworkAppObjectManager::getInstance();
          $helperImport = $objectManager->get('MagentoCatalogHelperImage');

          $imageUrl = $helperImport->init($product, 'product_page_image_small')
          ->setImageFile($product->getSmallImage()) // image,small_image,thumbnail
          ->resize(380)
          ->getUrl();
          echo $imageUrl;





          share|improve this answer

























            6












            6








            6







            If you need to return a product URL it should look like this:



            //todo get product object $product 

            $objectManager =MagentoFrameworkAppObjectManager::getInstance();
            $helperImport = $objectManager->get('MagentoCatalogHelperImage');

            $imageUrl = $helperImport->init($product, 'product_page_image_small')
            ->setImageFile($product->getSmallImage()) // image,small_image,thumbnail
            ->resize(380)
            ->getUrl();
            echo $imageUrl;





            share|improve this answer













            If you need to return a product URL it should look like this:



            //todo get product object $product 

            $objectManager =MagentoFrameworkAppObjectManager::getInstance();
            $helperImport = $objectManager->get('MagentoCatalogHelperImage');

            $imageUrl = $helperImport->init($product, 'product_page_image_small')
            ->setImageFile($product->getSmallImage()) // image,small_image,thumbnail
            ->resize(380)
            ->getUrl();
            echo $imageUrl;






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Apr 3 '18 at 2:47









            Shaoqing MaShaoqing Ma

            6111




            6111





















                5














                That's the way I did. it's quite efficient and clean:



                1) First, you need to inject the following classes:



                protected $_storeManager;
                protected $_appEmulation;
                protected $_blockFactory;

                public function __construct(
                ...
                MagentoStoreModelStoreManagerInterface $storeManager,
                MagentoFrameworkViewElementBlockFactory $blockFactory,
                MagentoStoreModelAppEmulation $appEmulation)

                $this->_storeManager = $storeManager;
                $this->_blockFactory = $blockFactory;
                $this->_appEmulation = $appEmulation;



                2) Then, create a getImageUrl method with the code below:



                protected function getImageUrl($product, string $imageType = '')

                $storeId = $this->_storeManager->getStore()->getId();

                $this->_appEmulation->startEnvironmentEmulation($storeId, MagentoFrameworkAppArea::AREA_FRONTEND, true);

                $imageBlock = $this->_blockFactory->createBlock('MagentoCatalogBlockProductListProduct');
                $productImage = $imageBlock->getImage($product, $imageType);
                $imageUrl = $productImage->getImageUrl();

                $this->_appEmulation->stopEnvironmentEmulation();

                return $imageUrl;



                Note: The "appEmulation" code is only necessary when you making this call from the admin or for an API. Otherwise, you will get the error below (or similar):



                Unable to resolve the source file for 'webapi_rest/_view/en_AU/Magento_Catalog/images/product/placeholder/.jpg'


                3) Call the getImageUrl passing the product object and the type of image you want (based on your view.xml file)



                ...
                $smallImage = $this->getImageUrl($productObject, 'product_page_image_small');
                ...





                share|improve this answer





























                  5














                  That's the way I did. it's quite efficient and clean:



                  1) First, you need to inject the following classes:



                  protected $_storeManager;
                  protected $_appEmulation;
                  protected $_blockFactory;

                  public function __construct(
                  ...
                  MagentoStoreModelStoreManagerInterface $storeManager,
                  MagentoFrameworkViewElementBlockFactory $blockFactory,
                  MagentoStoreModelAppEmulation $appEmulation)

                  $this->_storeManager = $storeManager;
                  $this->_blockFactory = $blockFactory;
                  $this->_appEmulation = $appEmulation;



                  2) Then, create a getImageUrl method with the code below:



                  protected function getImageUrl($product, string $imageType = '')

                  $storeId = $this->_storeManager->getStore()->getId();

                  $this->_appEmulation->startEnvironmentEmulation($storeId, MagentoFrameworkAppArea::AREA_FRONTEND, true);

                  $imageBlock = $this->_blockFactory->createBlock('MagentoCatalogBlockProductListProduct');
                  $productImage = $imageBlock->getImage($product, $imageType);
                  $imageUrl = $productImage->getImageUrl();

                  $this->_appEmulation->stopEnvironmentEmulation();

                  return $imageUrl;



                  Note: The "appEmulation" code is only necessary when you making this call from the admin or for an API. Otherwise, you will get the error below (or similar):



                  Unable to resolve the source file for 'webapi_rest/_view/en_AU/Magento_Catalog/images/product/placeholder/.jpg'


                  3) Call the getImageUrl passing the product object and the type of image you want (based on your view.xml file)



                  ...
                  $smallImage = $this->getImageUrl($productObject, 'product_page_image_small');
                  ...





                  share|improve this answer



























                    5












                    5








                    5







                    That's the way I did. it's quite efficient and clean:



                    1) First, you need to inject the following classes:



                    protected $_storeManager;
                    protected $_appEmulation;
                    protected $_blockFactory;

                    public function __construct(
                    ...
                    MagentoStoreModelStoreManagerInterface $storeManager,
                    MagentoFrameworkViewElementBlockFactory $blockFactory,
                    MagentoStoreModelAppEmulation $appEmulation)

                    $this->_storeManager = $storeManager;
                    $this->_blockFactory = $blockFactory;
                    $this->_appEmulation = $appEmulation;



                    2) Then, create a getImageUrl method with the code below:



                    protected function getImageUrl($product, string $imageType = '')

                    $storeId = $this->_storeManager->getStore()->getId();

                    $this->_appEmulation->startEnvironmentEmulation($storeId, MagentoFrameworkAppArea::AREA_FRONTEND, true);

                    $imageBlock = $this->_blockFactory->createBlock('MagentoCatalogBlockProductListProduct');
                    $productImage = $imageBlock->getImage($product, $imageType);
                    $imageUrl = $productImage->getImageUrl();

                    $this->_appEmulation->stopEnvironmentEmulation();

                    return $imageUrl;



                    Note: The "appEmulation" code is only necessary when you making this call from the admin or for an API. Otherwise, you will get the error below (or similar):



                    Unable to resolve the source file for 'webapi_rest/_view/en_AU/Magento_Catalog/images/product/placeholder/.jpg'


                    3) Call the getImageUrl passing the product object and the type of image you want (based on your view.xml file)



                    ...
                    $smallImage = $this->getImageUrl($productObject, 'product_page_image_small');
                    ...





                    share|improve this answer















                    That's the way I did. it's quite efficient and clean:



                    1) First, you need to inject the following classes:



                    protected $_storeManager;
                    protected $_appEmulation;
                    protected $_blockFactory;

                    public function __construct(
                    ...
                    MagentoStoreModelStoreManagerInterface $storeManager,
                    MagentoFrameworkViewElementBlockFactory $blockFactory,
                    MagentoStoreModelAppEmulation $appEmulation)

                    $this->_storeManager = $storeManager;
                    $this->_blockFactory = $blockFactory;
                    $this->_appEmulation = $appEmulation;



                    2) Then, create a getImageUrl method with the code below:



                    protected function getImageUrl($product, string $imageType = '')

                    $storeId = $this->_storeManager->getStore()->getId();

                    $this->_appEmulation->startEnvironmentEmulation($storeId, MagentoFrameworkAppArea::AREA_FRONTEND, true);

                    $imageBlock = $this->_blockFactory->createBlock('MagentoCatalogBlockProductListProduct');
                    $productImage = $imageBlock->getImage($product, $imageType);
                    $imageUrl = $productImage->getImageUrl();

                    $this->_appEmulation->stopEnvironmentEmulation();

                    return $imageUrl;



                    Note: The "appEmulation" code is only necessary when you making this call from the admin or for an API. Otherwise, you will get the error below (or similar):



                    Unable to resolve the source file for 'webapi_rest/_view/en_AU/Magento_Catalog/images/product/placeholder/.jpg'


                    3) Call the getImageUrl passing the product object and the type of image you want (based on your view.xml file)



                    ...
                    $smallImage = $this->getImageUrl($productObject, 'product_page_image_small');
                    ...






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Apr 18 '18 at 6:31









                    Key Shang

                    1,6961235




                    1,6961235










                    answered Jun 14 '17 at 0:32









                    medinamedina

                    29229




                    29229





















                        0














                        For gettting custom image url I used this code. So if the image does not exits it will load the default theme image.



                        $product = $block->getProduct();

                        $productImageAttr = $product->getCustomAttribute('product_banner_image');

                        if ($productImageAttr && $productImageAttr->getValue() != 'no_selection')

                        $productImage = $this->helper('MagentoCatalogHelperImage')
                        ->init($product, 'product_banner_image')
                        ->setImageFile($productImageAttr->getValue());

                        $imageUrl = $productImage->getUrl();

                        else

                        $imageUrl = $this->getViewFileUrl('images/cat-img1.jpg'); // Theme/web/images







                        share|improve this answer



























                          0














                          For gettting custom image url I used this code. So if the image does not exits it will load the default theme image.



                          $product = $block->getProduct();

                          $productImageAttr = $product->getCustomAttribute('product_banner_image');

                          if ($productImageAttr && $productImageAttr->getValue() != 'no_selection')

                          $productImage = $this->helper('MagentoCatalogHelperImage')
                          ->init($product, 'product_banner_image')
                          ->setImageFile($productImageAttr->getValue());

                          $imageUrl = $productImage->getUrl();

                          else

                          $imageUrl = $this->getViewFileUrl('images/cat-img1.jpg'); // Theme/web/images







                          share|improve this answer

























                            0












                            0








                            0







                            For gettting custom image url I used this code. So if the image does not exits it will load the default theme image.



                            $product = $block->getProduct();

                            $productImageAttr = $product->getCustomAttribute('product_banner_image');

                            if ($productImageAttr && $productImageAttr->getValue() != 'no_selection')

                            $productImage = $this->helper('MagentoCatalogHelperImage')
                            ->init($product, 'product_banner_image')
                            ->setImageFile($productImageAttr->getValue());

                            $imageUrl = $productImage->getUrl();

                            else

                            $imageUrl = $this->getViewFileUrl('images/cat-img1.jpg'); // Theme/web/images







                            share|improve this answer













                            For gettting custom image url I used this code. So if the image does not exits it will load the default theme image.



                            $product = $block->getProduct();

                            $productImageAttr = $product->getCustomAttribute('product_banner_image');

                            if ($productImageAttr && $productImageAttr->getValue() != 'no_selection')

                            $productImage = $this->helper('MagentoCatalogHelperImage')
                            ->init($product, 'product_banner_image')
                            ->setImageFile($productImageAttr->getValue());

                            $imageUrl = $productImage->getUrl();

                            else

                            $imageUrl = $this->getViewFileUrl('images/cat-img1.jpg'); // Theme/web/images








                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 20 '18 at 10:05









                            Amit SinghAmit Singh

                            906930




                            906930



























                                draft saved

                                draft discarded
















































                                Thanks for contributing an answer to Magento Stack Exchange!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid


                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.

                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function ()
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f137057%2fhow-to-get-product-image-and-url-in-magento-2%23new-answer', 'question_page');

                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Sum ergo cogito? 1 nng

                                419 nièngy_Soadمي 19bal1.5o_g

                                Queiggey Chernihivv 9NnOo i Zw X QqKk LpB