Cookies setting

Cookies help us enhance your experience on our site by storing information about your preferences and interactions. You can customize your cookie settings by choosing which cookies to allow. Please note that disabling certain cookies might impact the functionality and features of our services, such as personalized content and suggestions. Cookie Policy

Cookie Policy
Essential cookies

These cookies are strictly necessary for the site to work and may not be disabled.

Information
Always enabled
Advertising cookies

Advertising cookies deliver ads relevant to your interests, limit ad frequency, and measure ad effectiveness.

Information
Analytics cookies

Analytics cookies collect information and report website usage statistics without personally identifying individual visitors to Google.

Information
mageplaza.com

Latest Guide on How to Add Images To Product in Magento 2

Vinh Jacker | 12-18-2024

Latest Guide on How to Add Images To Product in Magento 2

In today’s e-commerce landscape, visuals are everything. The first thing that grabs the attention of a potential buyer is the product image. On Magento 2, an industry-leading platform, adding product images is an essential part of setting up your store. Not only do images help in showcasing the products better, but they also play a vital role in conversion rates.

In this guide, we will walk you through how to add images to a product in Magento 2, which ensures your product catalog shines with high-quality visuals. Ready to get started? Let’s dive in.

How to Add Images to the Product in Magento 2

In this article, I will show you two method to add/ remove images to the product programmatically:

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

Firstly, I will 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 been tested 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 base, small_image and thumbnail.

The code comments need to meet a few below requirements:

  • The document root of the Magento 2 application must be set to ROOT/pub.
  • The directory containing the images needs to be placed within ROOT/pub/media.
  • 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 images from a product by using the 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();


Magento 2 extensions

Magento 2 extensions

Allow you to achieve more with your online store

Check it out!


Conclusion

To sum up, adding images to products in Magento 2 is a straightforward process that greatly enhances the visual appeal and user experience of your online store. By following the steps outlined in this guide, you can ensure that your product pages are engaging and informative. Remember to optimize your images for fast loading times and search engine rankings. By doing so, you’ll not only improve your store’s performance but also increase customer satisfaction and conversion rates.

Related Post

x
    Jacker

    With over a decade of experience crafting innovative tech solutions for ecommerce businesses built on Magento, Jacker is the mastermind behind our secure and well-functioned extensions. With his expertise in building user-friendly interfaces and robust back-end systems, Mageplaza was able to deliver exceptional Magento solutions and services for over 122K+ customers around the world.



    Related Post

    Website Support
    & Maintenance Services

    Make sure your store is not only in good shape but also thriving with a professional team yet at an affordable price.

    Get Started
    mageplaza services