Skip to content

Magento2 – How to get Image Size?

For Image optimisation, I want’t to get Product Image Size. (Either in KB or MB etc.)

enter image description here

Ex: 6 KB, 6KB,5KB etc.

I am using following code on root path.

<?php

error_reporting(1);
ini_set('max_execution_time', 0);
use MagentoFrameworkAppBootstrap;

require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$instance = MagentoFrameworkAppObjectManager::getInstance();
$state = $objectManager->get('MagentoFrameworkAppState');
$state->setAreaCode('frontend');
$product_collections = $instance ->get('MagentoCatalogModelResourceModelProductCollectionFactory');
$collections = $product_collections->create();
$i = 0;
foreach ($collections as $product) {

    $objectManager = MagentoFrameworkAppObjectManager::getInstance(); 

    $productRepository = $objectManager->get('MagentoCatalogModelProductRepository');
    $productObj = $productRepository->get($product->getSku());

    echo "<b>".$productObj->getName()."</b>";    
        echo "<br>";

        $i++;
    $objectManager = MagentoFrameworkAppObjectManager::getInstance();
    $directory = $objectManager->get('MagentoFrameworkFilesystemDirectoryList');
    $mediaPath = $directory->getPath('media');

    $product_id = $productObj->getId();
    $product = $objectManager->create('MagentoCatalogModelProduct')->load($product_id);

    $galleryReadHandler = $objectManager->get('MagentoCatalogModelProductGalleryReadHandler');
    $galleryReadHandler->execute($product);
    $images = $product->getMediaGalleryImages();

        foreach($images as $image){
            echo "<pre>";print_r($image);echo "</pre>";
         $temp = $mediaPath."/catalog/product".$image->getFile();
         //echo "<pre>"; print_r($temp); echo "</pre>";
         echo $temp;
         echo "<br>";
        }    
}
echo "Total Products: ".$i;