Programmatically add multiple images to a single product in magento -
the product id given multiple images need added in magento.
$count = 0; $imgarray = array($fpath.'configurable.png'); foreach ($imgarray $image){ $imgurl = _save_image( $image,$objectmanager ); if ($count == 0){ $configproduct->addimagetomediagallery( $imgurl , $mediaattribute, true, false ); }else { $configproduct->addimagetomediagallery( $imgurl , null, true, false ); } $count++; }
$objectmanager = \magento\framework\app\objectmanager::getinstance(); $product = $objectmanager->create('magento\catalog\model\product')->load($productid); // load product object $mediaattribute = array ('thumbnail','small_image','image'); $mediadir = $objectmanager->get('magento\framework\app\filesystem\directorylist')->getpath('media');// im magento 2 $mediadir = mage::getbasedir('media');// in magento 1 //case 1: when image files alredy in server $fpath = 'product/images/';// path file $count = 0; $imgarray = array('image1.png','image2.png','image3.png','image4.png'); foreach ($imgarray $image){ $imgurl = _save_image( $fpath.$image,$objectmanager,$mediadir );// copies file local storage your-magento-root-path/pub/media if ($count == 0){ $product->addimagetomediagallery( $imgurl , $mediaattribute, true, false ); }else { $product->addimagetomediagallery( $imgurl , null, true, false ); } $count++; } function _save_image($img,$objectmanager,$mediadir) { $imagefilename = basename($img); $image_type = substr(strrchr($imagefilename,"."),1); //find image extension $filename = md5($img . strtotime('now')).'.'.$image_type; //give new name, can modify per requirement if (!file_exists($mediadir)) mkdir($mediadir, 0777, true); else chmod($mediadir, 0777); $filepath = $mediadir . '/'. $filename; //path temp storage folder: pub/media file_put_contents($filepath, file_get_contents(trim($img))); //store image external url temp storage folder return $filepath; } //case 2: when have browse images form. (then save server , ) if(!empty($imagefile)){ $count = 0; if (!file_exists($mediadir)) mkdir($mediadir, 0777, true); else chmod($mediadir, 0777); foreach($imagefile['name'] $k2=>$v2){ if($imagefile['error'][$k2] == 0 && file_exists($imagefile['tmp_name'][$k2])){ $ext[$k2] = pathinfo($imagefile['name'][$k2], pathinfo_extension); $filename[$k2] = md5(strtotime('now')).'.'.$ext[$k2]; $filepath[$k2] = $mediadir .'/'. $filename[$k2]; $bin_string[$k2] = file_get_contents($imagefile['tmp_name'][$k2]); file_put_contents($filepath[$k2], $bin_string[$k2]); if ($count == 0) : $product[$k]->addimagetomediagallery( $filepath[$k2] , $mediaattribute, true, false ); else : $product[$k]->addimagetomediagallery( $filepath[$k2] , null, true, false ); endif; $count++; } } }
Comments
Post a Comment