Magento – Magento 2 : set product image programatically

magento2productproduct-images

I want to upload a product along with product image, please suggest how to set path or upload image for a product.
here is my code

 try{
                $_product->setName($product["name"]);
                $_product->setTypeId('simple');
                $_product->setAttributeSetId(4);
                $_product->setSku($product["sku"]);
                $_product->setWebsiteIds(array(1));
                $_product->setVisibility(4);
                $_product->setDescription($product["description"]);
                $_product->setPrice($product["price"]);

                $tmpDir = $this->getMediaDirTmpDir();
                $this->file->checkAndCreateFolder($tmpDir);
                $newFileName = $tmpDir . baseName($imageUrl);
                $result = $this->file->read($imageUrl, $newFileName);
                 if ($result) {
                /** add saved file to the $product gallery */
                $_product->setMediaGallery(array('images'=>array (),'values'=>array ())); 
                $_product->addImageToMediaGallery(how to set path, what to do,array('image', 'small_image', 'thumbnail'), true, $visible);
                }

         'manage_stock' => 1, //manage stock
   'min_sale_qty' => 1, //Minimum Qty Allowed in Shopping Cart
                        'max_sale_qty' => 2, //Maximum Qty Allowed in Shopping Cart
                        'is_in_stock' => $product['stockstatus'], //Stock Availability
                        'qty' =>  $product['quantity']
                        )
                    );
                $_product->save();

            }                             
            catch(\Exception $e) { 
                 echo $e->getMessage();
            }

Best Answer

Simply add this code after product price (No need another code for upload image)

 $imagePath = "D:\image\sample.jpg"; // path of the image
 $_product->addImageToMediaGallery($imagePath, array('image', 'small_image', 'thumbnail'), true, false);
 $_product->save();