Magento2 – Resize images for only one product.

Fixing bug in production. I strongly don’t recommend it. But sometimes we have to do it.

Friday, 22 Oct, 2021. I had an urgent bug need to be fixed on the production. The issue is images of one product don’t show on a frontend due to their cache files were not generated. A website has a lot of products and images associate, so if I would used the command “bin/magento catalog:image:resize”, It would have taken an age to finish.

I just wanted to resize images for only one product, not for all of them. But Magento does not help. So I have to adjust it.

Here is a quick solution, but we need to fix a core file (I strongly don’t recommend it).

  • To fix a core file Magento\Catalog\Model\ResourceModel\Product\Image, see below.
  • Run a command “bin/magento catalog:image:resize”.
  • It worked!
  • Then Finally, I rolled the file back to its original version. (must).

Certainly, I will note it and implement a new command line to resize images for a specific product. I will update its status here.

https://github.com/trunglv/mage2_dev

File:

Magento\Catalog\Model\ResourceModel\Product\Image

Original version

private function getUsedImagesSelect(): Select
    {
        return $this->connection->select()->distinct()
            ->from(
                ['images' => $this->resourceConnection->getTableName(Gallery::GALLERY_TABLE)],
                'value as filepath'
            )->joinInner(
                ['image_value' => $this->resourceConnection->getTableName(Gallery::GALLERY_VALUE_TABLE)],
                'images.value_id = image_value.value_id',
                []
            )->where(
                'images.disabled = 0 AND image_value.disabled = 0'
            );
    }

Customized version – Add a condition image_value.entity_id = [product_id]

private function getUsedImagesSelect(): Select
    {
        return $this->connection->select()->distinct()
            ->from(
                ['images' => $this->resourceConnection->getTableName(Gallery::GALLERY_TABLE)],
                'value as filepath'
            )->joinInner(
                ['image_value' => $this->resourceConnection->getTableName(Gallery::GALLERY_VALUE_TABLE)],
                'images.value_id = image_value.value_id',
                []
            )->where(
                'images.disabled = 0 AND image_value.disabled = 0 AND image_value.entity_id = [product_id]'
            );
    }

Leave a Reply

Your email address will not be published. Required fields are marked *