Bobcares

Add Images To Product Programmatically in magento 2

by | Jan 10, 2023

Wondering how to add Images To Product Programmatically in magento 2? Our in-house experts are here to help you out with this article. Our magento support is here to offer a lending hand with your queries and issues.

Add Images To Product Programmatically in magento 2

Product images play an essential role in building an eye-catching whole product page, which attracts customers in the first place.

As a highly flexible and customizable platform, Magento allows adding or removing images from products in different ways.

You can save a lot of time without having to add images manually.

Today, let us see two methods explained by our support techs to add images.

Method 1: Add Or Remove Media Images Programmatically By Using The Magento_Catalog Module Classes

Firstly, describe the process of adding and removing images programmatically in Magento 2 by using Magento_Catalog module.

A one-off script is required to run it.

Hence, the code displayed will reside in a single file which externally bootstraps the Magento 2 application.

The code below has test as of Magento Open Source version 2.2.5 and will delete all existing gallery images from a product, then add a single image, assigning the image to the basesmall_image and thumbnail.

The code comments need to meet a few below requirements:

  • The document root of the Magento 2 application must set to ROOT/pub.
  • Next, the directory containing the images need to place within ROOT/pub/media.
  • Then, the images are named identical to the SKU of the product which images should be updated.
  • Make sure that [image_dir] is replaced by the name of the directory which contains the images.

Add a file within the ROOT/pub directory containing the code below and run the code either within the browser or via CLI. You can change various aspects of the file (such as the glob’d image file types) to meet your needs.

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
 
/*
 * Assumes doc root is set to ROOT/pub
 */
require_once dirname(__DIR__) . '/app/bootstrap.php';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
 
class AssignImages extends \Magento\Framework\App\Http implements \Magento\Framework\AppInterface
{
    public function launch()
    {
        $state = $this->_objectManager->get('Magento\Framework\App\State');
        $state->setAreaCode('adminhtml');
 
        $galleryReadHandler = $this->_objectManager->create('Magento\Catalog\Model\Product\Gallery\ReadHandler');
        $imageProcessor = $this->_objectManager->create('Magento\Catalog\Model\Product\Gallery\Processor');
        $productGallery = $this->_objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Gallery');
 
        /**
         * Assumed images are named [sku].[ext] and reside in ROOT/pub/media/[image_dir]
         */
        foreach (glob(__DIR__ . "/media/[image_dir]/*.{jpg,png,gif}", GLOB_BRACE) as $image) {
            $imageFileName = trim(pathinfo($image)['filename']);
            $sku = $imageFileName;
            try {
                $product = $this->_objectManager->create('Magento\Catalog\Model\Product')->loadByAttribute('sku', $sku);
                if ($product) {
                    $galleryReadHandler->execute($product);
 
                    // Unset existing images
                    $images = $product->getMediaGalleryImages();
                    foreach($images as $child) {
                        $productGallery->deleteGallery($child->getValueId());
                        $imageProcessor->removeImage($product, $child->getFile());
                    }
 
                    /**
                     * Add image. Image directory must be in ROOT/pub/media for addImageToMediaGallery() method to work
                     */
                    $product->addImageToMediaGallery('[image_dir]' . DIRECTORY_SEPARATOR . pathinfo($image)['basename'], array('image', 'small_image', 'thumbnail'), false, false);
                    $product->save();
                    echo "Added media image for {$sku}" . "\n";
                }
            } catch (\Exception $e) {
                echo $e->getMessage();
            }
        }
        return $this->_response;
    }
 
    public function catchException(\Magento\Framework\App\Bootstrap $bootstrap, \Exception $exception)
    {
        echo $exception->getMessage();
        return false;
    }
}
 
/** @var \Magento\Framework\App\Http $app */
$app = $bootstrap->createApplication('AssignImages');
$bootstrap->run($app);

Method 2: Add Or Remove Media Images Programmatically By Using Object Manager

Now, I will show you the second method to add or remove image from a product by using object manager

// Instance of object manager
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
//Remove Images From Product
$productId =  1 ; // Id of product
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($productId);
$productRepository = $objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');
$existingMediaGalleryEntries = $product->getMediaGalleryEntries();
foreach ($existingMediaGalleryEntries as $key => $entry) {
    unset($existingMediaGalleryEntries[$key]);
}
$product->setMediaGalleryEntries($existingMediaGalleryEntries);
$productRepository->save($product);
/*Add Images To The Product*/
$imagePath = "sample.png"; // path of the image
$product->addImageToMediaGallery($imagePath, array('image', 'small_image', 'thumbnail'), false, false);
$product->save();

[Looking for a solution to another query? We’re happy to help.]

Conclusion

In this article, we provide a quick and simple solution from our Support team to add Images To Product Programmatically in magento 2

 

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

Never again lose customers to poor
server speed! Let us help you.

Privacy Preference Center

Necessary

Necessary cookies help make a website usable by enabling basic functions like page navigation and access to secure areas of the website. The website cannot function properly without these cookies.

PHPSESSID - Preserves user session state across page requests.

gdpr[consent_types] - Used to store user consents.

gdpr[allowed_cookies] - Used to store user allowed cookies.

PHPSESSID, gdpr[consent_types], gdpr[allowed_cookies]
PHPSESSID
WHMCSpKDlPzh2chML

Statistics

Statistic cookies help website owners to understand how visitors interact with websites by collecting and reporting information anonymously.

_ga - Preserves user session state across page requests.

_gat - Used by Google Analytics to throttle request rate

_gid - Registers a unique ID that is used to generate statistical data on how you use the website.

smartlookCookie - Used to collect user device and location information of the site visitors to improve the websites User Experience.

_ga, _gat, _gid
_ga, _gat, _gid
smartlookCookie
_clck, _clsk, CLID, ANONCHK, MR, MUID, SM

Marketing

Marketing cookies are used to track visitors across websites. The intention is to display ads that are relevant and engaging for the individual user and thereby more valuable for publishers and third party advertisers.

IDE - Used by Google DoubleClick to register and report the website user's actions after viewing or clicking one of the advertiser's ads with the purpose of measuring the efficacy of an ad and to present targeted ads to the user.

test_cookie - Used to check if the user's browser supports cookies.

1P_JAR - Google cookie. These cookies are used to collect website statistics and track conversion rates.

NID - Registers a unique ID that identifies a returning user's device. The ID is used for serving ads that are most relevant to the user.

DV - Google ad personalisation

_reb2bgeo - The visitor's geographical location

_reb2bloaded - Whether or not the script loaded for the visitor

_reb2bref - The referring URL for the visit

_reb2bsessionID - The visitor's RB2B session ID

_reb2buid - The visitor's RB2B user ID

IDE, test_cookie, 1P_JAR, NID, DV, NID
IDE, test_cookie
1P_JAR, NID, DV
NID
hblid
_reb2bgeo, _reb2bloaded, _reb2bref, _reb2bsessionID, _reb2buid

Security

These are essential site cookies, used by the google reCAPTCHA. These cookies use an unique identifier to verify if a visitor is human or a bot.

SID, APISID, HSID, NID, PREF
SID, APISID, HSID, NID, PREF