{"id":2287,"date":"2023-09-06T10:51:20","date_gmt":"2023-09-06T10:51:20","guid":{"rendered":"https:\/\/meetanshi.com\/blog\/resize-specific-product-image-in-magento-2-using-command\/"},"modified":"2025-03-25T06:38:14","modified_gmt":"2025-03-25T06:38:14","slug":"resize-specific-product-image-in-magento-2-using-command","status":"publish","type":"post","link":"https:\/\/meetanshi.com\/blog\/resize-specific-product-image-in-magento-2-using-command\/","title":{"rendered":"How to Resize Specific Product Image in Magento 2 Using Command"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">In Magento 2, the product images are resized and stored in the cache after the product is saved. The storefront displays the images from the cache. If you\u2019ve imported products or modified the images in the cache, you can use the Magento 2 image resize command to resize all images in Magento 2.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">But what if you want to resize only specific product images in Magento 2?<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The default image resize command in Magento 2\u00a0 has no other parameters and does not support resizing only specific images. However, this can be accomplished by creating a\u00a0<a href=\"https:\/\/developer.adobe.com\/commerce\/docs\/\" target=\"_blank\" rel=\"noreferrer noopener\">CLI command in Magento 2<\/a>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">I created a&nbsp;<a href=\"https:\/\/meetanshi.com\/blog\/create-console-command-in-magento-2\/\" target=\"_blank\" rel=\"noreferrer noopener\">custom console command in Magento 2<\/a>&nbsp;to resize specific product images. In this post, you\u2019ll find the complete steps + code to create the command.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Let\u2019s learn to&nbsp;<em><strong>resize specific product image in Magento 2 using command<\/strong><\/em>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Create a Custom Console Command to Resize Product Images by ID in Magento 2<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">To create a custom console command in Magento 2, we\u2019ll need to create a module and define it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Follow these steps to do that:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Create a&nbsp;<strong>module.xml<\/strong>&nbsp;file at&nbsp;<em><strong>app\/code\/Vendor\/Extension\/etc\/<\/strong><\/em>&nbsp;directory and add the following code:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;?xml version=\"1.0\"?>\n&lt;config xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:framework\/Module\/etc\/module.xsd\">\n    &lt;module name=\"Meetanshi_SingleProductImageResize\" setup_version=\"1.0.0\">\n        &lt;sequence>\n            &lt;module name=\"Magento_Catalog\"\/>\n        &lt;\/sequence>\n    &lt;\/module>\n&lt;\/config><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Now, create&nbsp;<strong>di.xml<\/strong>&nbsp;file in the same directory with the following code:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;?xml version=\"1.0\"?>\n&lt;config xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\"\n    xsi:noNamespaceSchemaLocation=\"urn:magento:framework:ObjectManager\/etc\/config.xsd\">\n    &lt;type name=\"Magento\\Framework\\Console\\CommandListInterface\">\n        &lt;arguments>\n            &lt;argument name=\"commands\" xsi:type=\"array\">\n                &lt;item name=\"imagesResizeCommand\" xsi:type=\"object\">\n                    Meetanshi\\SingleProductImageResize\\Console\\Command\\ImagesResizeCommand\n                &lt;\/item>\n            &lt;\/argument>\n        &lt;\/arguments>\n    &lt;\/type>\n    &lt;type name=\"Meetanshi\\SingleProductImageResize\\Console\\Command\\ImagesResizeCommand\">\n        &lt;arguments>\n            &lt;argument name=\"imageResizeScheduler\" xsi:type=\"object\">\n                Magento\\MediaStorage\\Service\\ImageResizeScheduler\\Proxy\n            &lt;\/argument>\n        &lt;\/arguments>\n    &lt;\/type>\n&lt;\/config><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Register the module by adding&nbsp;<strong>registration.php<\/strong>&nbsp;file in the&nbsp;<em><strong>app\/code\/Vendor\/Extension\/<\/strong><\/em>&nbsp;directory with the following code:<br>ImageResizeCommand.php at the&nbsp;<em><strong>app\/code\/Vendor\/Extension\/Console\/Command\/<\/strong><\/em>&nbsp;directory and add the following code:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;?php\n \ndeclare(strict_types=1);\n \nnamespace Meetanshi\\SingleProductImageResize\\Console\\Command;\n \nuse Magento\\Framework\\App\\Area;\nuse Magento\\Framework\\App\\State;\nuse Magento\\Framework\\Console\\Cli;\nuse Magento\\MediaStorage\\Service\\ImageResize;\nuse Magento\\MediaStorage\\Service\\ImageResizeScheduler;\nuse Symfony\\Component\\Console\\Helper\\ProgressBar;\nuse Symfony\\Component\\Console\\Helper\\ProgressBarFactory;\nuse Symfony\\Component\\Console\\Input\\InputInterface;\nuse Symfony\\Component\\Console\\Output\\OutputInterface;\nuse Symfony\\Component\\Console\\Input\\InputOption;\nuse Symfony\\Component\\Console\\Command\\Command;\nuse Symfony\\Component\\Console\\Input\\InputArgument;\nuse Magento\\Framework\\DB\\Query\\Generator;\nuse Magento\\Framework\\DB\\Select;\nuse Magento\\Framework\\App\\ResourceConnection;\nuse Magento\\Catalog\\Model\\ResourceModel\\Product\\Gallery;\nuse Magento\\Catalog\\Model\\ResourceModel\\Product\\Image as ProductImage;\n \n\/**\n* Resizes product images according to theme view definitions.\n*\/\n \nclass ImagesResizeCommand extends Command\n{\n    \/**\n    * Asynchronous image resize mode\n    *\/\n \n    const ASYNC_RESIZE = 'async';\n \n    \/**\n    * @var ImageResizeScheduler\n    *\/\n \n    private $imageResizeScheduler;\n \n    \/**\n    * @var ImageResize\n    *\/\n \n    private $imageResize;\n \n    \/**\n    * @var State\n    *\/\n \n    private $appState;\n \n    \/**\n    * @var ProgressBarFactory\n    *\/\n \n    private $progressBarFactory;\n \n    \/**\n    * @var ProductImage\n    *\/\n \n    private $productImage;\n \n    \/**\n    * @var ResourceConnection\n    *\/\n \n    private $resourceConnection;\n \n    public function __construct(\n        Generator $generator,\n        ImageResizeScheduler $imageResizeScheduler,\n        State $appState,\n        ImageResize $imageResize,\n        ProgressBarFactory $progressBarFactory,\n        ProductImage $productImage,\n        ResourceConnection $resourceConnection\n    )\n    {\n        parent::__construct();\n        $this->batchQueryGenerator = $generator;\n        $this->imageResizeScheduler = $imageResizeScheduler;\n        $this->appState = $appState;\n        $this->imageResize = $imageResize;\n        $this->progressBarFactory = $progressBarFactory;\n        $this->productImage = $productImage;\n        $this->resourceConnection = $resourceConnection;\n    }\n \n    \/**\n    * @inheritdoc\n    *\/\n    protected function configure()\n    {\n        $this->setName('image:product:resize')\n            ->setDescription('Single Product Image Resized')\n            ->setDefinition($this->getOptionsList());\n        $this->addOption(\n            'product_id',\n            null,\n            InputOption::VALUE_REQUIRED,\n            'Add Product ID'\n        );\n    }\n \n    \/**\n    * Image resize command options list\n    * @return array\n    *\/\n    private function getOptionsList()\n    {\n        return [\n            new InputOption(\n                self::ASYNC_RESIZE,\n                'a',\n                InputOption::VALUE_NONE,\n                'Resize image in asynchronous mode'\n            ),\n        ];\n    }\n \n    \/**\n    * @inheritdoc\n    * @param InputInterface $input\n    * @param OutputInterface $output\n    *\/\n \n    protected function execute(InputInterface $input, OutputInterface $output)\n    {\n        $product_id = $input->getOption('product_id');\n        $result = $this->executeAsync($output, $product_id);\n        return $result;\n    }\n \n    \/**\n    * Schedule asynchronous image resizing\n    * @param OutputInterface $output\n    * @param int $product_id\n    * @return int\n    *\/\n \n    private function executeAsync(OutputInterface $output, $product_id)\n    {\n        try{\n            $errors = [];\n            $this->appState->setAreaCode(Area::AREA_GLOBAL);\n \n            \/** @var ProgressBar $progress *\/\n            $progress = $this->progressBarFactory->create(\n                [\n                    'output' => $output,\n                    'max' => $this->getCountUsedProductImages($product_id)\n                ]\n            );\n            $progress->setFormat(\n                \"%current%\/%max% [%bar%] %percent:3s%% %elapsed% %memory:6s% \\t| &lt;info>%message%&lt;\/info>\"\n            );\n            if ($output->getVerbosity() !== OutputInterface::VERBOSITY_NORMAL){\n                $progress->setOverwrite(false);\n            }\n            $productImages = $this->getUsedProductImages($product_id);\n            foreach ($productImages as $image)\n            {\n                $result = $this->imageResizeScheduler->schedule($image['filepath']);\n                if (!$result){\n                    $errors[$image['filepath']] = 'Error image scheduling: ' . $image['filepath'];\n                }\n                $progress->setMessage($image['filepath']);\n                $progress->advance();\n            }\n        }\n        catch (\\Exception $e){\n            $output->writeln(\"&lt;error>{$e->getMessage()}&lt;\/error>\");\n            return Cli::RETURN_FAILURE;\n        }\n        $output->write(PHP_EOL);\n        if (count($errors)){\n            $output->writeln(\"&lt;info>Product images resized with errors:&lt;\/info>\");\n            foreach ($errors as $error){\n                $output->writeln(\"&lt;error>{$error}&lt;\/error>\");\n            }\n        }\n        else{\n            $output->writeln(\"&lt;info>Product images scheduled successfully&lt;\/info>\");\n        }\n        return Cli::RETURN_SUCCESS;\n    }\n \n    \/**\n    * Get used product images.\n    * @param int $product_id\n    * @return \\Generator\n    *\/\n \n    private function getUsedProductImages($product_id)\n    {\n        $batchSelectIterator = $this->batchQueryGenerator->generate(\n            'value_id',\n            $this->getUsedImagesSelect($product_id),\n            100,\n            \\Magento\\Framework\\DB\\Query\\BatchIteratorInterface::NON_UNIQUE_FIELD_ITERATOR\n        );\n        foreach ($batchSelectIterator as $select){\n            foreach ($this->resourceConnection->getConnection()->fetchAll($select) as $key => $value){\n                yield $key => $value;\n            }\n        }\n    }\n \n    \/**\n    * Return select to fetch all used product images.\n    * @param int $product_id\n    * @return Select\n    *\/\n \n    private function getUsedImagesSelect($product_id)\n    {\n        $query = 'images.disabled = 0 AND image_value.disabled = 0 AND image_value.entity_id = '.$product_id;\n        return $this->resourceConnection->getConnection()->select()->distinct()\n        ->from(\n            ['images' => $this->resourceConnection->getTableName(Gallery::GALLERY_TABLE)],\n            'value as filepath'\n        )->joinInner(\n            ['image_value' => $this->resourceConnection->getTableName(Gallery::GALLERY_VALUE_TABLE)],\n            'images.value_id = image_value.value_id',\n            []\n        )->where($query);\n    }\n \n    \/**\n    * Get the number of unique and used images of products.\n    * @param int $product_id\n    * @return int\n    *\/\n \n    private function getCountUsedProductImages($product_id)\n    {\n        $select = $this->getUsedImagesSelect($product_id)\n        ->reset('columns')\n        ->reset('distinct')\n        ->columns(\n            new \\Zend_Db_Expr('count(distinct value)')\n        );\n        return (int) $this->resourceConnection->getConnection()->fetchOne($select);\n    }\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">That\u2019s it. You can now use this custom module to resize specific product images in Magento 2 using command.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How to Resize Specific Product Images in Magento 2 Using Command<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">You can use the following command to resize specific product images in Magento 2:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>php bin\/magento meet:product:resize --product_id=33<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You can pass any product ID in the command above and resize a specific image in Magento 2.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">&amp; that\u2019s it!<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Loved this post? Please share it with your friends on social media &amp; spread the knowledge.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In case you\u2019ve any doubts or queries, feel free to comment.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Thank You!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In Magento 2, the product images are resized and stored in the cache after the product is saved. The storefront displays the images from the&#8230;<\/p>\n","protected":false},"author":13,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[34],"tags":[],"class_list":["post-2287","post","type-post","status-publish","format-standard","hentry","category-magento"],"acf":[],"_links":{"self":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/2287","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/users\/13"}],"replies":[{"embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/comments?post=2287"}],"version-history":[{"count":3,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/2287\/revisions"}],"predecessor-version":[{"id":10963,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/2287\/revisions\/10963"}],"wp:attachment":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/media?parent=2287"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/categories?post=2287"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/tags?post=2287"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}