Magento 2 Add Image to Product Programmatically

How To Programmatically Add Image To Product In Magento 2

by Trang Tran

Product image is an indispensable part of selling online. E-commerce businesses that sell items like clothing require multiple product images so that the client can see the item from all sides.

However, by default Magento 2, you must manually add each product’s photos. This is a lengthy procedure that requires a lot of time. Instead, Magento 2 allows you to bulk-upload pictures to the product gallery using a CSV file.

Let’s learn how to add images to products programmatically in Magento 2 now!

How Do Product Images Impact Your Customer Journey?

E-commerce store owners typically use product images to display and visually introduce their products. More than that, do you know that it can change customer mindset by just an attractive image?
There are 2 main numbers you should focus on first before we show you the importance of product images in eCommerce websites:

  • 87.6% of respondents considered the product image as the key element of the shopping experience
  • 75% of online shoppers rely on product photos when deciding on a potential purchase

Indeed, product images are crucial for Magento 2 stores because they influence the customer’s perception. An image improves the product description, making it more enticing to your website visitors. When buying online, customers have difficulty feeling the product. Thus they use an image instead. 

Various products are featured in an online store; the products vary by category, style, color, material, design, and so on. The customer’s eyes will appeal to the image and click there to get a better view. By zooming in on the product photographs, customers can better understand how well it will suit their needs. 

magento 2 product image

Therefore, you must always ensure that the buyer views at least four to five angles. Otherwise, if you upload poor-quality images, you risk losing them.

Generally, an image is a crucial element that shapes your customer’s perception in today’s visually oriented world.

How To Magento 2 Add Image To Product Programmatically 

You can use the default Magento 2 to add images to the product. However, if you have an extensive catalog, it can be time-consuming. Hence, we recommend the programmatical method. 

Instead of adding images to each product, using this method can save time and effort. You simply need to consider one disadvantage of having coding experience. 

So let’s dig into the guide now!

To Magento 2 add image to product programmatically, you only have to place the following PHP code in a new file in the ROOT directory:

// Instance of object manager
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
/*Add Images To The Product*/
$imagePath = "sample.png"; // path of the image
$product->addImageToMediaGallery($imagePath, array('image', 'small_image', 'thumbnail'), false, false);
$product->save();

Additional information for removing product images, you add the below code:

$productId =  1 ; // Id of product
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($productId);
$productRepository = $objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');
$existingMediaGalleryEntries = $product->getMediaGalleryEntries();
foreach ($existingMediaGalleryEntries as $key => $entry) {
    unset($existingMediaGalleryEntries[$key]);
}
$product->setMediaGalleryEntries($existingMediaGalleryEntries);
$productRepository->save($product);

Tips To Optimize Magento 2 Product Image

After successfully adding image to product programmatically in Magento 2 

Reduce the file size of your images

Page loading speed is crucial for SEO performance. According to Google, users love fast sites, which raises the web standard (especially for those users with slow Internet connections). Google advises that you evaluate the functionality of your page using programs like PageSpeed Insights and Webpagetest.org.

Significantly, Magento 2 store owners can reduce most images by enabling the “Frontend Resizes” feature. But if you have to accelerate your page, even more, think about optimizing your Magento 2 image sizes.

magento-2-add-image-to-product-programmatically

Lossy or lossless compression are the two methods for shrinking an image.

It would help if you reduced file sizes as much as possible. You can allow users to view the images in a larger pop-up window or on another page because quality images are essential to generating online sales. Avoid uploading a large image file to your website and using HTML code to reduce its size because this can lengthen load times. File sizes must not exceed 70KB.

You might also use lazy loading images to increase your page speed faster for your users.

Change the file format 

File sizes can be kept smaller by using the appropriate file types. For e-commerce sites, there are many image formats to choose from, such as JPEG, GIF, PNG, and WebP. 

In recent years, WebP has been the most popular file type since it allows for higher quality while maintaining a reduced file size. So why has this format become favorable?

There are 3 notable advantages of converting product images to WebP format:

  • Quick loading times: WebP images have smaller file sizes than any other image formats, so they load more quickly. 
  • Lessening of online storage requirements due to WebP’s improved compression. High-image-volume Magento 2 sites can’t ignore WebP, which might even help you save money on web hosting.
  • WebP is the only image format that allows transparent backgrounds for PNG files and animation features for GIF files, and it also outperforms JPEG’s compression. 

Fortunately, instead of manually converting using limited tools, the Magento 2 WebP Image Support module can automatically switch photos in the JPG, PNG, and JPEG formats to WebP to improve your website’s loading and display times.

Magento 2 webp images extension - BSS Commerce

Furthermore, you also define all or specific pages where you want to change the image format. There are 4 main page types you can configure:

  • Product Page
  • Category Page
  • Home Page
  • CMS Page

When you get Magento 2 Convert Images to WebP, you also experience the best customer policy with Free 1-Year Support, Free Lifetime Update, Free Installation, and 30-Day Money Back. 

>>> Read this article to install this module to your Magento 2 store: Install Extension Magento 2 Clearly: A Step-by-Step Guide

Provide an image sitemap

If you want to improve SEO performance, this action is a key that gives the search engine additional information when crawling a website. 

An image sitemap helps direct search engines to images that would be challenging to find. In Magento 2 add image to product programmatically process, you can add images to an existing sitemap or a new one made for them.

Write Alt text

magento-2-add-image-to-product-programmatically

Alt-text is the game-changer regarding SEO and making your image stand out when a potential customer hits the Google search box.

When the image cannot be displayed on the website, alt text is offered as a substitute. The alt text also describes for search engines comprehend the image. At least one keyword should be included in the alt text, but be careful not to overdo it. Use only terms pertinent to the image’s content; otherwise, search engines may penalize you.

Additionally, we also provide Magento SEO best practices to bring your website to the top of search engine results page

Use words that describe the image accurately to name image files

You can save the image file with a name before adding an image to the product programmatically in Magento 2. 

Use phrases that clearly and accurately describe the image when naming image files. It would be best if you used “red-running shoes” in place of “Image01”. Search engines can identify the image’s subject based on its file name. When naming the image file, it would be better to use a term you want to rank for.

On the other hand, refrain from loading your files with keywords and giving them big file names since this could hurt your rating. Instead of using underscores, which blend words instead of separating them, use dashes to divide words. Also, avoid using articles like “the,” “a,” and other similar words that don’t add keyword value.

Conclusion

That’s the end of this guide. Hopefully, you can easily add images to the product programmatically to your Magento 2 website.

In addition, don’t forget to optimize product images to influence the customer’s perception and improve search engine rankings. For more tips, please refer to this Magento 2 image optimization guide!

BSS Commerce is the top class Multi-platform eCommerce solution provider and Magento 2 development company in the world. With experienced and certified developers, we commit to bringing high-quality products and services to optimize your business effectively.

Next Reading Suggestions

© 2019 BSS Commerce owned by THANH CONG INTER ., JSC. All Rights Reserved.
Business registration certificate no. 0106064469 issued by Hanoi Department of Planning and Investment on 19 December 2019.
Legal Representative: Mr. Nguyen Quang Trung.