Set default , additional images magento programmatically

This tutorial explains how to set default and additional images in magento backend programmatically.

Please also refer the tutorial that explains how to download an image from an external url to magento folder .

 
        if ($import_product[35]) {
            $images_collection = explode(" | ", $import_product[35]);

            $file_name = @array_pop(explode('/', $images_collection[0]));
            $image_directory = $dir.DS.'data'.DS. $file_name;


            if (!file_exists($image_directory)){
                downloadFile($images_collection[0], $image_directory);
            }

            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
            }

            if (count($images_collection) > 1){
                foreach ($images_collection as $image) {
                    $image = explode('/', $image);
                    $file_name = array_pop($image);
                    $image_directory = $dir.DS.'data'.DS. $file_name;
                    if (!file_exists($image_directory)){
                        downloadFile($image, $image_directory);
                    }
                    if (file_exists($image_directory)) {
                        $product->addImageToMediaGallery($image_directory, null, false, false);
                    }
                }
                echo 'Additional images for product ' . $product->getName() . ' ' . $product->getId() . ' imported successfully' . PHP_EOL;
            }

        }

Share this Tutorial