Import product images magento 2

This tutorial explains how to import product images magento 2.The following code shows how to set the media folder absolute path and import product images programmatically and set main image and additional image as shown in the figure below.

Please click here to get the detailed explanation of how initialise the import script, read data from CSV and import products programmatically.

Step by step explanation

  • Get media folder absolute path
  • Import product images magento 2

Media folder absolute path

Copy the images in the media folder. This example I am creating a data folder inside media folder. Inside the import products script as the first step we need to get the media folder absolute path.

import product images magento 2

Import product images magento 2

The following code get the absolute path and get the main and additional image from the folder and set those programmatically.

import-product-image-magento-2

Please click here to refer other magento tutorials.

// Absolute path

    $filesystem = $objectManager->create('Magento\Framework\Filesystem');
    $mediaDirectory = $filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
    $mediaPath = $mediaDirectory->getAbsolutePath();
    

 $mainImage = $importProduct[9];
// Main Image
    if ($mainImage) {
        $image_directory = $mediaPath . DS . 'data' . DS . $mainImage;
        if (file_exists($image_directory)) {
            $product->setMediaGallery(array('images' => array(), 'values' => array()))//media gallery initialization
                ->addImageToMediaGallery($image_directory, array('image', 'thumbnail', 'small_image'), false, false);//assigning image, thumb and small image to media gallery
        } 
        else {
            $image_directory = $mediaPath . 'data' . DS . 'comingsoon.jpg';
            $product->setMediaGallery(array('images' => array(), 'values' => array()))//media gallery initialization
                ->addImageToMediaGallery($image_directory, array('image', 'thumbnail', 'small_image'), false, false);
        }
    }

    // additional images
    if ($importProduct[29] != '') {
        $addImages = explode(",", trim($importProduct[29]));
        foreach ($addImages as $additional_image) {
            $image_directory = $mediaPath .DS.'data'.DS. trim($additional_image);
            if (file_exists($image_directory)) {
                $product->addImageToMediaGallery($image_directory, null, false, false);
            } 
            else {
                $image_directory = $mediaPath . 'data' . DS . 'comingsoon.jpg';
                $product->addImageToMediaGallery($image_directory, null, false, false);
            }
        }
        echo 'Additional images for product ' . $product->getName() . ' ' . $product->getId() . ' imported successfully' . PHP_EOL;
    }

Share this Tutorial