Magento – Magento2 : Additional images import programmatically

importmagento-2.1magento2

I'm trying to add additional images in products using custom script and below code i'm using. I have put product images in "additional_images" column of my csv and $image_directory is my path where product images put.

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


        $addimages = $data["additional_images"]; 

$addimagesData = explode(',',$addimages);
 foreach($addimagesData as $addimages_img){
 $image_directory = '/var/www/html/myproject/pub/media/import/'.$addimages_img;
 $product->addImageToMediaGallery($image_directory, null, false, false);//assigning image, thumb and small image to media gallery      
}

After run my script i'm getting below error. I have also set all permission for folder and images. Any help should be appreciated.

[Magento\Framework\Exception\FileSystemException]
The file "/var/www/html/myproject/pub/media/tmp/catalog/product/p/o/powerhub-back.jpg" doe
sn't exist or not a file

Best Answer

I also got the same error when I was trying to import the main image and additional images together.So I import the main image and the added the additional images using the following code.

 $imgs = explode('|',$prodData[10]);

        if(sizeof($imgs) > 1) {

            $product = $_objectManager->create('Magento\Catalog\Model\Product')->load($newProdId);
            $productRepository = $_objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');
            $productRepository->save($product);

            for ( $i=1; $i<sizeof($imgs); $i++ ) {

                echo 'Add Images :' . $prdbasepath.basename(trim($imgs[$i])) . PHP_EOL;
                $image_directory = $prdbasepath.'data'.DS.basename(trim($imgs[$i]));


                if (file_exists($image_directory) && getimagesize($image_directory)) {

                    echo 'File exists'.PHP_EOL;
                    $product->addImageToMediaGallery($image_directory, array('image', 'small_image', 'thumbnail'), false, false);
                    $product->save();

                }
            }

        }
Related Topic