How to get product image and url in Magento 2How 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?

What do the Banks children have against barley water?

Why is the design of haulage companies so “special”?

Is ipsum/ipsa/ipse a third person pronoun, or can it serve other functions?

I’m planning on buying a laser printer but concerned about the life cycle of toner in the machine

How would photo IDs work for shapeshifters?

Crop image to path created in TikZ?

I see my dog run

Does a dangling wire really electrocute me if I'm standing in water?

Why was the "bread communication" in the arena of Catching Fire left out in the movie?

Can the Produce Flame cantrip be used to grapple, or as an unarmed strike, in the right circumstances?

Email Account under attack (really) - anything I can do?

Is this food a bread or a loaf?

Ideas for 3rd eye abilities

What causes the sudden spool-up sound from an F-16 when enabling afterburner?

What do you call something that goes against the spirit of the law, but is legal when interpreting the law to the letter?

How can I add custom success page

Why do we use polarized capacitors?

Calculate Levenshtein distance between two strings in Python

Can I legally use front facing blue light in the UK?

Are white and non-white police officers equally likely to kill black suspects?

Lied on resume at previous job

Was there ever an axiom rendered a theorem?

Does the average primeness of natural numbers tend to zero?

What are the advantages and disadvantages of running one shots compared to campaigns?



How to get product image and url in Magento 2


How 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;








13















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

















13















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













13












13








13


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,28721435




2,28721435












  • 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


















17














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









        17














        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















        17














        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













        17












        17








        17







        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 1 hour ago

























        answered Sep 19 '16 at 13:04









        Khoa TruongDinhKhoa TruongDinh

        22.1k64187




        22.1k64187












        • 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,6911135




                    1,6911135










                    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

                                Magento 2 duplicate PHPSESSID cookie when using session_start() in custom php scriptMagento 2: User cant logged in into to account page, no error showing!Magento duplicate on subdomainGrabbing storeview from cookie (after using language selector)How do I run php custom script on magento2Magento 2: Include PHP script in headerSession lock after using Cm_RedisSessionscript php to update stockMagento set cookie popupMagento 2 session id cookie - where to find it?How to import Configurable product from csv with custom attributes using php scriptMagento 2 run custom PHP script

                                Can not update quote_id field of “quote_item” table magento 2Magento 2.1 - We can't remove the item. (Shopping Cart doesnt allow us to remove items before becomes empty)Add value for custom quote item attribute using REST apiREST API endpoint v1/carts/cartId/items always returns error messageCorrect way to save entries to databaseHow to remove all associated quote objects of a customer completelyMagento 2 - Save value from custom input field to quote_itemGet quote_item data using quote id and product id filter in Magento 2How to set additional data to quote_item table from controller in Magento 2?What is the purpose of additional_data column in quote_item table in magento2Set Custom Price to Quote item magento2 from controller

                                How to solve knockout JS error in Magento 2 Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?(Magento2) knockout.js:3012 Uncaught ReferenceError: Unable to process bindingUnable to process binding Knockout.js magento 2Cannot read property `scopeLabel` of undefined on Product Detail PageCan't get Customer Data on frontend in Magento 2Magento2 Order Summary - unable to process bindingKO templates are not loading in Magento 2.1 applicationgetting knockout js error magento 2Product grid not load -— Unable to process binding Knockout.js magento 2Product form not loaded in magento2Uncaught ReferenceError: Unable to process binding “if: function()return (isShowLegend()) ” magento 2