Magento – Magento 2: Where are Gallery Images Processed in an Admin Save

imagemagento2productupload

In Magento 2, if you navigate to

 Products->Catalog->Edit->Images and Videos

you can add images to your products. The uploader will upload a temp image immediately, and after a product save there will be appropriately sized images in pub/media/catalog/product/cache.

Where is the code that handles saving the product gallery image data to the database, and where is the code that handles creating the new media image files on disk? The product save controller

#File: vendor/magento/module-catalog/Controller/Adminhtml/Product/Save.php
public function execute()
{
    //...
    $product = $this->initializationHelper->initialize(
        $this->productBuilder->build($this->getRequest())
    );
    $this->productTypeManager->processProduct($product);

    if (isset($data['product'][$product->getIdFieldName()])) {
        throw new \Magento\Framework\Exception\LocalizedException(__('Unable to save product'));
    }

    $originalSku = $product->getSku();
    $product->save();
    //...
}

Doesn't contain anything obvious about image saving, so the code is probably somewhere down the initializationHelper, productBuilder, productTypeManager, or save call stacks. I'm hoping someone here knows where this data gets saved in Magento 2.

Best Answer

Take a look: vendor/magento/module-catalog/Model/Product.php

public function afterSave()
{
        ......
        // Resize images for catalog product and save results to image cache
        /** @var Product\Image\Cache $imageCache */
        if (!$this->_appState->isAreaCodeEmulated()) {
            $imageCache = $this->imageCacheFactory->create();
            $imageCache->generate($this);
        }
        ......
}

As we can see, the process image is in afterSave() method.
There are some classes handle the process image:

vendor/magento/module-catalog/Model/Product/Image.php
vendor/magento/module-catalog/Helper/Image.php

Related Topic